Need to include the computer name in return values from Invoke-command so I know which computer the output is from

Viewed 246

I have a simple one line script that runs against a list of computers and returns the path of a file if the file contains certain text. This works.

I do however, need to run this against hundreds of computers and when I run it with Invoke-command, I don't know which computer has returned the path ... here is where I need your help please.

This is the command in its simplest form

invoke-command -computername $computers -erroraction silentlycontinue -scriptblock {get-childitem 'C:\' -rec -force -filter *.txt -ea silentlycontinue | foreach {select-string "<lookup.text>" $_} | select -exp Path}

The output comes in this form:

c:\path\filename

But there is no indication as to which server that path came from and I know that I am seeing multiple paths from multiple computers just from files I have dropped for my early testing.

Is it possible to amend the -scriptblock to get the computer name.

2 Answers

This should get you what you're looking for, there are a few considerations.

  • If you don't use -ExpandProperty on your Script Block, the result of Invoke-Command should be an object[] that has the property PSComputerName attached to it. If you wish to use a specific property name instead, like in this example "ComputerName", you can use a calculated property in addition to the use of -HideComputerName switch.
  • Select-String can be piped directly to Get-ChildItem, there is no need to use ForEach-Object.
Invoke-Command -ComputerName $computers -ScriptBlock {
    Get-ChildItem 'C:\' -Recurse -Force -Filter *.txt -EA SilentlyContinue |
        Select-String "<lookup.text>" |
        Select-Object Path, @{
            Name = 'ComputerName'
            Expression = { $env:ComputerName }
        }
} -HideComputerName -ErrorAction SilentlyContinue

Pscomputername is normally output by invoke-command with objects. Just take out the "-exp" at the end.

# elevated
invoke-command localhost,localhost,localhost { dir -r ..\foo *.txt -force -ea 0 | 
  select-string hi | select path }

Path                           PSComputerName RunspaceId
----                           -------------- ----------
C:\Users\admin\foo\file.txt    localhost      b7b6ca8b-f35e-41fc-ad98-ff2b6a51ae44
C:\Users\admin\foo\file.txt    localhost      2454784b-b56b-4e90-92fb-49b31dcc1745
C:\Users\admin\foo\file.txt    localhost      49e61d03-a68c-4308-a823-246cb3698f6a
Related