日期:2014-05-16  浏览次数:20802 次

powershell在远程主机上执行命令,请指点
我想在一台主机A上通过powershell连接到主机B,并在B上执行cmd命令。

已知B的计算机名、ip,用户名和密码,B上没有安装powershell,A和B不在域里面。

我的想法是通过连接WMI服务来完成,但没找到方法,如果有朋友知道怎么搞麻烦说下。如果还可以使用别的方法请讲一下怎么实现。

------解决方案--------------------
在别的机器上也需要装上远程管理框架
http://support.microsoft.com/kb/968929
下载,安装对应的管理框架核心Windows Management Framework Core)
启动winrm
winrm quickconfig -q
设置信任主机
winrm set winrm/config/client @{TrustedHosts="192.168.8.8"}
这样后你就能通过powershell连接到另一台机器上了。

$c = Get-Credential #登录验证
$cname = "192.168.8.10" #这里是你要连接的那台机器
$ser1=New-PSSession -ComputerName $cname -Credential $c #建立一个连接
#下面就可以在这台机器做操作了
invoke-command -session $ser1 -scriptblock {net stop w32Time} #停止时间服务
invoke-command -session $ser1 -scriptblock {net start w32Time} #启动时间服务
invoke-command -session $ser1 -scriptblock {dir} #查看当前文件
------解决方案--------------------
[code=BatchFile]net use \\10.0.0.1\ipc$ pass123 /user:administrator && shutdown /r /f /m \\10.0.0.1 /t 0
[/code]
------解决方案--------------------
powershell 就是专门为批量管理而设计的,我管理着好几百台呢。
$cname=Get-Content "D:\My Documents\My Documents\works\server1.txt"

server1.txt是一个服务器ip列表。
powershell可以实现你需要的任何管理功能。
invoke-command -session $ser1 -scriptblock {在这个大括号里,你可以做很多事情,在远程机器上。}
前提是对方安装了Windows Management Framework Core。
------解决方案--------------------

 invoke-command -session $ser1 -scriptblock {$cpu=((get-counter -counter "\processor(_total)\% processor time").CounterSamples
------解决方案--------------------
where {$_.InstanceName -eq "_total" }).CookedValue
  $men = gwmi  win32_OperatingSystem 
  $devid=gwmi Win32_NetworkAdapter 
------解决方案--------------------
Where-Object{$_.NetConnectionStatus -eq 2}
------解决方案--------------------
 Select-Object DeviceID 
  $hostname=ForEach ($id in $devid ){gwmi Win32_NetworkAdapterConfiguration
------解决方案--------------------
where {$_.index -eq $id.DeviceID -and $_.DefaultIPGateway -ne $null}}
  $Disks = gwmi  win32_logicaldisk -filter "drivetype=3" 
  $Havecpu = "{0:0.0} %" -f $cpu 
  $Allmen = "{0:0.0} MB" -f ($men.TotalVisibleMemorySize  / 1KB) 
  $Freemen = "{0:0.0} MB" -f ($men.FreePhysicalMemory  / 1KB) 
  $Permem =  "{0:0.0} %" -f ((($men.TotalVisibleMemorySize-$men.FreePhysicalMemory)/$men.TotalVisibleMemorySize)*100)