Hello stackoverflow team, please could You assist on following question: How to pass correctly parameter to new PS instance run by Start-Process using arguments or ideally parameters.
I have found only one ugly way interpreting-concatenating string variable to script. This actually works but e.g. adds some spaces to string:
#ugly variable concatenation to script, but adds spaces
$whatToSay="Hello World"
$process = Start-Process powershell "-Command",'
$greeting=\"',$whatToSay,'\"
Write-Output \"I say: $greeting\"
Read-Host
exit ($greeting -eq \" Hello World \")
' -Wait -PassThru
Write-Output "Process exited with exit code: $($process.ExitCode)"
Result (note added spaces before and after "Hello World"):
I say: Hello World
Process exited with exit code: 1
Following two examples are based on powershell.exe /? (help):
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
...
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
Using Script-Block:
#does not work script-block argument
$whatToSay="Hello World"
$process = Start-Process powershell "-Command",{
$greeting=$args[0]
Write-Output \"I say: $greeting\"
Read-Host
exit ($greeting -eq 'Hello World')
},"-args","$whatToSay" -Wait -PassThru
Write-Output "Process exited with exit code: $($process.ExitCode)"
Using Script-String:
#does not work script-string parameter
$whatToSay="Hello World"
$process = Start-Process powershell "-Command",'
param ($greeting)
Write-Output \"I say: $greeting\"
Read-Host
exit($greeting -eq \"Hello World\")
',"-greeting","$whatToSay" -Wait -PassThru
Write-Output "Process exited with exit code: $($process.ExitCode)"
Both results:
I say:
Process exited with exit code: 0
Thank You for tips.