Skip to: Site menu | Main content

Email LinkedIn


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

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.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
## 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 *
# Posted By stack | 2/11/14 9:04 AM

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'
# Posted By Richard | 5/26/14 4:16 PM
Thank you so much for sharing this post.
# Posted By rogerafrance | 5/24/17 11:19 PM