我想在 TXT 文件中保存的主机名列表中提取服务状态的表中添加 IP 地址。一个主机可能包含多个服务。服务名称以 I 开头。我该怎么做。
$servers=Get-Content c:\servers.txt
$servers|Foreach-Object{Get-Service -ComputerName $_ -Name I*} | Select-Object -Property ServiceName, Status | ConvertTo-Html -Head $htmlhead | Out-String
答案1
根据您的评论,以下是我针对这种情况使用的脚本:
# Gettings the server list from text file
$servers = Get-Content c:\servers.txt
# Creating an empty array
$array = @()
# Starting the loop for each server in the list
foreach ($server in $servers)
{
# Getting the server's IP. Other methods could apply
$IP = [System.Net.Dns]::GetHostAddresses("$server").IPAddressToString
# Getting the list of services
$services = Get-Service -ComputerName $server -Name I*
# Starting the loop for each service in the list
foreach ($service in $services)
{
# Creating a new PS object and adding values
$Object = New-Object PSObject
$Object | Add-Member -MemberType NoteProperty -Name "Hostname" -Value $server
$Object | Add-Member -MemberType NoteProperty -Name "IP" -Value $IP
$Object | Add-Member -MemberType NoteProperty -Name "Service" -Value $service.Name
$Object | Add-Member -MemberType NoteProperty -Name "Status" -Value $service.Status
#Feeding the array with the values
$array += $Object
}
}
# Now converting the array to HTML
$array | ConvertTo-Html -Head $htmlhead | Out-String
在控制台中,$array 将像这样扩展:
请尝试并告诉我们它是否适合您的需求。您可能需要根据您的环境进行调整。
希望这可以帮助 !