我正在尝试在远程计算机上运行我想要的任何命令。示例:gpupdate / force或copy 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
为什么不呢?
答案 0 :(得分:2)
问题是您要在脚本块中将字符串变量传递给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
答案 1 :(得分:0)
尝试像这样运行脚本:
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