C# 从C使用Invoke-sqlcmdlet执行PowerShell脚本#
我需要执行一个简单的PS脚本,该脚本包含一个C#app中的Invoke-sqlcmdlet。当通过PS窗口执行脚本时,它工作正常。在C#app中,什么都不会发生 我尝试过C#应用程序中的其他脚本并获得了结果,但是这个特定脚本出现了问题C# 从C使用Invoke-sqlcmdlet执行PowerShell脚本#,c#,powershell,C#,Powershell,我需要执行一个简单的PS脚本,该脚本包含一个C#app中的Invoke-sqlcmdlet。当通过PS窗口执行脚本时,它工作正常。在C#app中,什么都不会发生 我尝试过C#应用程序中的其他脚本并获得了结果,但是这个特定脚本出现了问题 using (var powerShell = PowerShell.Create()) { powerShell.AddScript(psScript); powerShel
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)
导入模块SqlPs
调用Sqlcmd-ServerInstance$Server-Username$Username-Password$Password-Query$Script-QueryTimeout 750-ConnectionTimeout 600
有人知道如何解决这个问题吗?在向函数中添加一些错误记录代码后:
foreach (var error in powerShell.Streams.Error)
{
Console.WriteLine("Error: {0}", error);
}
它打印了一个问题,说您的参数没有到达脚本。经过深入研究,我发现了这篇关于如何将参数传递给Powershell的文章:
在此处缩减该解决方案的版本:
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);
}
}
}
正如@ByIf所述,如果您遇到异常问题:
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(对于控制台应用):
如果您正在使用MSTest,请尝试以下解决方案:
您能否验证正在启动的PS C#是否确实具有访问SQLPS模块的权限,并且是否成功加载了该模块?它加载不正确。木偶公爵回答后,我检查了Streams.Error属性,发现错误:“无法加载Windows PowerShell管理单元C:\Program Files(x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SqlPs\Microsoft.SqlServer.Management.PSSnapins.dll出现以下错误:无法加载一个或多个请求的类型。有关详细信息,请检索LoaderExceptions属性。混合模式程序集是根据运行时版本“v2.0.50727”生成的,无法在中加载如上文所述,在您回答后,我检查了Streams.Error属性并出现此错误:“无法加载Windows PowerShell管理单元C:\Program Files(x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SqlPs\Microsoft.SqlServer、 管理ns.dll,因为出现以下错误:无法加载一个或多个请求的类型。有关详细信息,请检索LoaderExceptions属性。混合模式程序集是根据运行时版本“v2.0.50727”生成的,如果没有其他配置信息,则无法在4.0运行时中加载。已尝试将e app.config,但没有任何结果。你是在控制台应用程序中运行它吗?我的测试控制台应用程序中的错误消息也有同样的问题。我添加到我的app.config:如果你切换到使用上面的运行空间和管道代码,它为我解决了所有问题。使用Runsapce和管道代码,我得到了一个System.Management.Automation.CmdletInvocationException的错误与使用以前的代码运行的错误相同。如果有问题,这将是一个MSTest项目。
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup>