这是我拥有的脚本,我试图让它从文本中读取服务列表,但将它们组合在一起。例如,我有两个服务(RTCRGS和TabletInputService),它将读取为
“ RTCRGS TabletInputService”,而不是一次提供一项服务。
$Serverstxt = "C:\Scripts\Services\Server.txt"
$Servicestxt = "C:\Scripts\Services\Services.txt"
$ServiceList = get-content "$Servicestxt"
$ServerList = get-content "$Serverstxt"
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
#
foreach($Server in $ServerList){
foreach($Service in $ServiceList){
$svc = (get-service -computername $Server -name $Service)
Write-host "$Service on $Sever is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $Service..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $Service..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$Service is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try {
# For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $Service failed to $Verb."
}
$svc = (get-service -computername $Server -name $Service)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $Service on $Server is $($svc.status)"
}
答案 0 :(得分:0)
foreach
是正确的,但是您使用的是整个列表,而不是循环中的每个元素。
$SvrNames
和$SvcNames
是文件的内容。
$SvrName
和$SvcName
是当前循环变量。
所以你会用
$svc = (get-service -computername $SvrName -name $SvcName)
等等,在循环内。
为使情况更清楚,请重命名变量
$Serverstxt = "C:\Scripts\Services\Server.txt"
$Servicestxt = "C:\Scripts\Services\Services.txt"
$ServiceList = get-content "$Servicestxt"
$ServerList = get-content "$Serverstxt"
foreach($Server in $ServerList){
foreach($Service in $ServiceList){
# . . .
$svc = (get-service -computername $Server -name $Service)
# . . .
}
}