我试图在Powershell中,在C#中执行一个SQL查询。我已经成功地使用了ActiveDirectory cmdlet,并希望更进一步。
我的第一个问题是,当以下格式与ActiveDirectory (在ISE中)一起工作时,它在C#中失败:
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“调用没有显示模块的迹象:
using (PowerShell pS = PowerShell.Create())
{
pS.AddScript("Import-Module sqlps");
pS.Invoke();
}如果我试着导入ActiveDirectory模块并调用Get,它将不会显示任何内容。
这里发生了什么事?
发布于 2014-06-20 10:34:55
我不太擅长C夏普,但是当从powershell外部调用脚本时,在执行程序时会有一个标志来绕过执行策略,即
powershell.exe -executionpolicy bypass -command "& '\\somepath\somescript.ps1' "这允许调用远程脚本,因为即使在无限制设置下,我仍然发现它希望提示某些脚本的执行,因此,例如在任务调度程序中,它将无法运行。
另外,在导入SQLPS时,我还发现添加-DisableNameChecking标志很有用,您还可能希望提前推送您的位置,然后再弹出它,否则如果需要的话,您将在SQLPS PSdrive中没有访问本地位置的权限。
发布于 2016-04-18 22:09:53
你试过这样的东西吗?
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 });发布于 2018-11-02 09:31:54
我在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 \WindowsPowerShell\Modules\SqlServer“中找到。我将文件夹添加到解决方案中,以便能够在远程服务器上执行。您需要添加Microsoft.SqlServer.BatchParser.dll引用,以便从Powershell执行调用- the命令。您应该能够对sqlps模块执行同样的操作。而是使用SqlServer,因为它是新的。
https://stackoverflow.com/questions/24316329
复制相似问题