PowerShell:控制台应用程序的远程执行失败
在powershell中运行以下代码段时,我看到一个错误(创建管道时出错)。有人能帮我吗PowerShell:控制台应用程序的远程执行失败,powershell,powershell-2.0,powershell-3.0,powershell-4.0,powershell-remoting,Powershell,Powershell 2.0,Powershell 3.0,Powershell 4.0,Powershell Remoting,在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 $comp
# 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$1'
$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命令-ComputerName…
作用域引用调用者的变量-请参阅$using:
- 变量引用只能嵌入双引号字符串(
)中,而单引号字符串(“…”
)则逐字处理其内容-有关PowerShell字符串文本的概述,请参阅的底部部分“…”
Invoke-Command -Computername $computer -ScriptBlock {
& "\\$using:computer\July\Telegraf\telegraf" --service install --config-directory "\\$using:computer\July\Telegraf\conf"
}
对于您看到的不起眼的错误消息,
RuntimeException:创建管道时出错。
:
这应该被认为是一个bug;您应该看到&:术语“\\$computer\July\Telegraf\Telegraf”不能识别为cmdlet、函数、脚本文件或可操作程序的名称。
,这与本地调用相同
正在跟踪只显示UNC路径的错误。远程执行的脚本块不知道局部变量。应在脚本块内将
$computer
替换为$using:computer
。此外,不应在要计算PowerShell变量的表达式周围使用单引号。您将需要使用双引号代替。