Share via


Use Variables created in script block outside of script block

Question

Monday, April 13, 2015 6:36 PM

hello

I have a code like:

 $command= { param($p1,$p2)  if (Test-Path "D:\$p1") {
 $s=$p1+ "_" +$p2 }

} Invoke-Command -session $sesion -ScriptBlock $command -ArgumentList 1,2

here session is already created with remote server. Invoke-Command runs that script block on a remote server.

Now I want to use that variable $s after invoke-command like

$command= { param($p1,$p2)
   if (Test-Path "D:\$p1") {  $s=$p1+ "_" +$p2 }

} Invoke-Command -session $sesion -ScriptBlock $command -ArgumentList 1,2

write-host $s

if ($s -eq "ZTE_3G") {

Write-host True

} else {

write host false

}

But here value of variable $s comes as null.

Could you please help me how can i use value of that vairable?

All replies (3)

Monday, April 13, 2015 7:09 PM âś…Answered | 2 votes

You need to return $s in your scriptblock and then save the output of Invoke-Command to a variable in order to test.

Something like this may work:

$command= { 
    param($p1,$p2)
    if (Test-Path "D:\$p1") {
        $s=$p1+ "_" +$p2
    }
    $s
}
$s = Invoke-Command -session $sesion -ScriptBlock $command -ArgumentList 1,2

write-host $s

If ($s -eq "ZTE_3G") {
    $True
} else {
    $False
}

Boe Prox
Blog | Twitter
PoshWSUS | PoshPAIG | PoshChat | PoshEventUI | PoshRSJob
PowerShell Deep Dives Book


Friday, April 17, 2015 10:19 AM

Hi Boe,

Thanks for your reply.

I have tried your suggestion but I am sorry to say that it's not working.

Could you please check and let me know if there is another method?

Thakns


Monday, April 27, 2015 9:30 AM

Hi Jaadoo,

If you want to get the value of the variable "$s", I think you can apply Boe's script, I tested the script and post the result as below:

Please note to make sure the variable $s isn't null, we need to make sure the folder path "C:\a" exist on the remote server "VM3" in my example.

If there is anything else regarding this issue, please feel free to post back.

Best Regards,

Anna Wang

Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]