首页 > 解决方案 > 脚本不会从 txt 文件中逐行读取服务,而是将它们组合起来

问题描述

这是我拥有的脚本,我试图让它从文本中读取服务列表,但它将它们组合在一起。例如,我有两个服务(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)"
}

标签: powershellservicescriptingpowershell-2.0powershell-3.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)
    # . . .
    }
}

推荐阅读