使用powershell进行远程管理
我试图从网络上的几台机器上获取一些信息,但我得到了本地机器的大量条目。。对于文本文件中的每个条目,我都从本地机器获得一个条目 知道我哪里出了问题吗。。winrm在远程计算机上配置并正在运行使用powershell进行远程管理,powershell,Powershell,我试图从网络上的几台机器上获取一些信息,但我得到了本地机器的大量条目。。对于文本文件中的每个条目,我都从本地机器获得一个条目 知道我哪里出了问题吗。。winrm在远程计算机上配置并正在运行 $Username = Read-Host "Please enter Username" $Password = read-host "please enter Password" $pass = ConvertTo-SecureString -AsPlainText $Password -Force $C
$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:\test\file.txt
foreach ($Computer in $computers)
{
Invoke-command -ComputerName $computers -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | out-file c:\test\output.txt -append}
}
cls
提前感谢:)问题是您正在逐个迭代,但没有逐个传递给invoke命令,$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:\test\output.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:\test\output.txt -append}
}
进一步改进:
您不必给出Invoke Expression-命令:“cmd.exe/c'ipconfig'”
您可以在scriptblock中直接使用ipconfig
Invoke命令
将为ComputerName参数获取一个数组,因此您可以使用$computers
而不是使用foreach循环(假设文件中每行有一个计算机名)
我还使用了Get Credential
一次提示输入完整的凭证,而不是单独要求输入用户名和密码
$Cred = Get-Credential
$computers = Get-Content c:\test\file.txt
Invoke-Command -ComputerName $computers -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'" | Out-File c:\test\output.txt -Append}
在c:\test\output.txt
中只看到一台计算机信息的原因是ipconfig
命令的输出正在保存到远程计算机。。。因此,在运行命令的每台计算机上都有一个c:\test\output.txt
文件
编辑: 要获取每个远程命令的输出并将其保存到本地计算机,只需将
文件移出调用命令
,如下所示:
$Cred = Get-Credential
$computers = Get-Content c:\test\file.txt
Invoke-Command -ComputerName $computers -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'ipconfig'"} | Out-File c:\test\output.txt -Append
调用命令-ComputerName$computer
。singularHi Dutta,感谢您的快速响应。我只得到了一个输出,我看不出两个示例之间的区别:($computer=只给我本地机器的输出显示文件内容。文件内容是…svr01.test.loc dc01.test.locsvr01.test.loc dc01.test.loc感谢Dutta和James..$computer(单数)东西和远程机器上的test\output文件..duh!为了清楚起见,我需要在每台机器上都有一个c:\test文件夹,这样它才能在远程机器上保存输出?@NorrinRad:它的本地only@RanadipDutta谢谢大家:)@NorrinRad:不是问题,伙计。只要它符合你的要求