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
2
  • 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. Commented Dec 27, 2019 at 14:46
  • -Filter alone can make a difference of multiple minutes Commented Dec 27, 2019 at 14:54

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.