使用Powershell脚本中的参数运行Shell命令 [英] Run a shell command with arguments from powershell script

查看:106
本文介绍了使用Powershell脚本中的参数运行Shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用bcp从远程SQL数据库中提取并保存一些表.我想编写一个powershell脚本来为每个表调用bcp并保存数据.到目前为止,我已经有了此脚本,该脚本为bcp创建了必要的args.但是我不知道如何将args传递给bcp.每次我运行脚本时,它只会显示bcp帮助.这一定是我真正不容易做到的事情.

I need to extract and save a some tables from a remote SQL database using bcp. I would like to write a powershell script to invoke bcp for each table and save the data. So far I have this script that creates the necessary args for bcp. However I can not figure out how to pass the args to bcp. Every time I run the script it just shows the bcp help instead. This must be something really easy that I am not getting.

#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之类的任何行都不会执行任何操作(即使启用了严格模式;尽管抱怨会很不错).

First of all, $args is an automatic variable; you can't set it, so any line like $args = foo will do nothing (even with strict mode on; though a complaint would have been nice).

然后,您只将一个参数(字符串)传递给程序.我包含空格,但是空格可以正确地转义或用括号括起来,因此程序只能看到一个参数.

Then you are only passing a single argument (the string) to the program. I contains spaces, but they are properly escaped or enclosed in parentheses, so the program only sees a single argument.

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

You'll need to use an array for arguments to a program, instead of a single string, if you want to store it in a variable beforehand. And you need to name it something different than $args:

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

& $bcp_path $arguments

或者,实际上,您可以简单地将其写成一行,从而摆脱了这里的大多数丑陋之处.

Or, what I would prefer, actually, you can simply write it out in a single line which gets rid of most of the ugliness here:

$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脚本中的参数运行Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆