Using global Variable in Invoke-Command

263 Views Asked by At

I am trying to figure out a way to use a global variable in a Invoke-Command without success. There are some posts which I tried but they do not work in this use-case.

So what I have is a script like this:

$global:remoteLogFilePath = [string]::Empty

function init()
{
   $global:remoteLogFilePath = "a/pretty/valid/path"
}


function doSomething($hostName)
{
   Invoke-Command -ComputerName $hostName -ScriptBlock{$f = Get-Item $global:remoteLogFilePath;$f.length/1MB} -ArgumentList $global:remoteLogFilePath
}

# Some more functions ...

The idea of this script is to have a powershell session which "dots" the script and then uses the functions individually. This is neccessary for simplicity reasons in my use-case.

I can't seem to use the $global:remoteLogFilePath in the Invoke-Command. I tried the using scope like $using:remoteLogFilePath but no success. Actually the using scope can work if the variable is local, so I probably could just copy the global variable to a local one but then I would have to do that in every function which uses it. And its quite some functions.

Can someone help out?

1

There are 1 best solutions below

0
k_k On

After some more trying I figured it out:

$global:remoteLogFilePath = [string]::Empty

function init()
{
   $global:remoteLogFilePath = "a/pretty/valid/path"
}


function doSomething($hostName)
{
   Invoke-Command -ComputerName $hostName -ScriptBlock{$f = Get-Item $using:remoteLogFilePath;$f.length/1MB} -ArgumentList $global:remoteLogFilePath
}

# Some more functions ...

Turns out that using -ArgumentList with the global Variable and then using in the local scope of the Invoke-Command does the job.