2017-02-08 1 views
0

C#을 사용하여 .Net 응용 프로그램에서 PowerShell과의 연결을 만들려고했습니다. 세션을 만들려고 할 때 연결이 완료되면 빈 콜렉션을 반환합니다.C#을 사용하여 PowerShell 원격 세션 만들기

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; 

PSCredential remoteCredential = new PSCredential("userID", StringToSecureString("Password")); 

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "Ip Address of server", 5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000); 

runspace = RunspaceFactory.CreateRunspace(connectionInfo); 
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; 

runspace.Open(); 

using (PowerShell ps = PowerShell.Create()) 
{ 
ps.Runspace = runspace; 

ps.AddScript(@"$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername/poweshell -Credential " + remoteCredential); 

//result count returned is 0 
var result = ps.Invoke(); 

ps.Commands.Clear(); 

ps.AddCommand("Import-PSSession $Session"); 

ps.Invoke(); 
} 
+0

당신이 어떤 결과를 기대하고 있습니다? – PetSerAl

답변

1

나는 이것을 테스트 할 수 있지만이 바른 길에 당신을 둘 수 있습니다`추가 string`와`PSCredential`에서

 string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; 
     PSCredential remoteCredential = new PSCredential("userID", StringToSecureString("Password")); 
     WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "Ip Address of server", 5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000); 

     string scriptPath = [email protected]" 
     $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername/poweshell -Credential {remoteCredential} | Out-String 
     Import-PSSession $Session"; 

     Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); 
     connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; 
     runspace.Open(); 
     RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 
     Pipeline pipeline = runspace.CreatePipeline(); 
     string scriptfile = scriptPath; 
     Command myCommand = new Command(scriptfile, false); 
     pipeline.Commands.Add(myCommand); 
     pipeline.Invoke(); 
     runspace.Close(); 
+0

나는 그것을 시험해 보았다. 하지만 "작업 :"NewNotImplementedException at file : line : column : 0 : 0 "이 구현되지 않았기 때문에"작업을 수행 할 수 없습니다. " 오류. – Member0927

+0

자, 실제로 "http : // servername/poweshell"에 원격 세션을 설정할 수 있는지 의문입니다. 실행할 때 $ Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http : // servername/poweshell - 자격 증명; Import-PSSession $ Session "을 PowerShell에서 직접 가져온 경우 모든 데이터를 반환 할 수 있습니까?이 경우에도 도움이 될 수 있습니다. https://msdn.microsoft.com/en-us/library/bb332449(v=exchg.80).aspx –

+0

위의 솔루션을 시도했지만 아무 소용이. 문제는 Windows PowerShell 명령 프롬프트에서 PSSession 명령을 실행할 수 있습니다.하지만 내 .Net 응용 프로그램에서 작동하지 않습니다 .PowerShell 명령을 호출 할 때 0을 반환합니다. "결과 = ps.Invoke(); "var 결과의 개수는 0입니다. – Member0927

관련 문제