Printing an array in Powershell

前端 未结 1 980
时光取名叫无心
时光取名叫无心 2021-01-17 08:48

I am trying to print an array (I tried both with a for loop and directly with .ToString()), but I allways get a System.Object output.

The c

相关标签:
1条回答
  • 2021-01-17 09:15

    You're using Select-String, which produces MatchInfo objects. Since it looks like you want the whole matching lines from the files you probably should return just the value of the Line property of the MatchInfo objects. Also, your array handling is way too complicated. Just output whatever Invoke-Command returns and capture the loop output in a variable. For status output inside the loop use Write-Host, so that the messages don't get captured in $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
        }
    }
    

    If you also need the hostname you could add it with a calculated property and return custom objects:

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

    You output an array simply by echoing the array variable:

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

    To get custom-formatted output you can for instance use the format operator (-f):

    $result | ForEach-Object {
      '{0}: {1}' -f $_.Server, $_.Line
    }
    
    0 讨论(0)
提交回复
热议问题