【发布时间】:2021-11-26 12:18:13
【问题描述】:
我希望我的脚本将服务器和服务作为 .txt 文件中的列表。之后,我希望我的脚本检查该服务是否存在于 txt 文件中的服务器上。
但是当我运行这个脚本时,它会返回服务器上存在的所有服务,而不是我在服务列表中指定的服务。即使服务不存在,它也不会掉线。
你能告诉我为什么它会返回所有的服务吗?
$ErrorActionPreference='stop'
$ServerList = Get-Content 'C:\Users\username\Desktop\service test\servers.txt'
$ServiceList = Get-Content 'C:\Users\username\Desktop\service test\services.txt'
try{
foreach($Server in $ServerList){
foreach($Service in $ServiceList){
$Result = Invoke-Command -ComputerName $Server -ScriptBlock {
Get-Service -Name $Service
}
foreach($List in $Result){
Write-Host "$List exists on $Server"
}
}
}
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
Write-Host "Error"
}
【问题讨论】:
-
问题是,
$Service在您的脚本块中是不可访问的。如果您将脚本块更改为Write-Host $Service,您将不会得到任何输出。这就是你获得所有服务的原因,因为Get-Service $Service将变成Get-Service。您需要将参数作为 -ArgumentList 传递,如下所示:stackoverflow.com/questions/4225748/… -
您需要将服务作为参数传递,或者作为远程变量进行引用。您可以使用
$using变量:$using:service。 . .但是,Get-Service接受远程计算机的-ComputerName参数,您可以切换它。 -
@AbrahamZinala 当我尝试它工作时,它显示服务名称不同。像 System.ServiceProcess.ServiceController
-
@M.G 这个话题对我来说似乎很高级。我总是在部分传递参数方面苦苦挣扎
-
@RedAndBlack 那是因为
$List包含一个ServiceController对象。如果您只想打印名称,请执行Write-Host "$($List.Name) exists on $Server"
标签: powershell