0

I'm running both Apache (as a Windows service) and IIS 10, and would like to be able to toggle each of these services on or off, as they both grab port 80, and I don't wish to configure either to use another port.

So I would like to make a PowerShell script that either stops IIS and starts Apache or vice versa. How can I achieve this?

3
  • 1
    use get-service, start-service and stop-service. if Apache Service runs stop it and then start IIS and vice versa. this is just an if/elseif thing
    – SimonS
    Nov 9, 2017 at 7:21
  • @SimonS Thanks for the tip on get-service et al, but I would rather have two scripts, one to switch to Apache, and one for IIS, vs. if/else so that I'm more in control.
    – ProfK
    Nov 9, 2017 at 9:12
  • 2
    you can do it that way, but it wouldn't make that much sense. get-service IISAdmin | stop-service -force ; start-service "ApacheServiceName" would be the command for stopping IIS and starting Apache, you can do the same for Apache, just the other way round. also I don't knbow the service name of apache so you would have to change that
    – SimonS
    Nov 9, 2017 at 10:23

2 Answers 2

3
function Switch-Webserver {

    Param(
        [Parameter( ParameterSetName = "IIS")]
        [switch]$IIS,
        [Parameter( ParameterSetName = "Apache")]
        [switch]$Apache
    )

    switch ($PSCmdlet.ParameterSetName)
    {
        'IIS'    { get-service "Apache" | stop-service -force ; start-service IISAdmin }
        'Apache' { get-service IISAdmin | stop-service -force ; start-service "Apache" }
    }

}

you can use this function in PowerShell console like this:

Switch-Webserver -IIS # This will stop Apache and start IIS
Switch-Webserver -Apache # This will stop IIS and start Apache

You can put this function inside your PowerShell Profile or load it from a console window like this:

. C:\Path\To\Function\Switch-Webserver.ps1
1
  • Thanks for you effort in writing this script for me. However, isn't the IIS service name W3SVC vs. IISAdmin?
    – ProfK
    Nov 10, 2017 at 4:52
0

The trick is to use argument when starting and stopping services so that they can run in the background. First, you may need to install the service. Then. to gracefully stop apache, use this in a script:

httpd -k graceful-stop

Just put the above in a script and execute it and it will stop apache.

To start it, you might've guessed:

httpd -k start

For stopping and starting IIS, you can find there instructions here.

1
  • Apache as a Windows service does run in the background. All services do. You are talking about the Apache server application, not the Windows service. I have edited my question to make clear I'm running Apache as a service.
    – ProfK
    Nov 9, 2017 at 10:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .