无法从 PowerShell 执行 运行 bcp 命令

Unable to run bcp command from PowerShell

我必须从 PowerShell 脚本调用 bcp.exe。我的代码是:

$dataBase = 'MyDb'
$ProdEinheitTable = 'dbo.ProdEinheit'
$ProzessdatenTable = 'dbo.Prozessdaten_aktuell'
$sqlServerUserName = 'sa'
$sqlServerPassword = 'Password'
$server = 'MSSQLLocalDB'

$bcp = & 'C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe'

我这样调用 bcp 实用程序:

$bcp_args = "$bcp $dataBase.$ProdEinheitTable IN $datFileName -f $fmtFileName -U $sqlServerUserName -P sqlServerPassword -S $server -n"
Invoke-Expression $bcp_args

它给我错误

usage: : The term 'usage:' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ usage: C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe { ...
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (usage::String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

如果我从字符串中删除 & 我会得到异常

C:\Program : The term 'C:\Program' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe MyDb.dbo ...
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Program:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

如何从 PowerShell 调用 bcp

尝试以下操作:

$bcp = 'C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe'
$bcp_args = "$dataBase.$ProdEinheitTable IN $datFileName -f $fmtFileName -U $sqlServerUserName -P sqlServerPassword -S $server -n"

Start-Process -FilePath $bcp -ArgumentList $bcp_args

另一种使用调用运算符的方法,就像这里使用一个以某种方式正确工作的 args 数组:https://com2kid.wordpress.com/2011/09/25/powershell-call-operator-using-an-array-of-parameters-to-solve-all-your-quoting-problems/

$bcp = 'C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe'
$bcp_args = echo $bcp $dataBase.$ProdEinheitTable IN $datFileName -f $fmtFileName -U $sqlServerUserName -P sqlServerPassword -S $server -n
& $bcp $bcp_args

您的代码无法按预期方式工作的原因(除了您首先 shouldn't be using Invoke-Expression 之外)是因为您的预期似乎是

$bcp = & 'C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe'

将定义某种命令调用别名。事实并非如此。该语句不带参数直接调用bcp.exe并将命令的输出存储在变量$bcp中(正常输出,不是错误输出)

这应该有效:

$dataBase = 'MyDb'
$ProdEinheitTable = 'dbo.ProdEinheit'
$ProzessdatenTable = 'dbo.Prozessdaten_aktuell'
$sqlServerUserName = 'sa'
$sqlServerPassword = 'Password'
$server = 'MSSQLLocalDB'

$bcp = 'C:\Program Files\Microsoft SQL Server0\Tools\Binn\bcp.exe'

$bcp_args = "${dataBase}.${ProdEinheitTable}", 'IN', $datFileName,
            '-f', $fmtFileName, '-U', $sqlServerUserName,
            '-P', $sqlServerPassword, '-S', $server, '-n'

& $bcp @bcp_args