Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use foreach loop inside Invoke-Command in PowerShell?

In the below code I was using $scripts variable to iterate through a foreach loop inside the Invoke-Command statement. But $script values are not replacing properly and outcome seems to be single string as "count.sql size.sql". The foreach loop is executing properly if defined outside the Invoke-Command loop.

Is there any particular way to define foreach loop inside Invoke-Command?

$scripts = @("count.sql", "size.sql")
$user = ""
$Password = ""
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

foreach ($server in $servers) {
    Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
        Param($server, $InputFile, $scripts, $url)

        foreach ($script in $scripts) {
            echo "$script"
    } -ArgumentList "$server,"$scripts","$url"
}
like image 424
workholic Avatar asked Jun 03 '26 19:06

workholic


1 Answers

I'm going to assume that the syntax errors in your code are just typos in your question and are not present in your actual code.

The problem you describe has nothing to do with the nested foreach loop. It's caused by the double quotes you put around the arguments you pass to the invoked scriptblock. Putting an array in double quotes mangles the array into a string with the string representations of the values from the array separated by the output field separator defined in the automatic variable $OFS (by default a space). To avoid this behavior don't put variables in double quotes when there is no need to do so.

Change the Invoke-Command statement to something like this:

Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
    Param($server, $scripts, $url)
    ...
} -ArgumentList $server, $scripts, $url

and the problem will disappear.

Alternatively you could use the variables from outside the scriptblock via the using scope modifier:

Invoke-Command -ComputerName $Server -Credential $cred -ScriptBlock {
    foreach ($script in $using:scripts) {
        echo "$script"
    }
}
like image 76
Ansgar Wiechers Avatar answered Jun 05 '26 08:06

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!