Search code examples
powershellfirebirddatabase-backups7zip

Powershell wait until process completes running simultaneous processes


I have a powershell script that will kick off multiple instances of two different processes.

I want to be able to launch multiple simultaneous instances of gbak, and I don't want 7zip to start at all until the first instance of gbak finishes, and I want a new instance of 7zip to start each time an instance of gbak finishes.

Here is my script as it stands:

Import-Module "sqlps" -DisableNameChecking
Invoke-Sqlcmd -Query "USE ASPNETDB; SELECT DATABASELOCATION, SITEID FROM FIREBIRDCONNECTIONS;" -ServerInstance "DV-SQLSTAG01\EXPRESS2014" | Export-CSV - Path "C:\Scripts\strings.csv"
C:
CD C:\Scripts
$fbConn = Import-Csv -Path .\strings.csv
ForEach ($site in $fbConn) {
$cString = $site.DATABASELOCATION
$siteid = $site.SITEID
$backupDir = "D:\DBBackups"
$backupFile = "Cpib_$siteid.bak"
$gbak = ".\gbak.exe"
$gbakArgs = "-b -g -user sysdba -password masterkey $cString $backupDir\$backupFile"
$7zip = ".\7za.exe"
$7zArgs = "a -v1g -r -y -t7z -mx=3 $backupDir\CPIB_$siteid@$(get-date -f yyyyMMdd).7za $backupDir\$backupFile"
Start-Process $gbak $gbakArgs
Start-Process $7zip $7zArgs
}

What the application is doing now is launching all instances of gbak and 7zip at the same time, all at once. I can use a wait command after the start-process command for gbak, but then it will only launch one instance of gbak. I want it to have them all going at once.


Solution

  • I sugguest you to work with Jobs. Use the Start-Job cmdlet to start a new Job foreach of your sites. They will run in parallel so you can add the -Waitswitch to the gbak process again. Finally, retrieve all Jobs using the Get-Job cmdlet and wait until they finish using Wait-Job