2017-02-08 6 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がファイル:行:列<ファイル名>のオフセット78で発生するため、操作を実行できません:0:0"が実装されていません。エラー。 – Member0927

+0

「http:// servername/poweshell」へのリモートセッションを実際に確立できるかどうかは疑問です。 $ Session = New-PSSession -ConfigurationNameを実行すると、Microsoft.Exchange -ConnectionUri http:// servername/poweshell -credential資格情報が表示されます。 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

関連する問題