C# Powershell SQLPS模块未在C中导入

C# Powershell SQLPS模块未在C中导入,c#,powershell,sqlps,C#,Powershell,Sqlps,我正在尝试从C中的Powershell中执行SQL查询。我已经成功地使用ActiveDirectory cmdlet执行了SQL查询,并希望进一步执行 我的第一个问题是,当以下格式在ActiveDirectory中工作时,在ISE中,它在C中失败: using (PowerShell pS = PowerShell.Create()) { pS.AddCommand("import-module"); pS.AddArgument(&q

我正在尝试从C中的Powershell中执行SQL查询。我已经成功地使用ActiveDirectory cmdlet执行了SQL查询,并希望进一步执行

我的第一个问题是,当以下格式在ActiveDirectory中工作时,在ISE中,它在C中失败:

using (PowerShell pS = PowerShell.Create())
    {
        pS.AddCommand("import-module");
        pS.AddArgument("sqlps");
        pS.Invoke();
    }
我早就将安全设置为“无限制”,但我得到的错误是:

未处理CmdleInvocationException

无法加载文件C:\Program Files x86\Microsoft SQL Server\110\Tools\PowerShell\Modules\sqlps\sqlps.ps1,因为在此系统上已禁用运行脚本。有关更多信息,请参阅上的关于执行策略

但是,如果我这样运行,则不会出现错误,尽管稍后的get模块-all调用没有显示模块的迹象:

using (PowerShell pS = PowerShell.Create())
    {
        pS.AddScript("Import-Module sqlps");
        pS.Invoke();
    }
如果然后尝试导入ActiveDirectory模块并调用Get模块,则不会显示任何内容


这是怎么回事?

我对C sharp不是很在行,但是当从powershell外部调用脚本时,在执行程序时会有一个标志来绕过执行策略,即

powershell.exe -executionpolicy bypass -command "& '\\somepath\somescript.ps1' "
这允许调用远程脚本,因为即使使用unrestricted set,我仍然发现它希望提示执行某些脚本,因此例如在任务调度器中,它将无法运行


此外,在导入SQLPS时,我还发现添加-DisableNameChecking标志很有用,您可能还希望事先推送您的位置,然后将其弹出,否则如果需要,您将在SQLPS PSdrive中无法访问本地位置。

您尝试过类似的方法吗

        PowerShell ps = PowerShell.Create();
        ps.AddScript("set-executionpolicy unrestricted -scope process");
        ps.AddScript("import-module sqlps");
        ps.AddScript("get-module sqlps");

        var m = ps.Invoke();
        foreach (var mm in m.Select(x => x.BaseObject as PSModuleInfo))
            Console.WriteLine(new { mm.Name, mm.Version });

我在SQLServerPS模块中遇到了类似的问题。看起来,当从C执行时,您需要手动将模块加载到运行空间中,以使其正常工作

string scriptText = File.ReadAllText("yourScript.ps1");

//This is needed to use Invoke-sqlcommand in powershell. The module needs to be loaded into the runspace before executing the powershell.

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { @"SqlServer\SqlServer.psd1" });

Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();

using (PowerShell psInstance = PowerShell.Create())
{
   psInstance.Runspace = runspace;
   psInstance.AddScript(scriptText);
   var PSOutput = psInstance.Invoke();
}
还要添加位于SqlServer.psd1中的所有引用。此文件通常位于C:\Program Files\WindowsPowerShell\Modules\SqlServer中。我将文件夹添加到解决方案中,以便能够在远程服务器上执行。 您需要添加Microsoft.SqlServer.BatchParser.dll引用,以便从Powershell执行invoke sqlcommand。
您应该能够对sqlps模块执行相同的操作。不如使用SqlServer,因为它比较新。

我从来没有遇到过任务调度程序的问题-我有很多脚本每晚都运行,没有问题。但是,我将查看是否有类似的解决方案可用于在C中执行。至于SQLPS的导入,我已经尝试了该参数,并指定了cmdlet以拉入导入模块SQLPS-cmdlet invoke sqlcmd,两者的结果都没有差异。虽然此代码可以回答这个问题,但最好包含一些上下文,解释它如何工作以及何时使用。从长远来看,只使用代码的答案是没有用的。