Nathan
Nathan

Reputation: 167

Powershell script CPU usage high

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

Upvotes: 1

Views: 944

Answers (1)

codewario
codewario

Reputation: 21418

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.

Upvotes: 3

Related Questions