如何使用通过.net传入的参数从powershell调用BCP?

时间:2014-06-10 17:32:20

标签: c# powershell

我有以下c#代码:

var powerShell = PowerShell.Create();
            powerShell.Runspace = runspace;
            powerShell.AddArgument(connectionString);
            powerShell.AddArgument(storedProc);
            powerShell.AddArgument(dataSource);
            powerShell.AddArgument(filterList);
            powerShell.AddArgument(destinationFile);
            var script = "path\to\the\powershell.ps1";
            powerShell.AddScript(script);
            powerShell.Invoke();

我希望它可以使用这个PowerShell脚本:

$connString = $args[0]
$spName = $args[1]
$dataSource = $args[2]
$filterList = $args[3]
$destinationFile = $args[4]
bcp "$spName $filterList" queryout "$destinationFile" -c -t"\0" $connString

我没有使用PowerShell的经验。这看起来对你们和女孩们来说都是正确的吗?那么.NET代码呢?那会像我假设的那样运行脚本吗?

1 个答案:

答案 0 :(得分:0)

你的C#需要一些调整。首先,在添加命令之前,您无法添加参数。其次,AddScript()方法需要Powershell.ps1的脚本内容 - 而不是路径。试试这个:

var ps = PowerShell.Create();
ps.Runspace = runspace;
var script = System.IO.File.ReadAllText(@"path\to\the\powershell.ps1");
ps.AddScript(script)
ps.AddArgument(connectionString);
ps.AddArgument(storedProc);
ps.AddArgument(dataSource);
ps.AddArgument(filterList);
ps.AddArgument(destinationFile);
var results = ps.Invoke();