IIS8 – Create a virtual directory with read and browsing rights

Lately at work a co-worker asked me to script a virtual directory creation in PowerShell: My answer was pretty simple: OK gimme 2 mins !

A little too sure of myself, i’d spin up a vm with a Windows 2012 R2 server, install IIS feature and after few mins on Qwant (yeah, i dropped google and bing) i found this little snippet, sorry for the author, i didn’t have bookmarked or noted the post on stackOverflow 🙂

$siteName = 'Default Web Site'
$virtualDirectoryName = 'Repository'
$physicalPath = 'C:\Repository'

New-WebVirtualDirectory -Site $SiteName -Name $virtualDirectoryName -PhysicalPath $physicalPath

$Folder = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1/Root/$physicalPath")

Damn, pretty easy … But!

So i had my VM win 2K12R2 installed with IIS 8, but the script wasn’t working…


Let’s investigate why.

My guess is, that the New-Object worked peacefully, but anything available in the $Folder variable because the Virtual DIrectory is created and it said “exception orrurred while retrieving member” to the variable is created.

Let’s try to create the object

$Folder = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1/Root/Repository")


And look at what we get

$folder | gm


It seems that put method isn’t here, let’s see if we can have more informations about the Virtual Directory it self

$folder | fl *



Ok, we have nothing. Hmmm, let’s start with the MSDN documentation about the System.DirectoryServices class.

The System.DirectoryServices namespace provides easy access to Active Directory Domain Services from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the size of the network.


A new idea: because it seems that theses classes use ADSI which itself is WMI based and IIS 8 doesn’t have by default WMI. Let’s install WMI management components !

Install-WindowsFeature -Name Web-Mgmt-Compat -IncludeAllSubFeature


Now relaunch our snippet.

IIS_Troobleshoot_03BINGO !

I’ve made a full script available on github here, feel free to fork or comment !

Hope this helps you 🙂