Search code examples
powershellstart-processscriptblock

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.


Solution

  • 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.