Today I needed to adjust the script that maintains my web environment. A developer needed a folder inside a website to be redirected to a different URL. This is easily done in an IIS MMC with just a few clicks. Since the dev needed any call to or inside that folder to go to a specific destination (and not carry over the trailing path), the box is checked for “the exact URL entered above.”
But my web install script deletes all sites and rebuilds them nightly. So, I need it to also rebuild this redirect.
In IIS6, it is easy to list out all of the children objects in a site, such as Virtual Directories. But if something has not specifically been given an object ID in the metabase, you can’t edit it like an existing object. In IIS6, regular old subfolders inside a site are not objects by default. You have to make them objects, in this case an IIsWebDirectory, before you can manipulate them.
This script snippet connects to an existing website, creates the IIsWebDirectory object, and sets the httpredirect property. Note that the folder may or may not actually exist in the site hierarchy yet. That’s ok! Also, the “, EXACT_DESTINATION” is the piece that makes the necessary check mark.
$iis = [ADSI]”IIS://localhost/W3SVC”
$findsite = $iis.psbase.children | where { $_.keyType -eq “IIsWebServer” -AND $_.ServerComment -eq “mywebsite” }
$site = [ADSI]($findsite.psbase.path+”/ROOT”)
$targetredirect = “/different/path, EXACT_DESTINATION”
$directory = “MySubFolder”
$newwebdir = $site.psbase.children.Add($directory, “IIsWebDirectory”)
$newwebdir.psbase.commitchanges()
$newwebdir.put(“httpredirect”,$targetredirect)
$newwebdir.psbase.commitchanges()
Part of troubleshooting this is echoing back psbase.properties to see what values I needed. This little piece will help, especially when you make the change manually and refresh this to see what changed. Get $iis, $findsite, and $site before doing this:
$homer = $site.psbase.Children | Where {$_.KeyType -eq “IIsWebDirectory”}
foreach ($donut in $homer) { $donut.httpredirect }
or
$homer.psbase.properties