【发布时间】:2020-09-25 05:32:59
【问题描述】:
如何根据远程服务器上的字符串数组中列出的确切特定服务名称获取特定服务?
Status Name DisplayName
------ ---- -----------
Running DFS DFS Namespace
Running DFSR DFS Replication
Running DNS DNS Server
Running EventSystem COM+ Event System
Running IsmServ Intersite Messaging
Running KDC Kerberos Key Distribution Center
Running LANMANServer Server
Running LANMANWorkstation Workstation
Running Netlogon NETLOGON
Running NTDS Active Directory Domain Services
Running RPCSs Remote Procedure Call (RPC)
Running SAMSs Security Accounts Manager
Running W32Time Windows Time
因为下面的脚本从 $ServiceList 变量中提供的名称返回了错误的服务。
没有提到 Afd 服务,但它仍然显示:
列表中的必需服务之一,DNS 甚至没有显示:
注意:Powershell ISE 已以管理员身份执行并具有域管理员凭据。脚本执行成功,没有问题,但结果与$ServiceList变量内容的具体列表不符。
这是我目前的脚本:
$ServiceList = @(
'DFS'
'DFSR'
'DNS'
'EventSystem'
'IsmServ'
'KDC'
'LANMANServer'
'LANMANWorkstation'
'NETLOGON'
'NTDS'
'RPCSs'
'SAMSs'
'W32Time'
)
$input = Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName
$input | ForEach-Object `
{
$Servers = ($_ -split '\.')[0]
$Servers | ForEach-Object `
{
$Server = $_
Write-Host "Processing $($Server) ..." -ForegroundColor Cyan
if (Test-Connection -ComputerName $Server -Count 2 -Quiet)
{
foreach ($ServiceToCheck in $ServiceList)
{
Write-Host "`tChecking $($Server) - $($ServiceToCheck) ..." -ForegroundColor Yellow
Try
{
If ($services = Get-Service -ServiceName $ServiceToCheck -ComputerName $Server)
{
$services | Select-Object -ExpandProperty ServicesDependedOn | Select-Object StartType, Status, Name, DisplayName, Machinename, @{ N = 'Service Dependency'; E = { (Get-Service -Name $_.ServicesDependedOn -ComputerName $Server | ForEach-Object { "$($_.Name): $($_.Status)" }) -join '; ' } }
}
Else
{
"" | Select-Object @{ n = "Status"; e = { "Services not found" } },
@{ n = "DisplayName"; e = { "$($_.Services)" } },
@{ n = "Machinename"; e = { $Server } }
}
}
Catch
{
"" | Select-Object @{ n = "Status"; e = { "Error checking services" } },
@{ n = "DisplayName"; e = { "" } },
@{ n = "Machinename"; e = { $Server } }
}
}
}
else
{
"" | Select-Object @{ n = "Status"; e = { "Couldn't ping server" } },
@{ n = "DisplayName"; e = { "" } },
@{ n = "Machinename"; e = { $Server } }
}
}
} | Out-GridView
【问题讨论】:
-
$input是一个自动变量,因此您不应将该名称用作自定义变量。此外,第二个 ForEach-Object 循环是多余的,因为您已经一次循环一个域控制器。 -
嗨@Theo 谢谢你的更新。以某种方式更改 $input 变量不会改善结果?
标签: powershell active-directory