我有一个计算机列表,我只能使用每台计算机的本地帐户(user1)来获取服务列表。我正在循环浏览计算机并使用
get-service
但正如你所看到的,我必须用计算机名称为每个部分命名。我想知道是否可以将其合并到一个列表中,并将计算机名称附加到每项服务。
$computers =
@"
computer1
computer2
"@ -split [Environment]::NewLine
$computers | ForEach-Object {
$ServerUserId = "_$\user1"
$ServerPassword = ConvertTo-SecureString -String 'complexpassword' -AsPlainText -Force
$Credential = New-Object -TypeName PSCredential -ArgumentList $ServerUserId, $ServerPassword
Enter-PSSession -ComputerName $_ -Credential $Credential
"Computer name: $_"
get-service -ComputerName $computers -Name `
Service* `
Exit-PSSession
}
输出:
Computer name: Computer1
Service A
Service B
Computer name: Computer2
Service Y
Service Z
希望它看起来像:
Service A Computer1
Service B Computer1
Service Y Computer2
Service Z Computer2
您需要使用
Invoke-Command
而不是 Enter-PSSession
- 这允许您从远程计算机运行 Get-Service
,无需再次指定计算机名称。
对于本地帐户,指定
.
作为域前缀通常就足够了,因此您可以重复使用相同的凭证对象:
$ServerUserId = ".\user1"
$ServerPassword = ConvertTo-SecureString -String 'complexpassword' -AsPlainText -Force
$Credential = New-Object -TypeName PSCredential -ArgumentList $ServerUserId, $ServerPassword
$computers | ForEach-Object {
Invoke-Command -ComputerName $computerName -Credential $Credential -ScriptBlock {
Get-Service -Name Service*
}
} |Tee-Object -Variable remoteServices |Format-Table Name, PSComputerName
从带有
Invoke-Command
的远程会话输出的对象将附加一个 PSComputerName
属性,您可以用它来显示原始计算机名称