Search code examples
powershellinvoke-command

Invoke-Command takes a long time, but only occasionally


I have a PowerShell script using Invoke-Command that has been in use for about a year that suddenly has been having very bad performance issues. What normally took 1 to 2 seconds to run now takes about 90 seconds. Confusingly, it doesn't always take a long time. In fact, I've been testing it many times throughout today and have seen it run perfectly fine with every attempt over a 10-20 minute period, and then it goes back to being abysmally slow for the next 20-40 minute test period.

A simple look at my test code:

$cred = New-Object System.Management.Automation.PSCredential $username, $securePassword     
Write-Host "Running command..."
Invoke-Command -ComputerName $target -Credential $cred -ScriptBlock {  
    Write-Host "Hello"
}
Write-Host "Done"

The timing of the results goes something like this:

"Running command..."

65 seconds...

"Hello"

25 seconds...

"Done"

For the usage of this, I need to wait on the process and then be able to see the result of the command so I can't just throw -AsJob into the script and not wait for the output. What should I be looking for to find what's slowing this down? I've checked the target machine during a slow response and don't see unusual CPU or memory usage.


Solution

  • I think I finally found part of what's causing this... And the answer has to do with some details I didn't provide in my initial question.

    The target machine for my script is a domain controller, and network is setup with two domain controllers (for fault tolerance). If I make calls to -ComputerName "my.domain.com", I occasionally see the long delays... But if I just use the machine's IP address instead of the domain name, it goes through immediately.

    I still don't know why this only now just started having issues, and what the real root problem is... but this gives me something to at least have the script working until we can upgrade our environment.