【问题标题】:Running Invoke-Command on remote machine在远程机器上运行 Invoke-Command
【发布时间】:2019-11-19 22:02:35
【问题描述】:

我正在尝试在远程机器上运行我想要的任何命令。示例:gpupdate /force 或将 file1 复制到 file2 等...所以我有这个代码:

$ComputerName = Read-Host "Enter a remote computer name"
$RemoteCommand = Read-Host "Enter a remote command to run:  Example   gpupdate /force"

$s = New-PSSession -ComputerName $ComputerName
Invoke-Command -Session $s -ScriptBlock {$RemoteCommand}
Invoke-Command -Session $s -ScriptBlock { $? }

它运行没有错误,实际上它返回 TRUE。但是我在 c:\temp 中的文件永远不会被复制到 c:\temp\tmp

为什么不呢?

【问题讨论】:

  • 好的,我可以让它工作,但我的命令行不能使用 $variable。如果我硬编码我想在远程机器上运行的东西,它就可以工作。
  • Invoke-Command -Session $s -ScriptBlock {cmd /c dir > c:\temp\dir.txt} # 这个有效 Invoke-Command -Session $s -ScriptBlock {$RemoteCommand} # 这个不工作

标签: invoke-command


【解决方案1】:

问题是您将字符串变量传递给脚本块中的 Invoke-Command,它只计算字符串的内容。您没有向它传递带有实际命令的脚本块。 为了说明差异,请参见以下代码:

# Output is just the content of the string
$commandString = "Get-Service spooler"
Invoke-Command {$commandString}

# Output is the result of the commandlet
$scriptBlock = {Get-Service spooler}
Invoke-Command -ScriptBlock $scriptBlock

要获得您想要的结果,您可以使用[scritpblock] 加速器,如下所示:

# Output is the result of the commandlet invocation defined in the string
$commandString = "Get-Service spooler"
$scriptBlock = [scriptblock]::Create($commandString)
Invoke-Command -ScriptBlock $scriptBlock

【讨论】:

    【解决方案2】:

    尝试像这样运行脚本:

    Invoke-Command -Session $s -ScriptBlock { powershell.exe -Command "$RemoteCommand"}
    

    如果您遇到转义字符的问题,还有 -encodedCommand 开关。来自 powershell 帮助:

    # To use the -EncodedCommand parameter:   
    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    powershell.exe -encodedCommand $encodedCommand
    

    【讨论】:

      猜你喜欢
      • 2018-06-18
      • 1970-01-01
      • 2018-12-02
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多