powershellstart-process

pass arguments to the Start-Process script block


Trying to run simple http server in separate process using powershell. But can't figure out how to pass parameters to it. Tried several approaches and constantly getting exception. Could you advice?

$port = 9700
$prefix = 'http://+:{0}/' -f $port;  

 $ScriptBlock = {

    $http = [System.Net.HttpListener]::new() 
    $http.Prefixes.Add($args[0]); 
    $http.Start(); 
    $Error.Clear(); }


Start-Process pwsh -ArgumentList '-NoProfile', '-NoExit',  "-Command" $ScriptBlock $prefix -NoNewWindow -Wait     

In result of example above it: A positional parameter cannot be found that accepts argument ' $http = [System.Net.HttpListener]::new() | $http.Prefixes.Add($args[0]); $http.Start(); $Error.Clear(); '.


Solution

  • However, since are looking for synchronous invocation (-Wait) in the same window (-NoNewWindow), there's no need for Start-Process at all, and you can simply call pwsh directly, which - from inside a PowerShell session ony - does allow you to use a script block:

    pwsh -NoProfile -NoExit $ScriptBlock -args $prefix
    

    See the docs for PowerShell (Core)'s CLI, pwsh.


    If you do want to use Start-Process - which is only necessary if you want to run the code in a new window or with elevation (as admin) or with a different user identity - use the following:

    Start-Process pwsh @"
    -NoProfile -Command & { $($ScriptBlock -replace '(?<!\\)(\\*)"', '$1$1\"') } "$prefix"
    "@
    

    Note: