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

Mik*_*ghe 3 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
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 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
Run Code Online (Sandbox Code Playgroud)

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

$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']
Run Code Online (Sandbox Code Playgroud)