Configuring IIS Website "Connect As" With Powershell

Whilst I was setting a new web server instance on Windows Azure, I needed to find a way to specify the username and password for the website in IIS to connect with. I was previously doing this through the Basic Settings -> Connect As dialog.

I wanted to do this as a part of a Powershell script which was going to do some other configuration work for me, however it was surprisingly difficult to find out how to accomplish this, so having got a working solution I decided to share it here in the hope of helping someone else.

Eventually I found a snippet of code on at the bottom of a thread in the IIS forums, which gave me the starting point for automating the process.

function SetIISWebsiteConnectAsUser($webSiteName, $username, $password){

    set-webconfigurationproperty "system.applicationHost/sites/site[@name='$webSiteName']/application[@path='/']/virtualDirectory[@path='/']" -name username -value $username

    set-webconfigurationproperty "system.applicationHost/sites/site[@name='$webSiteName']/application[@path='/']/virtualDirectory[@path='/']" -name password -value $password

}

Simply supply the above function with strings for the name of the site in IIS you wish to configure, along with the username and password of the user you want to be running the site.