首页 > 解决方案 > Script to append records as found or in batches from Invoke-Command

问题描述

I'm fairly new to powershell. The below is my attempt to return records of software on a list of systems via invoke-command. It does work. However, it seems like all results are stored in memory and then exported to the CSV all at once. Instead, I'd like to offload the results in batches or as they're returned. Whichever is the simplest method. That way, I can run similar similar CMDs from our servers, without it bogging down my server that's running the scripts, whose memory is at 99% load at the moment, and then the CPU jumps to 99% after the script completes to offload the results.

$IC_ScriptBlock = {
    Get-itemproperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\currentversion\Uninstall* |
        Select Publisher, DisplayName, DisplayVersion, installDate
        }
$IC_Params = @{
    ThrottleLimit = 100
    ScriptBlock = $IC_ScriptBlock
    ComputerName = (Get-Content "C:\Users\JT\Desktop\Scripts\laptops.txt")
    }
Invoke-Command @IC_Params |
    Export-csv -NoTypeInformation -Path "C:\Users\JT\Desktop\Scripts\laptops.csv" -Delimiter ";"

标签: powershellpowershell-remotinginvoke-command

解决方案


看起来下面是我需要的。

 $Computers = Get-Content "C:\Desktop\workstations.txt" -ReadCount 20
    FOREACH ($Computer in $Computers) {
    Invoke-Command -ComputerName $Computer -ScriptBlock {
    Get-itemproperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\currentversion\Uninstall\* | 
    Select @{Name="HostName";Expression={$Computer}}, Publisher, DisplayName, DisplayVersion, installDate} |
    Export-csv -NoTypeInformation -Path "C:\Desktop\results.csv" -Delimiter ";" -Append
    } 
    {
    Start-Sleep 1
    }

推荐阅读