我需要执行一个包含来自C#app的Invoke-Sqlcmd cmdlet的简单PS脚本。当脚本通过PS窗口执行时,它可以正常工作。在C#app中没有任何事情发生。
我已经尝试过C#应用程序中的其他脚本并获得了结果,但是这个特定的脚本出了问题。
using (var powerShell = PowerShell.Create())
{
powerShell.AddScript(psScript);
powerShell.AddParameter("Username", "user");
powerShell.AddParameter("Password", "password");
powerShell.AddParameter("Server", server);
powerShell.AddParameter("Script", script);
var result = powerShell.Invoke();
}
PS脚本:
param ([String]$Username, [String]$Password, [String]$Server, [String]$Script)
Import-Module SqlPs
Invoke-Sqlcmd -ServerInstance $ Server -Username $ Username -Password $ Password -Query $ Script -QueryTimeout 750 -ConnectionTimeout 600
有谁知道如何解决这个问题?
答案 0 :(得分:0)
在您的函数中添加一些错误记录代码后:
foreach (var error in powerShell.Streams.Error)
{
Console.WriteLine("Error: {0}", error);
}
它打印出一个问题,说明您的参数未到达脚本。经过一番挖掘,我找到了关于如何将参数传递给Powershell的SO帖子:
Execute PowerShell Script from C# with Commandline Arguments
在此处删除该解决方案的版本:
using (Runspace runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create()))
{
runspace.Open();
using (Pipeline pipeline = runspace.CreatePipeline())
{
Command scriptCommand = new Command(psScript);
scriptCommand.Parameters.Add(new CommandParameter("Username", "user"));
scriptCommand.Parameters.Add(new CommandParameter("Password", "password"));
scriptCommand.Parameters.Add(new CommandParameter("Server", server));
scriptCommand.Parameters.Add(new CommandParameter("Script", script));
pipeline.Commands.Add(scriptCommand);
var results = pipeline.Invoke();
foreach (var item in results)
{
Console.WriteLine("Output: {0}", item);
}
}
}
如@bymyself所述,如果您遇到异常问题:
Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
尝试将此添加到您的app.config(对于控制台应用):
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup>
如果您使用的是MSTest,请尝试以下解决方案: http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/