Friday, March 18, 2016

Set up IIS using PowerShell

When you're setting up a new server there are sometimes steps you need to do before you can configure your website, such as turning on Windows Authentication in corporate environments, or perhaps installing the features necessary for an ASP.NET application. I had to do this recently when setting up new servers at a client:
404 - Image Not Found
404 - Image Not Found
404 - Image Not Found
There was this final screen though where I noticed that this configuration can be exported to an XML file and set up via PowerShell. When inspecting the XML that was generated however, it seemed to include specific host names and so may not be a very generic way of setting up a server. After a bit of investigation, there are other commands that one can run to view what is installed, as well as install specific features.
404 - Image Not Found
404 - Image Not Found
Notice too that it seems to install other dependent features by default, as I just specified ASP.NET 4.5 but the other related features were also installed (in the GUI version you would be prompted about this).
Could be quite useful to have this as a script instead of remembering which features to turn on and off. My PowerShellFu isn’t the strongest, but something along the lines of this should work (I formatted this on separate lines for readability, you will want to run it as a single line):

Get-WindowsFeature -Name Web-*
  | Where-Object
  {
    ($_.Name -eq "Web-Asp-Net45" -or $_.Name -eq "Web-Windows-Auth")
    -and
    $_.InstallState -ne "Installed"
  }
  | Install-WindowsFeature

This may be a bit more generic, and could be used as a script included in source control for setting up new servers, instead of manually doing this via the Server Manager. There are also more advanced options to the cmdlets, more information of which can be seen in the documentation, one example of which is specifying a ComputerName.
One scenario I could think of for this is when setting up a web farm, and perhaps you have multiple hosts you need to do this on. Instead of doing each separately, you could probably pipe in the hostnames to a setup script, and let it perform the setup on each host. Though, as said, my PowerShellFu isn't strong, and I've had issues setting up remote PowerShell admin before, so I'll leave that part up to you ;)