Wednesday, July 17, 2013

How to stop, start or restart IIS site on a remote machine with powershell

Sometimes during your script execution you need to shut down a site, do some work and start it again. Powershell remoting is a good way to go. To allow a script to be executed on a remote machine you have to log on there as an administrator and run the following command: 

winrm quickconfig

Notice that confirmation is required. After that you should be able to run your commands on a remote machine. First approach is straightforward. You can stop entire IIS server and then start it again. Like this:

Invoke-Command -ComputerName $targetServer -ScriptBlock {iisreset /STOP}
# do your stuff here
Invoke-Command -ComputerName $targetServer -ScriptBlock {iisreset /START}

where $targetServer is a variable that contains the name of the server. To restart the server use iisreset without arguments. This approach is fine for a single site on a server. On the other hand you probably don't want to shut down all sites on a server. In this case you can stop a few like this:

Invoke-Command 
-ComputerName $targetServer 
-ScriptBlock {import-module WebAdministration; Stop-Website $args[0]; Stop-Website $args[1]} 
-ArgumentList @($site1, $site2)

where $site1 and $site2 are the sites you want to stop. To start the sites use a similar command:

Invoke-Command 
-ComputerName $targetServer 
-ScriptBlock {import-module WebAdministration; Start-Website $args[0]; Start-Website $args[1]} 
-ArgumentList @($site1, $site2)

Hope this helps.

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work and skill. Thanks. Salesflow

    ReplyDelete