How to perform IISRESET with Powershell Script

Viewed 102446

Does anyone know how to perform IISRESET with a PowerShell script? I'm using the PowerGUI editor with PowerShell 1.0 installed on a Windows 2008 box.

8 Answers

You can do it with the Invoke-Command cmdlet:

invoke-command -scriptblock {iisreset}

UPDATE:

You can also simplify the command using the & call operator:

& {iisreset}

IIS Stop or Start (tested)

WaitForExit and ExitCode work fine

[System.Reflection.Assembly]::LoadWithPartialName("System.Diagnostics").FullName
$procinfo = New-object System.Diagnostics.ProcessStartInfo
$procinfo.CreateNoWindow = $true
$procinfo.UseShellExecute = $false
$procinfo.RedirectStandardOutput = $true
$procinfo.RedirectStandardError = $true
$procinfo.FileName = "C:\Windows\System32\iisreset.exe"
$procinfo.Arguments = "/stop"
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo = $procinfo
[void]$proc.Start()
$proc.WaitForExit()
$exited = $proc.ExitCode
$proc.Dispose()

    Write-Host $exited

iisreset.exe supports computer names as a parameter. An example below show basic idea how to reset IIS on multiple servers:

$servers = @()
$servers += 'server1'
$servers += 'server2'
...
$servers += 'serverN'

Since iisreset.exe doesn't support multivalued parameters we have to wrap it in a loop:

$servers | %{ iisreset $_ /restart /noforce }

You may want to add simple monitoring:

$servers | %{ Write-Host "`n`n$_`n" -NoNewline ; iisreset $_ /restart /noforce /timeout:30 }

If you have many servers you may be interested in failures only:

$servers | %{ Write-Host "`n`n$_`n" -NoNewline ; iisreset $_ /restart /noforce /timeout:30 | Select-String "failed" }

Multiline version for better readability:

foreach ( $server in $servers ) {
    Write-Host "`n`n$server`n" -NoNewline ; 
    iisreset $server /restart /noforce /timeout:30 | Select-String "failed"
}

I would strongly recommend testing your script with /status before implementing /reset action:

$servers | %{ iisreset $_ /status }

You may check stopped components with /status as well:

$servers | %{ Write-Host "`n`n$_`n" -NoNewline ; iisreset $_ /status | Select-String "Stopped" }

Reference

  • /restart is the default parameter. iisreset.exe users /restart in case no other actions params specified
  • /noforce will prevent iisreset.exe from running in case of an error.
  • /timeout - sometime you need to allow server more time to process request to avoid IIS stuck in Stopped state.
Related