[英]Powershell SQLPS module not importing within C#
我試圖從C#的Powershell內執行SQL查詢。 我已經使用ActiveDirectory cmdlet成功做到了這一點,並希望將其進一步發展。
我的第一個問題是,以下格式可用於ActiveDirectory(在ISE中),但在C#中失敗:
using (PowerShell pS = PowerShell.Create())
{
pS.AddCommand("import-module");
pS.AddArgument("sqlps");
pS.Invoke();
}
我早就將安全性設置為“不受限制”,但是我遇到的錯誤是:
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,它什么也沒顯示。
這里發生了什么?
我對C Sharp不太滿意,但是當從powershell外部調用腳本時,在執行程序時繞過執行策略會有一個標記,即
powershell.exe -executionpolicy bypass -command "& '\\somepath\somescript.ps1' "
這允許調用遠程腳本,因為即使使用不受限制的設置,我仍然發現它想提示某些腳本的執行,因此例如在任務計划程序中它將完全無法運行。
另外,在導入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 });
我在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-sql命令。 您應該能夠對sqlps模塊執行相同的操作。 而是使用SqlServer,因為它較新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.