0

I'm trying to run a Powershell script that pulls data from an APM device across a date range. However it can take up to 9 hours for a week date range. When I run it in a for loop day by date, it takes 35 minutes:

for($i = 0; $i -lt $dateList.Length-1; $i++){
    & "C:\Scripts\Grabber.ps1" -date  $dateList[$i] -date2 $dateList[$i+1]
}

I need to optimize that further. I've looked at PoshRSJob and Invoke-Parallel, but I can't seem to get my head around this! I'd appreciate any help, thanks.

  • so whats the problem? I'd definitely go with Runspaces for that – 4c74356b41 Feb 06 '17 at 11:51
  • @4c74356b41 can you recommend a resource? Tried technet but I get a syntax error: [link](https://blogs.technet.microsoft.com/heyscriptingguy/2015/11/26/beginning-use-of-powershell-runspaces-part-1/) error: "An expression was expected after '('." code:$Runspace = [runspacefactory]::CreateRunspace() $PowerShell = ::Create() $PowerShell.runspace = $Runspace $Runspace.Open() [void]$PowerShell.AddScript({ Get-Date Start-Sleep -Seconds 10 }) $AsyncObject = $PowerShell.BeginInvoke() – ConfusedNomad Feb 06 '17 at 12:02
  • Nah, I mean PoshRSJob, unless you want to reinvent the wheel – 4c74356b41 Feb 06 '17 at 12:06
  • To clarify: I want to run the Grabber.ps1 everyday for 7 days. Each day will have to invoke the grabber.ps1 script in parallel. Does that make sense? – ConfusedNomad Feb 06 '17 at 12:08
  • @4c74356b41 ok thanks. How do I invoke the script and pass in date values as parameters? I can only see examples of script blocks. – ConfusedNomad Feb 06 '17 at 12:16
  • http://stackoverflow.com/questions/12766174/how-to-execute-a-powershell-function-several-times-in-parallel#12768438 – gvee Feb 06 '17 at 12:45
  • Possible duplicate of [How to execute a Powershell function several times in parallel](http://stackoverflow.com/questions/12766174/how-to-execute-a-powershell-function-several-times-in-parallel) – gvee Feb 06 '17 at 12:45

1 Answers1

0

Well, just include your script in the scriptblock?

for($i = 0; $i -lt $dateList.Length-1; $i++){
    start-rsjob -name {$_} -ScriptBlock {
        & "C:\Scripts\Grabber.ps1" -date  ($using:dateList)[$using:i] -date2 ($using:dateList)[$using:i+1] 
    }
}
4c74356b41
  • 69,186
  • 6
  • 100
  • 141
  • It's a slow Monday.. cheers. However now I get a "expression is not allowed inside a using expression" on the $i variable. I just passed in a date as a string and the script executes, but isn't running as it should. It doesn't even hit the print statement at the top of the grabber.ps1 script. Any ideas? – ConfusedNomad Feb 06 '17 at 15:15
  • well, reassign $i and $datelist inside scriptblock to new variables, and use them – 4c74356b41 Feb 06 '17 at 15:25
  • 1) You should `$using:i` as well. 2) You should use parenthesis to not cause parse error: `($using:dateList)[$using:i]`. – user4003407 Feb 06 '17 at 16:28