Freigeben über


Binding a Certificate in IIS using C# and Powershell

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:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;

namespace ExecutePowershell
{
 class Program
 {
 static void Main(string[] args)
 {
 ExecutePowershellClass pwrshell = new ExecutePowershellClass();
 pwrshell.ExecuteCommand();
 Console.ReadLine();
 }
 }
 class 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.
 myPowerShellInstance.AddScript(sScript);

// 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)
 {
 Console.WriteLine(outputItem.ToString());
 }
 }
 }
 }
 }
}
 Powershell COMMAND to bind a certificate

# Import IIS web administration Module
Import-Module WebAdministration

New-SelfSignedCertificate -DnsName website.test.com -CertStoreLocation cert:\LocalMachine\My

$certificate = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.subject -like "*website.test.com*"} | Select-Object -ExpandProperty Thumbprint

Write-Host $certificate

Get-WebBinding -Port 443 -Name website.test.com | Remove-WebBinding

Remove-Item -Path "IIS:\SslBindings\*!443!website.test.com"

New-WebBinding -Name "Default Web Site" -IPAddress "*" -HostHeader "website.test.com" -Port 443 -Protocol https -SslFlags 0

get-item -Path "cert:\localmachine\my\$certificate" | new-item -path IIS:\SslBindings\0.0.0.0!443!website.test.com -Value $certificate -Force

Note: You need to modify the hostname and binding accordingly.