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.
This should get you what you're looking for, there are a few considerations.
-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