首页 文章

Powershell SQLPS模块不在C#中导入

提问于
浏览
0

我正在尝试在C#内的Powershell中执行SQL查询 . 我使用ActiveDirectory cmdlet成功完成了这项工作,并希望更进一步 .

我的第一个问题是,当以下格式与ActiveDirectory一起使用时(在ISE中)它在C#中失败:

using (PowerShell pS = PowerShell.Create())
    {
        pS.AddCommand("import-module");
        pS.AddArgument("sqlps");
        pS.Invoke();
    }

我早已将安全设置为Unrestricted,但我得到的错误是:

CmdletInvocationException未处理文件C:\ Program Files(x86)\ Microsoft SQL Server \ 110 \ Tools \ PowerShell \ Modules \ sqlps \ Sqlps.ps1无法加载,因为在此系统上禁用了运行脚本 . 有关详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=135170上的about_Execution_Policies .

但是,如果我像这样运行,我得到没有错误,虽然后来的“Get-Module -all”调用没有显示模块的迹象:

using (PowerShell pS = PowerShell.Create())
    {
        pS.AddScript("Import-Module sqlps");
        pS.Invoke();
    }

如果我然后尝试导入ActiveDirectory模块并调用Get-Module,则不显示任何内容 .

这里发生了什么?

3 回答

  • 0

    我在sqlServer ps模块中遇到了类似的问题 . 看起来当从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,因为它更新 .

  • 0

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

    powershell.exe -executionpolicy bypass -command "& '\\somepath\somescript.ps1' "
    

    这允许调用远程脚本,因为即使使用不受限制的集合,我仍然发现它想要提示执行某些脚本,因此例如在任务调度程序中它将无法运行 .

    另外,当导入SQLPS时我也发现添加-DisableNameChecking标志很有用,你可能还想事先推送你的位置并在之后弹出它,否则你将最终进入SQLPS PSdrive,如果你需要它就无法访问本地位置 .

  • 0

    你尝试过这样的事吗?

    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 });
    

相关问题