views:

316

answers:

1

Using Powershell 1.0 under Windows Server 2003 with IIS 6.

I have about 200 sites that I would like to change the IP address for (as listed in the website properties on the "website" tab in the "Web site identification" section "IP address" field.

I found this code:

$site = [adsi]"IIS://localhost/w3svc/$siteid"
$site.ServerBindings.Insert($site.ServerBindings.Count, ":80:$hostheader")
$site.SetInfo()

How can I do something like this but:

  1. Loop through all the sites in IIS
  2. Not insert a host header value, but change an existing one.
+5  A: 

The following PowerShell script should help:

$oldIp = "172.16.3.214"
$newIp = "172.16.3.215"

# Get all objects at IIS://Localhost/W3SVC
$iisObjects = new-object `
    System.DirectoryServices.DirectoryEntry("IIS://Localhost/W3SVC")

foreach($site in $iisObjects.psbase.Children)
{
    # Is object a website?
    if($site.psbase.SchemaClassName -eq "IIsWebServer")
    {
     $siteID = $site.psbase.Name

     # Grab bindings and cast to array
     $bindings = [array]$site.psbase.Properties["ServerBindings"].Value

     $hasChanged = $false
     $c = 0

     foreach($binding in $bindings)
     {
      # Only change if IP address is one we're interested in
      if($binding.IndexOf($oldIp) -gt -1)
      {
       $newBinding = $binding.Replace($oldIp, $newIp)
       Write-Output "$siteID: $binding -> $newBinding"

       $bindings[$c] = $newBinding
       $hasChanged = $true
      }
      $c++
     }

     if($hasChanged)
     {
      # Only update if something changed
      $site.psbase.Properties["ServerBindings"].Value = $bindings

      # Comment out this line to simulate updates.
      $site.psbase.CommitChanges()

      Write-Output "Committed change for $siteID"
      Write-Output "========================="
     }
    }
}
Kev
When running this I get the following prompt... cmdlet new-object at command pipeline position 1. Supply values for the following parameters: TypeName:
User
Forgot that PS uses a backtick to indicate line continuation
Kev
awesome that worked!
User
When an answer helps you out, feel free to vote up the answer. I'm sure Kev would appreciate it. :-)
Keith Hill
@Keith - I can't help myself :)
Kev