bbinnebose
bbinnebose

Reputation: 45

How can I check for stopped websites and starting those websites using powershell functions

Im currently updating and replacing old outdated nightly scheduled batch files with new self sufficient PowerShell scripts.

The one I am having trouble with is website starts. I am able to use the current test code to get the list of sites and display them but cannot figure out a way to correctly start them if they are stopped.

Set-ExecutionPolicy Unrestricted
start-transcript -path C:\TESTSTART.TXT
#function to get list of websites that are currently stopped
function Get-StoppedSites {
    Import-Module WebAdministration
    $website = Get-ChildItem IIS:\Sites | where {$_.State -eq 'Stopped'}
    write-host "$website is stopped"
    }
#function to start the stopped website
function StartSites {
    param(
    $websitename
    )
    start-website $websitename
    write-host "$website was started"
    }
$Script = Get-StoppedSites
$Script | ForEach-Object{StartSites -websitename $website} 
stop-transcript

When I call this from powershell it acts like it completed with no errors but the website is not started that I had stopped. Windows 2008 R2 server, PS 2.0. I will be running this on 2003 servers once it's ready to roll out though.

Here is my transcript:

Transcript started, output file is C:\TESTSTART.TXT
 is stopped
Start-Website : Cannot validate argument on parameter 'Name'. The argument is null. Supply a non-null argument and try 
the command again.
At C:\Users\Administrator\Desktop\test.ps1:14 char:18
+     start-website <<<<  $websitename
    + CategoryInfo          : InvalidData: (:) [Start-Website], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.IIs.PowerShell.Provider.StartWebsiteCommand

 was started
**********************
Windows PowerShell Transcript End
End time: 20120823150248

Can you guys help me figure out where/what I'm doing wrong here? Thanks!

Upvotes: 2

Views: 4712

Answers (1)

Cody
Cody

Reputation: 2482

Try this:

Set-ExecutionPolicy Unrestricted

Import-Module WebAdministration

$sites = Get-Website | where {$_.State -eq 'Stopped'}

$sites | ForEach-Object {
    $sitename = $_.name
    IF ($sitename -ne $NULL)
    {  
        Write-Host "$sitename is stopped. Starting it..."
        Start-Website $sitename
    }
}

There are a couple issues with your code. Most importantly, Get-StoppedSites wasn't actually returning anything, just printing out names. Also, you can use the existing commandlet Get-Website for getting websites.

Upvotes: 6

Related Questions