Search code examples
wcfaclwcfserviceclient

Shutdown or Restart Computer from WCF Service Not Working


I have a function in a WCF service hosted in IIS 7.5 which it task is shutdown or restart computer when it is being called.

I use the built in command line and execute it by passing "shutdown.exe -t 0 -r" to restart or "shutdown.exe -t 0 -s" to shutdown.

    Try
        Using process As New System.Diagnostics.Process()
            Dim startInfo As New System.Diagnostics.ProcessStartInfo()
            With startInfo
                .WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
                .CreateNoWindow = True
                .UseShellExecute = False
                .RedirectStandardError = True
                .RedirectStandardInput = True
                .RedirectStandardOutput = True
                .FileName = "shutdown.exe"
                .Arguments = "-t 0 -r"
            End With
            If System.Environment.OSVersion.Version.Major >= 6 Then process.StartInfo.Verb = "runas"
            process.StartInfo = startInfo
            process.Start()
            process.WaitForExit()
            If process.ExitCode = 0 Then
                Return True
            Else
                Return False
            End If
        End Using
    Catch ex As Exception
        Return False
    End Try

The command line works fine if execute in command prompt manually. However it doesn't work when it is being execute inside WCF service.


Solution

  • Ok, trying everything and keep failed, and ended up on this guy who use bat file. And it works..!

    It is so weird and still don't know why it works. For now...who cares :)...later when I have spare time I will try to figure it out.

            ....
            Dim strCmd As String = "SHUTDOWN -m {0} -f -t 0 -r"           
            File.WriteAllText(_pathCmd & "cmd_restart.bat", String.Format(strCmd, "127.0.0.1"))
            Return ExecuteCommand(_pathCmd & "cmd_restart.bat", "")