首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未导入C#中的Powershell SQLPS模块

未导入C#中的Powershell SQLPS模块
EN

Stack Overflow用户
提问于 2014-06-19 21:13:49
回答 3查看 975关注 0票数 0

我试图在Powershell中,在C#中执行一个SQL查询。我已经成功地使用了ActiveDirectory cmdlet,并希望更进一步。

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

代码语言:javascript
复制
using (PowerShell pS = PowerShell.Create())
    {
        pS.AddCommand("import-module");
        pS.AddArgument("sqlps");
        pS.Invoke();
    }

很久以前,我已经将安全性设置为无限制的,但是我得到的错误是:

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

但是,如果像这样运行,则没有错误,尽管稍后的" get -Module -all“调用没有显示模块的迹象:

代码语言:javascript
复制
using (PowerShell pS = PowerShell.Create())
    {
        pS.AddScript("Import-Module sqlps");
        pS.Invoke();
    }

如果我试着导入ActiveDirectory模块并调用Get,它将不会显示任何内容。

这里发生了什么事?

EN

回答 3

Stack Overflow用户

发布于 2014-06-20 10:34:55

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

代码语言:javascript
复制
powershell.exe -executionpolicy bypass -command "& '\\somepath\somescript.ps1' "

这允许调用远程脚本,因为即使在无限制设置下,我仍然发现它希望提示某些脚本的执行,因此,例如在任务调度程序中,它将无法运行。

另外,在导入SQLPS时,我还发现添加-DisableNameChecking标志很有用,您还可能希望提前推送您的位置,然后再弹出它,否则如果需要的话,您将在SQLPS PSdrive中没有访问本地位置的权限。

票数 0
EN

Stack Overflow用户

发布于 2016-04-18 22:09:53

你试过这样的东西吗?

代码语言:javascript
复制
        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 });
票数 0
EN

Stack Overflow用户

发布于 2018-11-02 09:31:54

我在sqlServer ps模块上也有类似的问题。看起来,在从C#执行时,需要手动将模块加载到运行空间,这样才能工作。

代码语言:javascript
复制
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 \WindowsPowerShell\Modules\SqlServer“中找到。我将文件夹添加到解决方案中,以便能够在远程服务器上执行。您需要添加Microsoft.SqlServer.BatchParser.dll引用,以便从Powershell执行调用- the命令。您应该能够对sqlps模块执行同样的操作。而是使用SqlServer,因为它是新的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24316329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档