使用powershell脚本中的参数运行shell命令

时间:2010-03-19 17:48:32

标签: powershell bcp

我需要使用bcp从远程SQL数据库中提取并保存一些表。我想编写一个powershell脚本来为每个表调用bcp并保存数据。到目前为止,我有这个脚本为bcp创建必要的args。但是我无法弄清楚如何将args传递给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

2 个答案:

答案 0 :(得分:5)

首先,$args是一个自动变量;你不能设置它,所以任何像$args = foo这样的行都不会做任何事情(即使有严格的模式开启;虽然投诉会很好)。

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

如果要事先将变量存储在变量中,则需要使用数组作为程序的参数,而不是单个字符串。您需要将其命名为与$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']

答案 1 :(得分: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(它在我看来并且在我第一次尝试时显示了奇怪的字符)。

相关问题