First published on MSDN on Mar 23, 2018
Other day I was assisting a customer who had a unique need of binding a Certificate from within C# code using Powershell. A direct API call won't work due to some constraints, so Powershell was the other viable option. Customer also didn't want any Powershell window to pop-up, so we needed to code around it.
Here is the code sample:
static void Main(string args)
ExecutePowershellClass pwrshell = new ExecutePowershellClass();
public void ExecuteCommand()
using (PowerShell myPowerShellInstance = PowerShell.Create())
//powershell script to get version number and list of processes currently executing in the machine.
string sScript= "$PSVersionTable.PSVersion;get-process"; //
REPLACE THIS sScript WITH THE POWERSHELL
//COMMAND BELOW. BASICALLY BUILD YOUR OWN STRING BASED ON YOUR NEED
// use "AddScript" to add the contents of a script file to the end of the execution pipeline.
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = myPowerShellInstance.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
if (outputItem != null)
Powershell COMMAND to bind a certificate
# Import IIS web administration Module
get-item -Path "cert:\localmachine\my\$certificate" | new-item -path IIS:\SslBindings\0.0.0.0!443!website.test.com -Value $certificate -Force
: You need to modify the hostname and binding accordingly.