我正在使用Postgres的pg_dump
工具创建一个Powershell脚本来备份2个PostgreSQL数据库。我在Windows 7和PostgreSQL 9.3上使用Powershell 2.0。
简化的脚本如下所示:
$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
从Windows Powershell IDE运行脚本时,一切都按预期工作。但是当脚本从命令行启动或通过这样的批处理文件启动时:
powershell -file pg_dump.ps1
,只有第一个pg_dump被执行,第二个被简单地忽略而没有任何错误。在这些语句之后执行的其他Powershell cmdlet将正常执行。
一旦我在语句末尾删除了stderr重定向(2>&1
),问题就消失了吗
& ($postgresDir + "\bin\pg_dump.exe") ("-U" + $pgUser) ("--dbname=" + $dbName1) ("--port=" + $pgPort) ("--file=`"" + $currentBackupFile1 + "`"") -v | out-host
此外,该问题本身并不适用于其他程序。例如,当用两个& dir 2>&1
语句替换pg_dumps时,这些语句在从批处理脚本运行时都会执行。这可能是一个pg_dump的事情。
更新回复Ansgar Wiechers的评论。
使用这样的splatting:
$exe=($postgresDir + "\bin\pg_dump.exe")
$args1= '-U', $pgUser, '--dbname', $dbName1, '--port', $pgPort, '--file', $currentBackupFile1, '2>&1'
& $exe @args1
导致pg_dump抱怨有太多的命令行参数。像这样使用它:
$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
产生与第一个例子相同的结果。