Board logo

标题: [转载代码] [PowerShell每日技巧]远程执行代码(20131203) [打印本页]

作者: DAIC    时间: 2013-12-4 11:38     标题: [PowerShell每日技巧]远程执行代码(20131203)

In a domain environment, PowerShell remoting is working almost out of the box. All you might have to do is enable Remoting on target machines (beginning with Server 2012, PowerShell remoting is enabled by default for Administrators).

In PowerShell 3.0, to enable remoting manually, that's all (Administrator privileges required):

PS> Enable-PSRemoting -SkipNetworkProfileCheck -Force


You do not need to configure anything on the client side (the machine that is going to send commands).

Next, any Administrator can send PowerShell code to the enabled machine and have it execute. This example would list all the PowerShell-related processes from the target machine:
  1. $code =
  2. {
  3.     Get-Process -Name powershell*, wsmprovhost -ErrorAction SilentlyContinue
  4. }
  5. $list = 'server1', 'w2k12-niki', 'pc11box'
  6. Invoke-Command -ScriptBlock $code #-ComputerName $list
复制代码
When you run the code as-is, Invoke-Command runs the script block stored in $code on your own machine.

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    323      25    36392      36980   201     0.45   2060 powershell
    270      22    26208      35512   184     0.41   5520 powershell


It reports all running instances of the PowerShell console, the ISE PowerShell editor, and any hidden PowerShell remoting sessions initiated from someone else on your machine.

Once you uncomment the -ComputerName parameter, the code will run on all of the machines listed in $list variable. Make sure they exist and have remoting enabled. When you receive data from remote computers, PowerShell automatically adds a "PSComputerName" property with the name of the computer that sent back the information.

http://powershell.com/cs/blogs/tips/archive/2013/12/03/executing-code-remotely.aspx




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2