我试图从网络上的几台机器获取一些信息,但我得到了本地机器的大量条目..对于文本文件中的每个条目,我从本地机器获得一个条目。
任何知道我哪里出错了.. winrm 在远程计算机上配置并正在运行。
$Username = Read-Host "Please enter Username"
$Password = read-host "please enter Password"
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
$computers = gc c:testfile.txt
foreach ($Computer in $computers)
{
Invoke-command -ComputerName $computers -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | out-file c:testoutput.txt -append}
}
cls
提前致谢:)
Invoke-Command
将采用一个数组作为 ComputerName 参数,因此您可以使用 $computers
而不是使用 foreach 循环(假设文件中每行都有一个计算机名称(。
我还使用Get-Credential
一次性提示输入完整凭据,而不是单独询问用户名和密码。
$Cred = Get-Credential
$computers = Get-Content c:testfile.txt
Invoke-Command -ComputerName $computers -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | Out-File c:testoutput.txt -Append}
您只看到c:testoutput.txt
计算机信息的原因是,ipconfig
命令的输出正在保存到远程计算机...因此,您将在运行命令的每台计算机上都有一个c:testoutput.txt
文件。
编辑:
要获取每个远程命令的输出并将其保存到本地计算机,只需将Out-File
移到Invoke-Command
之外,如下所示:
$Cred = Get-Credential
$computers = Get-Content c:testfile.txt
Invoke-Command -ComputerName $computers -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'"} | Out-File c:testoutput.txt -Append
问题是您正在逐个迭代,但您没有逐个传递给 invoke-command,$computer foreach 循环中一次将具有每个值。
取而代之的是:
foreach ($Computer in $computers)
{
Invoke-command -ComputerName $computers -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | out-file c:testoutput.txt -append}
}
这样做:
foreach ($Computer in $computers)
{
Invoke-command -ComputerName $computer -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | out-file c:testoutput.txt -append}
}
进一步改进:
你不必给Invoke-Expression -Command:"cmd.exe /c 'ipconfig'"
取而代之的是,您可以直接在脚本块中使用ipconfig。