首页 > 解决方案 > Powershell 不读取 .txt 行

问题描述

我无法让 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
        }
    }
}

标签: powershell

解决方案


正如所评论的,您在循环中使用了错误的变量。该代码可以很好地读取文本文件,它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
            }
        }
    }
}

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


推荐阅读