Blog

Use PowerShell to add IIS virtual directory with Login (Connect As)

January 7, 2014

While trying to automate the creation of new IIS websites using PowerShell I needed a script to create IIS virtual directories with a specific login (i.e. Connect As)

After several hours of searching and trying various solutions I finally arrived at this:

$sitename = "My Website Name"
$virtualdirectory = "virtual1"
$virtualdirectorypath = "C:\My Virtual Path"
$username = "username1"
$password = "password1"

New-WebVirtualDirectory -Site $sitename -Name $virtualdirectory -PhysicalPath $virtualdirectorypath 

Set-WebConfigurationProperty "system.applicationHost/sites/site[@name='$sitename']/application[@path='/']/virtualDirectory[@path='$virtualdirectory']" -name userName -value $username

Set-WebConfigurationProperty "system.applicationHost/sites/site[@name='$sitename']/application[@path='/']/virtualDirectory[@path='$virtualdirectory']" -name password -value $password

I tried several path alternatives, however the XPath queries listed in the snippet are the only iteration that worked.

Hope this saves someone else a little time.

3 Comments

stackFebruary 11, 2014 at 9:04:43 am

## Settings
$siteName = 'Default Web Site'
$virtualDirectoryName = 'Test'
$physicalPath = '\\UNC-path'

## Init
$virtualDirectoryPath = "IIS:\Sites\$siteName\$virtualDirectoryName"

## Create Virtual Directory where physicalpath is an UNC-path (New-WebVirtualDirectory wont do)
New-Item $virtualDirectoryPath -type VirtualDirectory -physicalPath $physicalPath

## Change 'Connect As' settings (New-WebVirtualDirectory don't include Username and Password)
Set-ItemProperty $virtualDirectoryPath -Name username -Value 'UserName'
Set-ItemProperty $virtualDirectoryPath -Name password -Value 'Password'

## Status
Get-Item -Path $virtualDirectoryPath | fl *

RichardMay 26, 2014 at 4:16:29 pm

stack...

Thanks for the post, just needed to change this line in order to get it to work userName instead of username

Set-ItemProperty $virtualDirectoryPath -Name userName -Value 'UserName'

rogerafrance
rogerafranceMay 24, 2017 at 11:19:01 pm

Thank you so much for sharing this post.

Leave Your Comment

Your email address will not be published. Required fields are marked *


about me

An information technology professional with twenty four years experience in systems administration, computer programming, requirements gathering, customer service, and technical support.