I'm developing c# application to call Exchange Management Shell Cmdlets. It always comes out with an exception of "The server certificate on the destination computer (208.243.XX.2XX:443) has the following errors:
The SSL certificate is signed by an unknown certificate authority.
The SSL certificate contains a common name (CN) that does not match the hostname. "
But I did write code to accept all certificate, don't know why still get the error.
My code:
PSCredential credential = new PSCredential("administrator", securePwd);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://208.243.49.20/powershell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-Mailbox");
command.AddParameter("Name", "TestName");
powershell.Commands = command;
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(
delegate { return true; }
);
try
{
runspace.Open();//This is where the exception happens
powershell.Runspace = runspace;
Collection<PSObject> result= powershell.Invoke();
}
WSManConnectionInfo
object has two properties to skip certificate checks.
connectionInfo.SkipCACheck = true;
connectionInfo.SkipCNCheck = true;
I agree with Brent, try putting the ServicePointManager call as the first call you make, before even creating the Uri.
The delegate is also missing some parameters, however. Give this a shot:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
I think Brent is correct re: needs to be in the PowerShell process. You'll need a line like the following in your PS:
[System.Net.ServicePointManager]::ServerCertificateValidationCallback += { $true }
Did the following test against an untrusted SSL site and confirmed it overrides the error:
$url = "https://www.us.army.mil"
$wc = new-object system.net.webclient
$x = $wc.downloadstring($url) # will fail
[System.Net.ServicePointManager]::ServerCertificateValidationCallback += { $true }
$x = $wc.downloadstring($url) # should succeed
... That said, it's strange that you say the exception happens upon opening the runspace, if that's the case then maybe not, since you aren't even getting to the point of execution of the PowerShell code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With