我需要使用SysInternal工具在多个Windows服务器上远程运行powershell命令,但我尝试了很多但似乎无法工作。任何帮助都非常感谢。
Servers.csv(文件内容)
10.10.10.100
10.0.0.111
代码:
$List = Import-CSV -Path "C:\Users\javed\Desktop\New\servers.csv"
foreach ($entry in $List) {
if (test-Connection -Cn $($entry.Name) -quiet) {
& C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$($entry.Name)\Admin" -p 'P@ssword' -accepteula cmd /c " HostName >> C:\Users\javed\Desktop\New\Script.log"
} else {
"$computer is not online" >> C:\Users\javed\Desktop\New\Script.log
}
}
输出:
PS C:\Users\javed> C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
psexec.exe : The handle is invalid.
At C:\Users\javed\Desktop\New\Change-NetworkRoute.ps1:26 char:9
+ & C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u "$(
...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The handle is invalid.:String) [], Re
moteException
+ FullyQualifiedErrorId : NativeCommandError
Connecting to 10.10.10.100...Couldn't access 10.10.10.100:
Connecting to 10.10.10.100...
PS C:\Users\javed>
答案 0 :(得分:1)
显然您的命令行没有完全评估,请注意PSExec在错误中显示\\$($entry.Name)
而不是实际名称。
解决此问题的正确方法是将第一个put命令变为变量,显示变量,然后执行它:
$CommandLine = "C:\Users\javed\Downloads\PsTools\psexec.exe \\$($entry.Name) -u ..."
Write-Host $CommandLine # Confirm that this is the command line you expect
if (test-Connection -Cn $($entry.Name) -quiet) {
&$CommandLine
} else {
无论如何,使用外部命令行作为PSExec包含凭据来实现这样的事情是一个坏主意。相反,我会使用WMI来检索服务器的实际名称。像这样:
$SPAdmin = "$($entry.Name)\Admin"
$Password = "P@ssword" | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $SPAdmin, $Password
$Computer = Get-WmiObject -Class Win32_Computersystem -ComputerName $entry.Name -Credential $Credential
Write-Host $Computer.Name