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.
CodePudding user response:
This should get you what you're looking for, there are a few considerations.
- If you don't use
-ExpandPropertyon your Script Block, the result ofInvoke-Commandshould be anobject[]that has the propertyPSComputerNameattached 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-HideComputerNameswitch. Select-Stringcan be piped directly toGet-ChildItem, there is no need to useForEach-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
