Add a virtual directory to multiple sites in IIS 7.x using PowerShell.

Someone needed to add virtual directory to a few dozen sites in IIS, so I wrote them a little script to do it. To use it save the code below as something like ‘CreateVirDirs.ps1’, open a Powershell prompt with administrator rights, cd to the directory you saved it in and then execute it with .CreateVirDirs.ps1

Import-Module WebAdministration $sites = Get-Childitem 'IIS:Sites' $name = "NewVirtualDirectory" $vdPath = "D:Temp" foreach ($site in $sites) { $path = 'IIS:Sites' + $site.Name + '' + $name New-Item $path -type VirtualDirectory -physicalPath $vdPath Write-Output $path }

You should get output like:

PS D:> .CreateVirDirs.ps1 Name PhysicalPath ---- ------------ NewVirtualDirectory D:Temp IIS:SitesDefault Web SiteNewVirtualDirectory NewVirtualDirectory D:Temp IIS:Siteswww.ichi.co.ukNewVirtualDirectory NewVirtualDirectory D:Temp IIS:SitesSome Other SiteNewVirtualDirectory

That will add the virtual directory to every site in IIS, but you can limit it quite easily which is explained here. If you get an error due to not having the WebAdministration module, this might be of some use. Hope that helps!

top