在 PowerShell 中将 sqlcmd 与 Start-Job 一起使用时出错

Error while using sqlcmd with Start-Job in PowerShell

当我在 PowerShell 中执行此命令时,一切正常:

sqlcmd -S dwh -i ".\script.sql" -o ".\log.txt"

但是,当我想设置多个作业时,以下命令不起作用:

Start-Job -Name TestSqlCmd -ScriptBlock {sqlcmd -S dwh -i ".\script.sql" -o ".\log.txt"}

我收到以下错误:

Sqlcmd: Error: Error occurred while opening or operating on file .\script.sql (Reason: The system cannot find the path specified).
    + CategoryInfo          : NotSpecified: (Sqlcmd: Error: ...ath specified).:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : localhost

你能帮我解决这个问题吗?

无论何时启动作业,作业中的脚本块实际上都会在新的 PS 会话中运行。因此,您不再被 cd 到同一路径,但您可以执行以下操作来解决此问题:

Start-Job -Name TestSqlCmd -ScriptBlock {
    Param(
        $path
    )
    echo "$path\script.sql" 
    echo "$path\log.txt"
} -ArgumentList (Get-Location).Path

或者只在脚本块中添加完整路径。

Powershell 7 也有一个 -workingdirectory 参数。实际上,ps 7 中的 start-job 或 start-threadjob 无论如何都尊重当前目录。