Advertisement
GaryWenneker

Assign-Certificate.ps1

Sep 26th, 2018
535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. [CmdletBinding()]
  2.     param(
  3.    
  4.         # a name you want to give to your certificate (can be anything you want for localhost) 
  5.         [Parameter(Mandatory=$True,Position=1)]
  6.         [ValidateNotNullOrEmpty()]
  7.         $dnsName = "localhost",
  8.        
  9.         #the website to apply the bindings/cert to (top level, not an application underneath!).
  10.         [Parameter(Mandatory=$True,Position=2)]
  11.         [ValidateNotNullOrEmpty()]
  12.         $siteName = "Default Web Site",
  13.        
  14.         #fully qualified domain name (empty for 'All unassigned', or e.g 'contoso.com')
  15.         [Parameter(Mandatory=$False,Position=3)]
  16.         [ValidateNotNullOrEmpty()]
  17.         $fqdn = ""
  18.     )
  19.  
  20.    
  21.  
  22. Clear-Host
  23.  
  24.  
  25. # ----------------------------------------------------------------------------------------
  26. # SSL CERTIFICATE CREATION
  27. # ----------------------------------------------------------------------------------------
  28.  
  29. # create the ssl certificate that will expire in 2 years
  30. $newCert = New-SelfSignedCertificate -DnsName $dnsName -CertStoreLocation cert:\LocalMachine\My -NotAfter (Get-Date).AddYears(2)
  31. "Certificate Details:`r`n`r`n $newCert"
  32.  
  33.  
  34. # ----------------------------------------------------------------------------------------
  35. # IIS BINDINGS
  36. # ----------------------------------------------------------------------------------------
  37.  
  38.  
  39. $webbindings = Get-WebBinding -Name $siteName
  40. $webbindings
  41.  
  42.  
  43. $hasSsl = $webbindings | Where-Object { $_.protocol -like "*https*" }
  44.  
  45. if($hasSsl)
  46. {
  47.     Write-Output "ERROR: An SSL certificate is already assigned. Please remove it manually before adding this certificate."
  48.     Write-Output "Alternatively, you could just use that certificate (provided it's recent/secure)."
  49. }
  50. else
  51. {
  52.     "Applying TLS/SSL Certificate"
  53.     New-WebBinding -Name $siteName -Port 443 -Protocol https -HostHeader $fqdn
  54.     (Get-WebBinding -Name $siteName -Port 443 -Protocol "https" -HostHeader $fqdn).AddSslCertificate($newCert.Thumbprint, "my")
  55.  
  56.     "`r`n`r`nNew web bindings"
  57.     $webbindings = Get-WebBinding -Name $siteName
  58.     $webbindings
  59. }
  60.  
  61.  
  62. "`r`n`r`nSSL Assignment Complete"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement