简体   繁体   中英

powershell script code to start/stop iis and mssql

I want to start/stop iis and mssql using powershell script code Means when i run ps script i want to start/stop iis and mssql

I search it on net and i found some code for it but its not working as per my requirement

code:

$iis = get-wmiobject Win32_Service -ComputerName "xyz" -Filter "name='IISADMIN'"
$iis.State=4

if($iis.State -ne "Running")
{
Write-Host "IIS Stop successfuly"
}

above code show me the output IIS Stop successful but iis still running after code execution is this correct code to stop iis using powershell script or something missing please suggest me for iis and mssql also

Thanks in advanced...

You can get all services that depend on IISAdmin service by running:

$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Dependent"
Get-WmiObject -Query $query | Select Name

You can get all services that IISAdmin service depends on by running:

$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Antecedent"
Get-WmiObject -Query $query | Select Name

Now, once you know that the dependent and required services, it is easy to stop.

For example, to stop all services that depend on IISAdmin :

$query = "ASSOCIATORS OF {Win32_Service.Name='IISAdmin'} WHERE ResultRole=Dependent"
Get-WmiObject -Query $query
$services | Foreach-Object { "Stopping $($_.Name)";$_.StopService() }

You need to invoke the StopService method and check the ReturnValue. To get a list of supported methods pipe $iis to Get-Member :

if($iis.State -eq 'Running')
{
    $rv = $iis.StopService()

    if($rv.ReturnValue -eq 0)
    {
        Write-Host "IIS Stopped successfuly"
    }
    else
    {
        Write-Host "IIS did not stop successfuly. Return value is $($rv.ReturnValue)"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM