Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Start-Process to start Powershell session and pass local variables

Is there a way to use the Powershell Start-Process cmdlet to start a new Powershell session and pass a scriptblock with local variables (once of which will be an array)?

Example:

$Array = @(1,2,3,4)

$String = "This is string number"

$Scriptblock = {$Array | ForEach-Object {Write-Host $String $_}}

Start-Process Powershell -ArgumentList "$Scriptblock"

Thanks.

like image 371
atownson Avatar asked Jul 21 '13 20:07

atownson


2 Answers

I'm pretty sure there's no direct way to pass variables from one PowerShell session to another. The best you can do is some workaround, like declaring the variables in the code you pass in -ArgumentList, interpolating the values in the calling session. How you interpolate the variables into the declarations in -ArgumentList depends on what types of variables. For an array and a string you could do something like this:

$command = '<contents of your scriptblock without the curly braces>'

Start-Process powershell -ArgumentList ("`$Array = echo $Array; `$String = '$String';" + $command)
like image 154
Adi Inbar Avatar answered Sep 28 '22 15:09

Adi Inbar


I was able to get this to work by joining the array with "/" to create a string and entering the scriptblock into another .ps1 script with appropriate parameters and splitting the joined string back to an array within the second script and using

Start-Process Powershell -ArgumentList "&C:\script.ps1 $JoinedArray $String"

Ugly, but it's the only way I could get it to work. Thanks for all the replies.

like image 28
atownson Avatar answered Sep 28 '22 17:09

atownson