i have a simple question. I want to use a variable in an invoke-command and pass this to the second invoke-command. In the second invoke-command the variable is empty
here is my code:,
$WaitSeconds = 1234
Invoke-Command -ComputerName $remote -Credential $cred -ScriptBlock {
$computer = dsquery computer "DC=domain,DC=local" -o rdn
$computers = $computer -replace ('"', '')
write-host $computers
foreach ($computer in $computers) {
if ($computer -notmatch "AZUREADSSOACC")
{
Invoke-Command -ComputerName $computer -Credential $using:cred -ScriptBlock {
#### here script
shutdown -s -t $using:waitseconds
}
}
}
}
CodePudding user response:
In the second invoke-command the variable is empty
That's because the variable doesn't exist inside the calling session (the first Invoke-Command
call's execution context).
Make sure you first instruct PowerShell to copy the variable to the "outer" Invoke-Command
call:
$WaitSeconds = 1234
Invoke-Command {
# PowerShell will now copy the $WaitSeconds variable value from the calling scope to this remote session
$WaitSeconds = $using:WaitSeconds
# ...
Invoke-Command {
# This will now resolve the variable value correctly
shutdown -s -t $using:WaitSeconds
}
}
CodePudding user response:
i got it my solution is:
$WaitSeconds = 1234
Invoke-Command {
param($WaitSeconds)
$WaitSeconds = $WaitSeconds
# ...
Invoke-Command {
param($WaitSeconds)
shutdown -s -t $WaitSeconds
} -ArgumentList $WaitSeconds
} -ArgumentList $WaitSeconds