I'm creating a Powershell script to backup 2 PostgreSQL databases using Postgres' pg_dump
tool. I'm using Powershell 2.0 on Windows 7 and PostgreSQL 9.3.
The simplified script looks like this:
$postgresDir="C:\PostgreSQL\9.3"
$pgUser="postgres"
$pgPort="5432"
$dbName1="db1"
$dbName2="db2"
$currentBackupFile1 = "C:\temp\backup\1.backup"
$currentBackupFile2 = "C:\temp\backup\2.backup"
& ($postgresDir + "\bin\pg_dump.exe") ("-U" + $pgUser) ("--dbname=" + $dbName1) ("--port=" + $pgPort) ("--file=`"" + $currentBackupFile1 + "`"") -v 2>&1 | out-host
& ($postgresDir + "\bin\pg_dump.exe") ("-U" + $pgUser) ("--dbname=" + $dbName2) ("--port=" + $pgPort) ("--file=`"" + $currentBackupFile2 + "`"") -v 2>&1 | out-host
Everything works as expected when the script is run from Windows Powershell IDE. But when the script is started from commandline or via a batch file like this:
powershell -file pg_dump.ps1
, only the first pg_dump gets executed, the second is simply ignored without any errors. Other Powershell cmdlets that follow after these statements are executed normally.
The problem vanishes as soon as I remove the stderr redirection (2>&1
) at the end of the statements, making it
& ($postgresDir + "\bin\pg_dump.exe") ("-U" + $pgUser) ("--dbname=" + $dbName1) ("--port=" + $pgPort) ("--file=`"" + $currentBackupFile1 + "`"") -v | out-host
Also, the problem does not apply to other programs per se. For example, when substituting the pg_dumps with two & dir 2>&1
statements, these statements are both executed when run from a batch script. It may be a pg_dump thing.
Update in reply to Ansgar Wiechers comment.
Using splatting like this:
$exe=($postgresDir + "\bin\pg_dump.exe")
$args1= '-U', $pgUser, '--dbname', $dbName1, '--port', $pgPort, '--file', $currentBackupFile1, '2>&1'
& $exe @args1
leads to pg_dump complaining about having too many command line arguments. Using it like this:
$exe=($postgresDir + "\bin\pg_dump.exe")
$args1 = '-U', $pgUser, '-d', $dbName1, '-p', $pgPort, '-f', $currentBackupFile1
& $exe @args1 2>&1
$args2 = '-U', $pgUser, '-d', $dbName2, '-p', $pgPort, '-f', $currentBackupFile2
& $exe @args2 2>&1
yields the same result as the first example.