Arrays 在Powershell中打印阵列
我试图打印一个数组(我尝试使用for循环和直接使用Arrays 在Powershell中打印阵列,arrays,powershell,Arrays,Powershell,我试图打印一个数组(我尝试使用for循环和直接使用.ToString()),但我总是得到一个System.Object输出 数组的内容是此命令的结果: $singleOutput = Invoke-Command -ComputerName $server -ScriptBlock { Get-ChildItem C:\*.txt -Recurse | Select-String -Pattern "password" -AllMatches } 这是我得到的输出: S
.ToString()
),但我总是得到一个System.Object
输出
数组的内容是此命令的结果:
$singleOutput = Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches
}
这是我得到的输出:
System.Object[]
我还尝试了:
foreach ($i in $result) {
$result[$i].ToString()
}
您正在使用
selectstring
,它生成MatchInfo
对象。由于看起来您需要文件中的所有匹配行,您可能应该只返回MatchInfo
对象的Line
属性的值。而且,您的数组处理太复杂了。只需输出Invoke命令返回的内容,并在变量中捕获循环输出。对于循环内的状态输出,请使用写入主机
,这样就不会在$result
中捕获消息
$result = foreach ($server in $servidores) {
Write-Host ("--- Searching on Server: $server at: " + (Get-Date).ToString())
Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches |
Select-Object -Expand Line
}
}
如果您还需要主机名,可以将其添加为并返回自定义对象:
$result = foreach ($server in $servidores) {
Write-Host ("--- Searching on Server: $server at: " + (Get-Date).ToString())
Invoke-Command -ComputerName $server -ScriptBlock {
Get-ChildItem C:\*.txt -Recurse |
Select-String -Pattern "password" -AllMatches |
Select-Object @{n='Server';e={$env:COMPUTERNAME}},Line
}
}
只需回显数组变量即可输出数组:
PS C:\> $result
Server Line
------ ----
... ...
这是一个对象数组,好的。为什么要用“tostring()”打印它?您想要什么输出?你是在写对象还是在写主机?然后我添加$result+=$singleOutput(声明的第一个$result=@())我使用写主机“$result”
而不是$result.ToString()
而不是写主机$result.ToString()
,使用写主机($result-join“`r`n”)
或$result
。
PS C:\> $result
Server Line
------ ----
... ...
$result | ForEach-Object {
'{0}: {1}' -f $_.Server, $_.Line
}