在 Invoke-Command 中使用全局变量

问题描述 投票:0回答:1

我试图找出一种在 Invoke-Command 中使用全局变量的方法,但没有成功。 我尝试了一些帖子,但它们在这个用例中不起作用。

所以我有一个像这样的脚本:

$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 ...

此脚本的想法是拥有一个 powershell 会话,该会话“点”该脚本,然后单独使用这些函数。出于我的用例的简单性原因,这是必要的。

我似乎无法使用

$global:remoteLogFilePath
中的
Invoke-Command
。 我尝试了像
using
这样的
$using:remoteLogFilePath
范围,但没有成功。实际上,如果变量是本地变量,则使用作用域可以工作,因此我可能可以将全局变量复制到本地变量,但随后我必须在每个使用它的函数中执行此操作。而且功能还蛮多的。

有人可以帮忙吗?

powershell invoke-command
1个回答
0
投票

经过一番尝试,我发现了:

$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 ...

事实证明,将

-ArgumentList
与全局变量一起使用,然后在 Invoke-Command 的本地范围内使用
using
即可完成这项工作。

© www.soinside.com 2019 - 2024. All rights reserved.