3

我需要使用 bcp 从远程 SQL 数据库中提取并保存一些表。我想编写一个 powershell 脚本来为每个表调用 bcp 并保存数据。到目前为止,我有这个脚本可以为 bcp 创建必要的参数。但是我不知道如何将参数传递给 bcp。每次我运行脚本时,它只会显示 bcp 帮助。这一定是我没有得到的非常容易的事情。

#commands bcp database.dbo.tablename out c:\temp\users.txt -N -t, -U uname -P pwd -S <servername>
$bcp_path = "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"
$serverinfo =@{}
$serverinfo.add('table','database.dbo.tablename')
$serverinfo.add('uid','uname')
$serverinfo.add('pwd','pwd')
$serverinfo.add('server','servername')
$out_path= "c:\Temp\db\"
$args = "$($serverinfo['table']) out $($out_path)test.dat -N -t, -U $($serverinfo['uid']) -P $($serverinfo['pwd']) -S $($serverinfo['server'])"

#this is the part I can't figure out
& $bcp_path $args
4

2 回答 2

5

首先,$args是一个自动变量;你不能设置它,所以任何类似的行都$args = foo不会做任何事情(即使在严格模式下;尽管投诉会很好)。

然后,您只需将一个参数(字符串)传递给程序。I 包含空格,但它们被正确地转义或括在括号中,因此程序只能看到一个参数。

如果您想预先将其存储在变量中,则需要使用数组作为程序的参数,而不是单个字符串。您需要将其命名为不同于$args

$arguments = "$($serverinfo['table'])",
             'out',"$($out_path)test.dat",
             '-N','-t,',
             '-U',"$($serverinfo['uid'])",
             '-P',"$($serverinfo['pwd'])",
             '-S',"$($serverinfo['server'])"

& $bcp_path $arguments

或者,我更喜欢的是,实际上,您可以简单地将其写在一行中,从而消除这里的大部分丑陋:

$out_path = 'c:\Temp\db'
& $bcp_path $serverinfo['table'] out $out_path\test.dat -N '-t,' -U $serverinfo['uid'] -P $serverinfo['pwd'] -S $serverinfo['server']
于 2010-03-19T22:10:51.000 回答
1

一些命令行应用程序需要接受带有斜线、引号、双引号、等号、冒号、破折号、名副其实的鸡尾酒的疯狂江南风格参数。

根据我的经验,PowerShell 有时无法应对。所以我写出一个 .cmd 文件并从 cmd.exe 执行它,如下所示:

echo $("Running command: " + $commandLine);

$rnd = $(([string](Get-Random -Minimum 10000 -Maximum 99999999)) + ".cmd");
$commandFilePath = $(Join-Path -Path $env:TEMP -ChildPath $rnd);
echo $commandLine | Out-File -FilePath $commandFilePath -Encoding ascii;

& cmd.exe /c $commandFilePath

确保输出为 ASCII,因为默认的 Unicode 可能无法与 cmd.exe 配合使用(它对我咆哮并在我第一次尝试时显示奇怪的字符)。

于 2012-12-20T16:59:21.800 回答