0

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?

0

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.