The below command is using
$results = Invoke-Command -ComputerName $remoteComputers -ScriptBlock{
(get-childitem "C:\tmp" | where-object {$_.Name -like "*MATCHINGfiles*"} | foreach ($_) {remove-item $_.fullname})
}
$remoteComputers
contains a list of computer names
The command works but there is no diagnostic information about which files were deleted, what went well, and what didn't.
(I'm adding this question as it seems quite useful and I had to write a script for it).
The following will execute the script on remote computers and also return results (it's been tested):
$results = Invoke-Command -ComputerName $remoteComputers -ScriptBlock {
$files = Get-ChildItem "C:\tmp" | Where-Object { $_.Name -like "*MYSTRING*" }
$deletionResults = foreach ($file in $files) {
try {
Remove-Item -Path $file.FullName -ErrorAction Stop
[PSCustomObject]@{
FileName = $file.Name
FilePath = $file.FullName
Status = "Deleted"
}
} catch {
[PSCustomObject]@{
FileName = $file.Name
FilePath = $file.FullName
Status = "Failed to Delete"
ErrorMessage = $_.Exception.Message
}
}
}
return $deletionResults
}
And then run:
$results | Format-Table -AutoSize
Screenshot: