Search code examples
powershelliispowershell-3.0web-administration

Use passthru to make sure the cmdlet is finished


I'm confused how -Passthru works.

From my understanding, the -Passthru parameter is used for passing the result of a cmdlet to the pipeline even the cmdlet itself doesn't produce any results.

I tried to write these code first: (I'm trying to recycle the IIS Application Pool without using Restart-WebAppPool cmdlet)

Stop-WebAppPool  -Name Foo
Start-WebAppPool -Name Foo

As I expected, it takes time to stop a IIS ApplicationPool, and since PowerShell does not wait for cmdlets to finish their job, the Stop-WebAppPool stops the application pool and returns. Because the application pool is not ready to get started, the Start-WebAppPool is called and error is thrown.

So I changed my code into these:

Stop-WebAppPool  -Name Foo
Start-Sleep -Seconds SomeValueNeedToGetMeasuredAndChanged
Start-WebAppPool -Name Foo

It works but not very elegent and flexible.

Then I add -Passthru to both of the cmdlets, it becomes:

Stop-WebAppPool  -Name Foo -Passthru
Start-WebAppPool -Name Foo -Passthru

Everything goes fine and no error is thrown.

In my case, I suppose:

The Stop/Start-WebAppPool cmdlet does not produce any results until the Application Pool really get stopped/started. Since -Passthru requires something to pass to the pipeline, PowerShell waits for the cmdlet produces its result, in this case, application pool get stopped/started, to execute the next one.

I can't find any useful manuals on either -Passthru or Stop-WebAppPool, so is it alright to do so in this case?


Solution

  • -Passthru is used to pass current object (i.e. AppPool) further down the pipeline. I don't think that it's guaranteed, that Start/Stop-WebAppPool cmdlets will wait for current operation to complete before passing down AppPool object. It works now, but it could break later.

    Solution? Use Restart-WebAppPool. Or if you really need to use Start/Stop cmdlets, do it like this:

    $AppPool = 'Foo'
    Stop-WebAppPool -Name $AppPool 
    while((Get-WebAppPoolState -Name $AppPool).Value -ne 'Stopped'){
        Start-Sleep 1
    }
    Start-WebAppPool -Name $AppPool