PowerShell:远程执行控制台应用程序失败

PowerShell: remote execution of console application fails

当 运行 在 powershell 中执行以下代码片段时,我看到一个错误(创建管道时出错)。有人可以帮我吗?

# This file contains the list of servers you want to copy files/folders to
$computers = gc "C:\folder1\sub1\server.txt"
 
# This is the file/folder(s) you want to copy to the servers in the $computer variable
$source = "\usa-chicago1\c$\Program Files\"
 
# The destination location you want the file/folder(s) to be copied to
$destination = "c$\July\"
$username = 'harry'
$password = 'hqwtrey'
$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred  = New-Object Management.Automation.PSCredential ($username, $secpw)


foreach ($computer in $computers) {
if ((Test-Path -Path \$computer$destination)) {

     Write-Output "INSIDE IF BLOCK"
    #Copy-Item $source -Destination \$computer$destination -Recurse
    Invoke-Command -Computername $computer -ScriptBlock { & '\$computer\July\' --service install --config-directory '\$computer\July\conf' } 
    Invoke-Command -Computername $computer -ScriptBlock { & net start telegraf } 
} 
else {
    
    Write-Output $computer
    New-Item -Path "\$computer\july\" -ItemType Directory
    Write-Output \$computer$destination
    Copy-Item $source -Destination \$computer$destination -Recurse
}
}
 
  • 传递给Invoke-Command -ComputerName ...的脚本块远程执行,远程会话对调用者的变量一无所知;通过 $using: 范围引用调用者的变量 - 参见 .

  • 变量引用只能嵌入在引号字符串("...")中,而 引号字符串 ('...') 将其内容 逐字处理 - 请参阅 this answer 的底部部分以了解 PowerShell 字符串文字的概述。

因此:

Invoke-Command -Computername $computer -ScriptBlock { 
  & "\$using:computer\July\Telegraf\telegraf" --service install --config-directory "\$using:computer\July\Telegraf\conf"
} 

至于你看到的莫名其妙的错误信息RuntimeException: An error occurred while creating the pipeline.:

这应该被认为是一个 bug;你应该看到 &: The term '\$computer\July\Telegraf\telegraf' is not recognized as the name of a cmdlet, function, script file, or operable program.,就像你使用 local 调用一样。

该错误仅出现在 UNC 路径中,正在 this GitHub issue 中进行跟踪。