繁体   English   中英

Powershell 不读取 .txt 行

[英]Powershell not reading .txt lines

我无法让 PowerShell 运行这个 .txt 文件,我做错了什么? 我尝试更改 .txt 的名称并检查通过的脚本,一切似乎都相同,但我不断收到错误消息,指出“.txt 无效”

$POSName = "$PSScriptRoot\Bex.txt"

foreach ($POS in (Get-Content $POSName)) {
    $Bex = Get-Service -ComputerName $POSName | Where-Object { $_.name -eq "BexServ" }
}

If ($Bex -eq $null) {
    # Service does not exist
    Write-Host " doesn't exist." -ForegroundColor Red
} 
Else {
    # Service does exist
    Write-Host "The $($Bex.Name) service found." -ForegroundColor Green
           
    If ($Bex.Status -eq "Running") {
        # Stop Service
        Set-Service -status stopped -ComputerName $POSName -name $Box.Name -ErrorAction Stop

        Write-Host "The $($Bex.Name) successfully stopped."  -ForegroundColor Green 
    }
    else {
        #service already stopped
        If ($Bex.Status -eq "Stopped") {
            Write-Host "The $($Bex.Name) service already Stopped." -ForegroundColor Green
        }
    }
}

正如所评论的,您在循环中使用了错误的变量。 代码读取文本文件就好了,它是Get-Service无法处理-ComputerName参数中的文件路径。

此外, if..else的放置应该循环内,而不是在循环之后。

尝试

$POSName = "$PSScriptRoot\Bex.txt"

foreach ($POS in (Get-Content $POSName)) {
    $Bex = Get-Service -ComputerName $POS | Where-Object { $_.name -eq "BexServ" }

    If (!$Bex) {
        # Service does not exist
        Write-Host " doesn't exist." -ForegroundColor Red
    } 
    Else {
        # Service does exist
        Write-Host "The $($Bex.Name) service found." -ForegroundColor Green
           
        If ($Bex.Status -eq "Running") {
            # Stop Service
            Set-Service -status stopped -ComputerName $POSName -name $Box.Name -ErrorAction Stop

            Write-Host "The $($Bex.Name) successfully stopped."  -ForegroundColor Green 
        }
        else {
            #service already stopped
            If ($Bex.Status -eq "Stopped") {
                Write-Host "The $($Bex.Name) service already Stopped." -ForegroundColor Green
            }
        }
    }
}

Write-Host行中输出计算机名 ( $POS ) 也可能是个好主意

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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