2010-03-19 151 views
3

我需要使用bcp从远程SQL数据库中提取并保存一些表。我想编写一个PowerShell脚本来调用每个表的bcp并保存数据。到目前为止,我有这个脚本为bcp创建必要的参数。但是我无法弄清楚如何将参数传递给bcp。每次运行脚本时,它都会显示bcp帮助。这一定很容易,我没有得到。使用powershell脚本中的参数运行shell命令

#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 [email protected]{} 
$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 

回答

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

一些命令行应用程序需要接受带有斜杠,引号,双引号,等号,冒号,破折号,真正鸡尾酒的疯狂江南式参数。

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的(它咆哮着我并在我第一次尝试时显示出奇怪的字符)。

+0

请参阅我的[问题](http://stackoverflow.com/q/21524101/107537)。如果可以的话请帮忙。 – Vijay 2014-02-03 09:53:44

+0

这是值得检查Vijay的问题,因为它有一个比其他人更好的答案,如果你在PS V3。 – 2014-02-11 13:03:56

相关问题