题
我需要提取和使用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
解决方案
首先,$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']
其他提示
这需要接受疯狂的江南风格的参数用斜杠,引号,双引号,等于,冒号,破折号,成为名副其实的鸡尾酒。
一些命令行应用程序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的输出(它咆哮我,表现出对我的第一次尝试奇怪的字符)。
不隶属于 StackOverflow