views:

2798

answers:

2

I need to create a virtual directory within an IIS Site pointing at a network share \\servername\sharename\directory and I need to specify a specific user for the Pass-through authentication.

I am after the WMI script to do this which I intend to call from a Powershell script.

Although the target IIS environment is IIS7 (WMI namespace root/WebAdministration) I would prefer to use WMI classes that are IIS6 compatible (root\MicrosoftIISv2) as the rest of the script already works against IIS6.

I know I can probably do this with the IIS7 powershell cmdlets or appcmd but I am trying to maintain the IIS6 compatibility.

+1  A: 

Here are two alternative powershell functions I came up with. I would prefer the second function which only uses WMI but the Powershell WMI error defect annoyed me enough that I resorted to using the ADSI interface. Both included for reference.

function CreateUNCVirtualDirectory( [string]$siteName = $(throw "Must provide a Site Name"), [string]$vDirName = $(throw "Must provide a Virtual Directory Name"), [string]$uncPath = $(throw "Must provide a UNC path"), [string]$uncUserName = $(throw "Must provide a UserName"), [string]$uncPassword = $(throw "Must provide a password") ) {

$iisWebSite = Get-WmiObject -Namespace 'root\MicrosoftIISv2' -Class IISWebServerSetting -Filter "ServerComment = '$siteName'"

$objIIS = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/" + $iisWebSite.Name + "/Root")
$children = $objIIS.psbase.children
$vDir = $children.add($vDirName,$objIIS.psbase.SchemaClassName)
$vDir.psbase.CommitChanges()
$vDir.Path = $uncPath
$vDir.UNCUserName = $uncUserName
$vDir.UNCPassword = $uncPassword
$vDir.psbase.CommitChanges()

}

function CreateUNCVirtualDirectory2( [string]$siteName = $(throw "Must provide a Site Name"), [string]$vDirName = $(throw "Must provide a Virtual Directory Name"), [string]$uncPath = $(throw "Must provide a UNC path"), [string]$uncUserName = $(throw "Must provide a UserName"), [string]$uncPassword = $(throw "Must provide a password") ) {

$iisWebSite = Get-WmiObject -Namespace 'root\MicrosoftIISv2' -Class IISWebServerSetting -Filter "ServerComment = '$siteName'"

$virtualDirSettings = [wmiclass] "root\MicrosoftIISv2:IIsWebVirtualDirSetting"
$newVDir = $virtualDirSettings.CreateInstance()
$newVDir.Name = ($iisWebSite.Name + '/ROOT/' + $vDirName)
$newVDir.Path = $uncPath
$newVDir.UNCUserName = $uncUserName
$newVDir.UNCPassword = $uncPassword

# Call GetType() first so that Put does not fail.
# http://blogs.msdn.com/powershell/archive/2008/08/12/some-wmi-instances-can-have-their-first-method-call-fail-and-get-member-not-work-in-powershell-v1.aspx
Write-Warning 'Ignore one error message:Exception calling "GetType" with "0" argument(s): "You cannot call a method on a null-valued expression."'
$newPool.GetType()

$newVDir.Put();
if (!$?) { $newVDir.Put() }

}

Martin Hollingsworth