1

I've got a simple script that looks for a file across a bunch of servers. Issue is that on each server it is pegging CPU and causing issues for production workloads. How can I get this script to not DDoS my machines?!

Start-transcript C:\tools\Querylog.txt

$Servers = Get-ADComputer -Filter {(OperatingSystem -like "*windows*server*") -and (Enabled -eq "True")} -Properties OperatingSystem

Invoke-command -ComputerName $Server-ScriptBlock {Get-ChildItem -Path $_.Root -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*somefile-readme*' } |Out-File -FilePath <filePath>\results.txt -Append}

Stop-Transcript
Nathan
  • 135
  • 3
  • 16
  • 1
    [1] use the `-Filter` for your G-Ci call instead of grabbing EVERYTHING and then filtering with the `Where-Object` call. [2] you may want to look at the `CIM_DataFile` class - it can find any type of file and is somewhat faster than G-CI. [3] try using robocopy - it is MUCH faster than G-CI. – Lee_Dailey Dec 27 '19 at 14:46
  • `-Filter` alone can make a difference of multiple minutes – T-Me Dec 27 '19 at 14:54

1 Answers1

3

Use the -Filter option with Get-ChildItem, it should be much more performant than returning all objects and filtering with Where-Object.


Also, not related to your CPU issue but in how you are crafting your Get-ADComputer call, you should use a String, not a ScriptBlock for the -Filter arguments on these cmdlets. From that answer:

-Filter doesn't support ScriptBlocks, but they Kind of Work Sometimes™ because they get ToString'd before getting evaluated. They will technically work if you use simple variable expansion like $_ or $emailAddress, but it will eventually cause you a headache, especially if you try to access an object property (like above) because it simply won't work. Use a string filter every time, and if you need to use an object property as a filter parameter, use Variable Substitution or Command Substitution.

codewario
  • 19,553
  • 20
  • 90
  • 159
  • I'll give it a go. I received this script from someone else. I'm not very good with PS... seems to me the script is incomplete though. I'm not able to follow its logic. – Nathan Dec 27 '19 at 15:28
  • 1
    I added a link to another answer where the `-Filter` parameter on `Get-ChildItem` is explained in more detail, along with a link to an MS blog post on the filtering options. There are some other good answers on that page as well that may help you. – codewario Dec 27 '19 at 15:38