2016-09-16 56 views
2

我试图打印一个数组(我试图用for循环和直接与.ToString()),但我总是得到一个System.Object输出。在Powershell中打印数组

数组的内容是这个命令的结果:

$singleOutput = Invoke-Command -ComputerName $server -ScriptBlock { 
    Get-ChildItem C:\*.txt -Recurse | 
     Select-String -Pattern "password" -AllMatches 
} 

这是我得到的输出:

System.Object[]

我缺少什么?

编辑:

这是整个功能:

foreach ($server in $servidores) { 
    $result = @() 
    Write-Output ("---Searching on Server:---" + $server + "----at:" + 
     (Get-Date).ToString() + "----") 
    $singleOutput = Invoke-Command -ComputerName $server -ScriptBlock { 
     Get-ChildItem C:\*.txt -Recurse | 
      Select-String -Pattern "password" -AllMatches 
    } 
    $result += $singleOutput 

    Write-Host $result.ToString() 
} 
Read-Host -Prompt "Press Enter to exit" 

我也试图与:

foreach ($i in $result) { 
    $result[$i].ToString() 
} 
+0

这是一组对象,没事。你为什么用'tostring()'打印?你想要什么输出?你是写对象还是写主机? – TessellatingHeckler

+0

然后我添加$ result + = $ singleOutput(声明的第一个$ result = @()) –

+0

我正在使用写主机 –

回答

9

您使用Select-String,产生MatchInfo对象。由于它看起来像要从文件中匹配整行,因此您应该只返回MatchInfo对象的Line属性的值。另外,你的数组处理太复杂了。只需输出任何Invoke-Command返回并捕获变量中的循环输出。对于循环内部的状态输出,使用Write-Host,以便在$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 
    } 
} 

如果您还需要的主机名,你可以用calculated property添加它,并返回自定义对象:

$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 
    } 
} 

您输出数组通过echo数组变量:

PS C:\>$result 
Server Line 
------ ---- 
...  ...

要获得自定义格式的输出,您可以使用例如format operator-f):

$result | ForEach-Object { 
    '{0}: {1}' -f $_.Server, $_.Line 
} 
+2

**看过5000次,但1 upvote ...?**得到开玩笑的人。分享爱。 –

+1

已观看10,000次只有7个投票...看起来不像这样Q/A变得很好信息转换 – GoldBishop