1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
class RemotePS
{
private Runspace runspace;
public RemotePS(string uri, string schema, string username, string livePass)
{
this.runspace = openRunspace(uri, schema, username, livePass);
}
/*<summary>
Opens remote runspace
</summary>
<param name="uri">Uri to connect to, for example https://pod51002psh.outlook.com/powershell/"</param>
<param name="schema">Schema of connection, for example http://schemas.microsoft.com/powershell/Microsoft.Exchange</param>
<param name="username">Username</param>
<param name="password">Secure pasword</param>
<returns>Runspace</returns> */
public Runspace openRunspace(string uri, string schema, string username, string livePass)
{
SecureString password = new SecureString();
foreach (char c in livePass.ToCharArray())
{
password.AppendChar(c);
}
PSCredential psc = new PSCredential(username, password);
WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc);
rri.AuthenticationMechanism = AuthenticationMechanism.Basic;
// rri.ProxyAuthentication = AuthenticationMechanism.Negotiate;
Runspace runspace = RunspaceFactory.CreateRunspace(rri);
try
{
runspace.Open();
}
catch (InvalidRunspaceStateException ex)
{
MessageBox.Show("" + ex);
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
return runspace;
}
private Runspace getRunSpace()
{
if (this.runspace.RunspaceStateInfo.State != RunspaceState.Opened)
try { this.runspace.Open(); }
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
return this.runspace;
}
/*
<summary>
Invoke simple command
Ex.
Collection<PSObject> col = RunCommand("Get-Mailbox");
</summary>
<param name="command">Command Name</param>
<returns></returns>
*/
public Collection<PSObject> RunCommand(string command)
{
Command myCommand = new Command(command);
Pipeline pipeLine = getRunSpace().CreatePipeline();
pipeLine.Commands.Add(myCommand);
Collection<PSObject> ret = null;
try
{
pipeLine.Invoke();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
return ret;
} |
Partager