powershell - 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
}
}
}
解决方案
正如所评论的,您在循环中使用了错误的变量。该代码可以很好地读取文本文件,它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
推荐阅读
- python - 抓取时无法获取标题内容
- jquery - Bootstrap ScrollSpy:隐藏垂直导航栏
- dataframe - 使用标准函数或 dbplyr 对 R 中的特定行进行子集/过滤?
- typescript - Typescript 使用 57 个键实现接口:使用扩展运算符?
- ios - Firebase -can Database.database().reference(withPath: ".info/connected") 替代 Ashley Mills 可达性
- php - Laravel 5在登录前向用户模型添加属性
- python - Ruby 有像 Python 一样的“bool”函数吗?
- javascript - 用于查找名字和姓氏的正则表达式
- ios - 创建 swift 文件的副本
- php - 如何使用 Jenkins CI 将 git repo 文件保存到本地文件夹中?