How can restart IIS
on a remote machine?
I know the IP address and administrator user\'s user name and password information.
I am using C#
Simplest will be iisreset <servername>
Run command prompt as admin and execute the command.
Example : If server name is SRVAPP then command will be iisreset SRVAPP
I tried the PowerShell-based method but I kept getting the following error:
Connecting to remote server <TARGET-HOST> failed with the following error message : The WinRM client cannot process the request.
I finally found out that I needed to add the target node as a TrustedHosts
in the source node and vice-versa. If you run into that same issue, you can fix it by opening an elevated Command Prompt and typing the following commands:
From the PC you'll use to issue the commands:
powershell
winrm set winrm/config/client '@{TrustedHosts="TARGET-HOST"}'
From the destination PC (the one with IIS):
powershell
winrm set winrm/config/client '@{TrustedHosts="SOURCE-HOST"}'
(replacing TARGET-HOST
and SOURCE-HOST
with your servers hostnames or IP addresses). As soon as you do that you can issue any remote PowerShell command, such as:
IIS Stop:
powershell invoke-command -computername "TARGET-HOST" -scriptblock {iisreset /STOP}
IIS Start:
powershell invoke-command -computername "TARGET-HOST" -scriptblock {iisreset /START}
IIS Restart:
powershell invoke-command -computername "TARGET-HOST" -scriptblock {iisreset /RESTART}
... and more.
For an extensive review of this issue you can also read this post on my blog.
You could use sc, as Thomas Franke suggested:
sc \\RemoteServer stop iisadmin
sc \\RemoteServer start w3svc
or SysInternals' psexec. The PsTools suite is useful for these scenarios.
psexec \\RemoteServer iisreset
You could use the "sc" command in order to control the iis-service on the remote machine.
sc \\RemoteServer stop [iis-service-name]
Use
sc help
in order to get a list of possible arguments.
Also take a look at a microsoft kb-article on your subject.
The following POSH script will allow you to asynchronously reset a set of machines remotely (very handy when working with a large set):
$a = Get-Content "c:\OneMachineNamePerLine.txt"
foreach($line in $a)
{
Start-Job -ScriptBlock {
iisreset $line
}
}
How remote is remote? You could just execute Shutdown.exe from your c# code? If that's not possible (firewalls etc) then the next best would probably be putting a service on there that you could call remotely (and securely!) that shuts the machine down.