Blog Post

IIS Support Blog
4 MIN READ

Create a New HTTPS Website in IIS using PowerShell script

meenakshiBalekar's avatar
Aug 20, 2024

HTTPS site on IIS

 

Creating a new HTTPS website in IIS using PowerShell can streamline your deployment process and ensure your site is secure from the start. In this blog, we will cover all the prerequisites, provide the necessary script, explain the steps to run the script, discuss the extensions to save the script, suggest any required modifications, and offer troubleshooting tips in case of failure.

 

Prerequisites

 

Before you begin, ensure you have the following prerequisites in place:

  • Windows Server with IIS installed
  • PowerShell version 5.1 or later
  • Administrator access to the server
  • SSL certificate (either self-signed for testing or a valid certificate from a trusted CA) else you can create a new certificate as well

 

The PowerShell Script

 

Here is a PowerShell script to create a new HTTPS website in IIS:

 

 

 

$siteName = "NewWebsite"
$sitePath = "C:\inetpub\wwwroot\NewWebsite"
$bindingInformation = "*:443:"
$certificateThumbprint = "3a210b86a45e3bb20147de366197621fe9d2020d"
$certStoreLocation = "Cert:\LocalMachine\My"

# Import the WebAdministration module
Import-Module WebAdministration

# Create the website directory if it doesn't exist
if (-Not (Test-Path $sitePath)) {
    New-Item -Path $sitePath -ItemType Directory
}

# Create the new website
New-IISSite -Name $siteName -PhysicalPath $sitePath -BindingInformation $bindingInformation -CertificateThumbPrint $certificateThumbprint -CertStoreLocation $certStoreLocation -Protocol https

# Verify the website creation
Get-IISSite -Name $siteName

 

 

 

Make sure to replace "YOUR_CERTIFICATE_THUMBPRINT" with the actual thumbprint of your certificate. You can find the thumbprint in the certificate details in the Certificates MMC snap-in.

 

 

Steps to Run the Script

 

Follow these steps to execute the script:

 

  1. Open PowerShell as an Administrator.
  2. Copy the script into a new file.
  3. Replace the placeholder values (e.g., `YOUR_CERT_THUMBPRINT`) with actual values.
  4. Save the script with a `.ps1` extension (e.g., `CreateHttpsSite.ps1`).
  5. Navigate to the directory containing the script.
  6. Run the script using the command:

 

 

 

.\CreateHttpsSite.ps1

 

 

 

Extensions to Save the Script

 

PowerShell scripts should be saved with a `.ps1` extension. This denotes a PowerShell script file and allows it to be executed within the PowerShell environment.

 

Modifications Required

 

Based on your specific needs, you may need to modify the script:

  • Site Name: Change the `$siteName` variable to your desired site name.
  • Site Path: Update the `$sitePath` variable to the location of your website files.
  • Certificate Thumbprint: Replace `YOUR_CERT_THUMBPRINT` with the actual thumbprint of your SSL certificate.
  • Application Pool: Modify the `$appPool` variable if you wish to use a different application pool.

Create a Self-signed Certificate

 

 

 

# Create a self-signed certificate
$cert = New-SelfSignedCertificate -DnsName "yourdomain.com" -CertStoreLocation "Cert:\LocalMachine\My"

# Add the certificate to the Trusted Root Certification Authorities store
$DestStore = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::Root, "LocalMachine")
$DestStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$DestStore.Add($cert)
$DestStore.Close()

# Use the thumbprint of the newly created certificate
$certificateThumbprint = $cert.Thumbprint

 

 

 

Advantages of using Powershell Script to create a website in IIS

 

  • Automation: PowerShell scripts allow you to automate the entire process, reducing the need for manual configuration. This is especially useful when setting up multiple websites or environments.

  • Consistency: Scripts ensure that each website is configured exactly the same way, minimizing human error and ensuring consistency across different environments.

  • Efficiency: Creating websites via PowerShell is much faster than using the IIS Manager GUI, saving time and effort.

  • Repeatability: Once you have a script, you can reuse it to set up new websites quickly, making it easy to replicate configurations across different servers or environments.

  • Scalability: PowerShell scripts can be integrated into larger automation frameworks, allowing for scalable deployment and management of web applications.

  • Flexibility: PowerShell provides a wide range of cmdlets and modules for managing IIS, giving you the flexibility to customize and extend your scripts as needed.

  • Version Control: Scripts can be stored in version control systems like Git, allowing you to track changes, collaborate with others, and roll back to previous versions if needed.

  • Documentation: Scripts serve as documentation for your setup process, making it easier for others to understand and replicate your configurations.

 

Troubleshooting in Case of Failure

 

If you encounter issues, here are some troubleshooting tips:

  • Permission Errors: Ensure you are running PowerShell as an Administrator.
  • Invalid Certificate Thumbprint: Double-check the thumbprint value. It must be the exact thumbprint of your SSL certificate.
  • Site Already Exists: Verify that the site name is not already in use in IIS. You can list all sites using:

    Get-Website​
  • Binding Conflicts: Ensure no other site is using the same IP address and port combination. Check current bindings with:

    Get-WebBinding​
  • Script Syntax Errors: Review the script for any syntax errors. PowerShell will often provide details on the line number and error type.

 

Conclusion

 

Using PowerShell to create a new HTTPS website in IIS can greatly simplify the process and ensure consistency across your deployments. By following this guide, you should be able to set up your site quickly and efficiently.

Remember to always test your setup in a development environment before deploying it to production.

 

Updated Aug 20, 2024
Version 1.0

3 Comments

  • bpokorny's avatar
    bpokorny
    Copper Contributor

    meenakshiBalekar - Thank you for the quick response.

     

    I have attempted various methods to bind the certificate to the website, however I get different results.  Quite frustrating if you ask me.

     

    I have taken your script and on one server the IIS drive works.  On another server, there is no IIS drive and it fails.  I was under the impression the IIS drive was being replaced by IIS specific cmdlets.  Additionally, I cannot assume how users will have their servers configured to use/have the IIS drive available.  If the IIS drive will continue to be supported, what makes that drive available?  I have imported the Administrator Module; is there something that needs to be selected when installing IIS on the server?

     

    In another strange twist, the server that does not have the IIS drive available, I am using VS Code to write and test my scripts (one of my many environments).  Since the IIS drive is unavailable, I am attempting to use the AddSslCertificate method, but continue to get the following error:  

     

    Method invocation failed because [Deserialized.Microsoft.IIs.PowerShell.Framework.ConfigurationEle
    ment#bindings#binding] does not contain a method named 'AddSslCertificate'

     

    I find it strange, as I am not doing any remoting, just straight function calls.  I'm wondering if PS 7.4.2 vs 5.1 is an issue.  Only reason why I mention that is, I have another test app that connects to the remote machine via Ssh, delivers the PS1 file and then executes the function using the PowerShell -Command method.

    My apologies as my testing environments are a mess right now due to various scenarios, but I will continue to get this working for all situations.  I appreciate your time and effort.  I hope to resolve this shortly.

  • bpokorny Thanks for your response.

    Binding SSL Certificates Without the IIS Drive

    If the IIS drive is not available, you can use the WebAdministration module directly. Here’s a script that should help you bind an SSL certificate to a website and update the thumbprint:

    
    # Import the WebAdministration module
    Import-Module WebAdministration
    
    # Define variables
    $Website = "YourWebsiteName"
    $Protocol = "https"
    $Port = 443
    $IPAddress = "*"
    $HostName = "yourhostname.com"
    $SNIFlag = 1
    $certThumbprint = "YourCertificateThumbprint"
    $certStoreLocation = "Cert:\LocalMachine\My"
    
    # Create a new binding
    New-WebBinding -Name $Website -Protocol $Protocol -Port $Port -IPAddress $IPAddress -HostHeader $HostName -SslFlags $SNIFlag
    
    # Get the binding
    $binding = Get-WebBinding -Name $Website -Protocol $Protocol -Port $Port -IPAddress $IPAddress
    
    # Update the certificate thumbprint
    $bindingItem = Get-Item "IIS:\SslBindings\*$($Port)!$($HostName)"
    Set-ItemProperty -Path $bindingItem.PSPath -Name CertificateThumbprint -Value $certThumbprint

    Updating the Certificate Thumbprint

    If you need to update the thumbprint of an existing binding, you can use the following approach:

     

    # Import the WebAdministration module
    Import-Module WebAdministration
    
    # Define variables
    $Website = "YourWebsiteName"
    $Port = 443
    $certThumbprint = "NewCertificateThumbprint"
    
    # Get the site
    $site = Get-Item "IIS:\Sites\$Website"
    
    # Get the binding
    $binding = $site.Bindings.Collection | Where-Object { $_.protocol -eq 'https' -and $_.bindingInformation -eq "*:$Port:" }
    
    # Update the certificate thumbprint
    $binding.AddSslCertificate($certThumbprint, "My")

     

    The deserialization issue you’re encountering might be due to the way PowerShell handles objects when remoting. Ensure that you’re running these scripts locally on the server where IIS is installed to avoid deserialization problems.

    Let me know if this helps resolve your issue!

  • bpokorny's avatar
    bpokorny
    Copper Contributor

    Great article.  I have been working on finding a solution to add a certificate to a remote machine using Ssh to connect, only to run into a variety of issues.

    I see, understand and successfully added the certificate to the cert store and create the new web-binding.  However, I am having problems binding the website to the certificate through PowerShell.  I've attempted to use the AddSslCertificate method after using Get-WebBinding, but you run into a deserializing issue over HTML.

    I have tried using the IIS drive, but I have run into places where machines don't have the IIS drive available (A drive with the name 'IIS' does not exist.)

    Is there an "IIS" cmdlet that can bind the certificate to the website and/or update the thumbprint in the event of replacing the certificate.  I feel You might be missing that part of securing wesbites.  
    Here are a couple samples of my code - I'd love to get some ideas.
    * Using IIS Drive (Not all machines have drive available)

    New-WebBinding -Name $Website -Protocol $Protocol -Port $Port -IPAddress $IPAddress -HostHeader $HostName -SslFlags $SNIFlag
    $bindingItem = Get-Item "IIS:\SslBindings\*$($Port)!$($HostName)"
    Set-ItemProperty -Path $bindingItem.PSPath -Name CertificateThumbprint -Value $cert.Thumbprint

    * This code failed because of this error: Method invocation failed because [Deserialized.Microsoft.IIs.PowerShell.Framework.ConfigurationEle
    ment#bindings#binding] does not contain a method named 'AddSslCertificate'.


    New-WebBinding -Name $Website -Protocol $Protocol -Port $Port -IPAddress $IPAddress -HostHeader $HostName -SslFlags $SNIFlag
    $NewBinding = Get-WebBinding -Name $Website -Protocol $Protocol -Port $port -IPAddress $IPAddress
    $NewBinding.AddSslCertificate($Certificate.Thumbprint, $StorePath)


    Any thoughts are appreciated to overcome my binding issues.