powershell - 脚本不会从 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)"
}
解决方案
这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)
# . . .
}
}
推荐阅读
- java - 如何将 2 excel 中的数据与 java 进行比较
- laravel - 如何重定向当前页面以使用 guzzle (laravel) 发布响应
- java - 如何在创建的目录中下载文件
- html - 替换 Sphinx 标准 HTML 输出中的“文档”后缀
- angular - 将字符串 (API) 添加为单个变量
- amazon - 什么是最好的 IMDB REST API?我可以从哪里得到它?
- regex - 使用正则表达式匹配多个条件
- c++ - 打印字节为 longlong
- python - 如何在不中断的情况下运行循环python脚本
- html - 如何在电子邮件正文中正确设置横幅徽标长度和高度