[.net]遠端操作powerShell

  • 565
  • 0
  • 2016-12-13

Windows PowerShell可支援腳本程式命令列工具,是以.NET Framework技術為基礎,提供使用者易學好用的特性,加快程式開發的速度

透過程式對遠端主機下指令,對一些檔案搬移、自動佈署、建IIS站台等等還蠻好用的

以下介紹如何開啟遠端PowerShell

若要遠端使用PowerShell,使用帳號必須為administrator才可以

引用namespace

  •     System.Security
  •     System.Management.Automation
  •     System.Management.Automation.Runspaces

 

使用網域帳號連線:

string computerName = "computerName ";
string _account = @"Domain\account";
string _password = @"password";

var password = new System.Security.SecureString();
Array.ForEach(_password.ToCharArray(), password.AppendChar);

var connectionInfo = new WSManConnectionInfo { ComputerName = computerName };
connectionInfo.Credential = new PSCredential(_account, password);

//建立遠方主機的Runspace
using (var powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
	powershellRunspace.Open();

	using (powershell = PowerShell.Create())
	{
		powershell.Runspace = powershellRunspace;   //指定遠端的runspace

		powershell.AddScript(@"md d:\\abc");    //要執行的指令或腳本
		var result = powershell.Invoke<string>(); 
	}
}

另外 WSManConnectionInfo 也可以這樣產生

string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
var targetWsMan = new Uri(string.Format("http://{0}:5985/wsman", computerName));
var cred = new PSCredential(_account, passing);
var connectionInfo = new WSManConnectionInfo(targetWsMan, shell, cred);

 

 

 

使用本機帳號連線:

首先必須先將遠端主機加入可信任網域,開啟cmd輸入

       winrm set winrm/config/client @{TrustedHosts="主機名稱"}

在選擇授權機制為  AuthenticationMechanism.Negotiate

string computerName = "computerName ";
string _account = @"Domain\account";
string _password = @"password";

var password = new System.Security.SecureString();
Array.ForEach(_password.ToCharArray(), password.AppendChar);

var connectionInfo = new WSManConnectionInfo { ComputerName = computerName };
connectionInfo.Credential = new PSCredential(_account, password);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Negotiate;

//建立遠方主機的Runspace
using (var powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
	powershellRunspace.Open();

	using (powershell = PowerShell.Create())
	{
		powershell.Runspace = powershellRunspace;   //指定遠端的runspace

		powershell.AddScript(@"md d:\\abc");    //要執行的指令或腳本
		var result = powershell.Invoke<string>(); 
	}
}

 

參考: