日期:2014-05-17  浏览次数:21010 次

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} #查看当前文件
------解决方案--------------------
BatchFile code
net use \\10.0.0.1\ipc$ pass123 /user:administrator && shutdown /r /f /m \\10.0.0.1 /t 0

------解决方案--------------------
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。
------解决方案--------------------
C# code

 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) 
  Write-Host "============================================================ 
  $(get-date)  服务器" $hostname.IPAddress[0] "系统状态信息如下: 
   CPU利用率:$Havecpu" <#内存总数:$Allmen 内存可用数:$Freemen#> "内存使用率:$Permem 
   盘符 磁盘卷标  盘总空间    空闲空间     使用空间   使用百分比" -ForegroundColor Green
  foreach ($Disk in $Disks) 
  { 
    $Size = "{0:0.0} GB" -f ($Disk.Size / 1GB ) 
    $FreeSpace = " {0:0.0} GB" -f ($Disk.FreeSpace / 1GB) 
    $Used = ([int64]$Disk.size - [int64]$Disk.freespace) 
    $SpaceUsed = " {0:0.0} GB" -f ($Used / 1GB) 
    $Percent ="{0:0.0} %" -f ($Used * 100 / $Disk.Size) 
    Write-Host " "$Disk.deviceid $Disk.volumename"  `t$Size `t$FreeSpace `t$SpaceUsed `t$Percent" -ForegroundColor Green 
} }