使用过:
private string RunScript(string storeNumber)
{
//string importSQL = "Import-Module sqlserver -DisableNameChecking";
//string executionPolicy = "Set-ExecutionPolicy -ExecutionPolicy Unrestricted";
//string script = "ping databaseName";
//string script = "sqlcmd - h - 1 - Q \"set nocount on;SELECT System_Date FROM Location_Codes\" - d pos - S databaseName | out-string";
string script = "invoke-sqlcmd -Query \"use pos set nocount on; SELCECT System_date FROM location_codes\" -serverinstance databaseName| out-string";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//pipeline.Commands.AddScript(importSQL);
//pipeline.Commands.AddScript(executionPolicy);
pipeline.Commands.AddScript(script);
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach(PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
MessageBox.Show(stringBuilder.ToString());
return stringBuilder.ToString();
}
尝试sqlcmd时,我没有收到任何错误,但没有返回任何内容(即使直接在Powershell中键入命令也可以得到我想要的数据)
尝试调用invoke-sqlcmd时,抛出CmdletInvocationException。 对于该错误,我添加了
<startup useLegacyV2RunttimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
添加了ping命令作为测试。那确实返回了数据。 任何帮助将不胜感激!
答案 0 :(得分:0)
这可能对您有帮助
从
更改
字符串脚本=“ invoke-sqlcmd -Query \”使用pos设置nocount; SELCECT System_date FROM location_codes \“ -serverinstance databaseName | out-string”;
收件人
字符串脚本= @“ invoke-sqlcmd -Query'use pos set nocount on 走 从位置代码的-serverinstance databaseName |中选择System_date字符串”;
我使用单个冒号的原因是,对于Powershell”用来表示字符串 而且我不认为Powershell会识别“;”用于sql分隔符。