【问题标题】:String expansion does not work in PowerShell when using Invoke-Command on remote computer在远程计算机上使用 Invoke-Command 时,字符串扩展在 PowerShell 中不起作用
【发布时间】:2011-06-16 06:05:38
【问题描述】:

为什么第一个示例不等同于第二个示例?

1:

$volumeNum = 2
Invoke-Command -ComputerName $IP -Credential $GuestVM -ScriptBlock {"select volume $volumeNum" | diskpart}

2:

Invoke-Command -ComputerName $IP -Credential $GuestVM -ScriptBlock {"select volume 2" | diskpart}

为什么 powershell 不评估

"选择卷 $volumeNum"

选择第 2 卷

【问题讨论】:

    标签: string variables powershell


    【解决方案1】:

    通过Invoke-Command 执行的脚本块无权访问当前环境状态,它在单独的进程中运行。如果您在本地计算机上运行该命令,它将起作用。

    问题是字符串"select volume $volumeNum" 在远程机器上执行之前不会被评估。所以它在远程机器上寻找当前进程的环境中的值,而$volumeNum没有在那里定义。

    PowerShell 提供了一种通过Invoke-Command 传递参数的机制。这可以从我的本地机器到远程:

    Invoke-Command -ComputerName $ip -ScriptBlock { param($x) "hello $x" } -ArgumentList "world"
    

    我相信类似的方法对你有用:

    Invoke-Command -ComputerName $IP -Credential $GuestVM -ScriptBlock {param($volumeNum) "select volume $volumeNum" | diskpart} -ArgumentList $volumeNum
    

    【讨论】:

      【解决方案2】:

      脚本块被编译。这意味着它们中的变量引用在编译时是固定的。您可以通过将脚本块的创建推迟到运行时来解决此问题:

      $sb = [scriptblock]::create("select volume $volumeNum | diskpart")
      Invoke-Command -ComputerName $IP -Credential $GuestVM -ScriptBlock $sb
      

      【讨论】:

        【解决方案3】:

        其他人的进一步说明:GetNewClosure 也不起作用。

        $filt = "*c*"
        $cl = { gci D:\testdir $filt }.GetNewClosure()
        & $cl
        
        # returns 9 items
        Invoke-command -computer mylocalhost -script $cl
        # returns 9 items
        Invoke-command -computer mylocalhost -script { gci D:\prgs\tools\Console2 $filt }
        # returns 4 items
        Invoke-command -computer mylocalhost -script { gci D:\prgs\tools\Console2 "*c*" }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多