Powershell和Windows服务

Windows服务可以在计算机启动时自动启动、可以暂停、也可以重新启动,而且不显示任何用户界面。这种服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。

服务可以在微软提供的图形化界面上设置,想大批量设置,而且不能接触图形化界面的情况下,就可以使用脚本命令了。

(1)powershell代码:

$status 
$starttype

#脚本信息         
write-host "此power shell脚本用来操纵windows服务" -foregroundcolor green 
write-host "服务的status属性:stopped or running" -foregroundcolor green 
write-host "服务的StartupType属性:manual(手动), automatic(自动), disabled(禁用)" -foregroundcolor green 
#服务器名单和服务名单
$servers =Get-Content "D:\st07\windows\shell\shell_1\servers.txt"
$services =Get-Content "D:\st07\windows\shell\shell_1\services.txt" 

#判断输入的参数是否有效
while(1){
    $status = Read-host "请输入status的属性:"  
    if(($status -like "stopped") -or ($status -like "running")){ }else{ 
    Write-Host "您输入的参数无效,3s后继续!" -foregroundcolor Red 
    timeout 3 
    }
    Write-Host "Status is OK!"
    break
}

while(1){
    $starttype = Read-host "请输入StartupType的属性:"  
    if(($starttype -like "manual") -or ($starttype -like "automatic") -or ($starttype -like "disabled")){ }else{ 
    Write-Host "您输入的参数无效,3s后继续!" -foregroundcolor Red 
    timeout 3 
    } 
    Write-Host "StartupType is OK!"
    break
}

#操纵windows服务
Write-host "######服务器名单######" -foregroundcolor green
$servers | foreach-object { "$_" }
$comp = Read-host "请输入您选择的服务器:"
Write-host "######服务名单######" -foregroundcolor green
$services | foreach-object { "$_" }
$svc = Read-host "请输入您选择的服务:"

Set-Service -ComputerName $comp -Name $svc -StartupType $starttype 
if( $status -like "stopped"){ 
get-service -ComputerName $comp -Name $svc | Stop-Service -force
"$svc 已经结束服务!"
} 
if( $status -like "running"){ 
get-service -ComputerName $comp -Name $svc | Start-Service
"$svc 已经开启服务!"
} 

(2)在这里获取services.txt文件,通过一句简单的脚本命令:

get-service | foreach-object {$_.name} > D:\st07\windows\shell\shell_1\services.txt

猜你喜欢

转载自blog.csdn.net/southwind0/article/details/80458959