[英]System.Management.Automation.PowerShell does not return results for Get-Website from IIS
[英]C# Invoke powershell "Get-Website" always return empty
我正在嘗試使用 Powershell 從 C# 讀取我的 IIS 本地網站但我總是得到一個空輸出
public static ManageWebsite GetWebSiteStatus(string websiteName)
{
ManageWebsite websiteState = new ManageWebsite();
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create(); // Create a new PowerShell instance
ps.Runspace = runspace; // Add the instance to the runspace
ps.Commands.AddScript(@"Get-Website -Name """ + websiteName + @""" | %{$_.state}"); // Add a script
Collection<PSObject> results = ps.Invoke();
string powershell_output = string.Empty;
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
powershell_output = obj.BaseObject.ToString();
}
websiteState.Status = powershell_output;
websiteState.WebSite = websiteName;
return websiteState;
}
我不知道為什么,我總是使用該函數在 C# 中使用 powershell 調用其他東西並且總是工作正常
要檢查的幾件事:
你實例化了一個字符串生成器,但從不使用它
StringBuilder stringBuilder = new StringBuilder();
您將變量設置為空字符串,這沒問題,但每次循環遍歷對象時都會覆蓋它。 如果你永遠不會得到對象,它仍然是一個空字符串! 然后你分配給Status websiteState.Status。
string powershell_output = string.Empty;
foreach (PSObject obj in results)
{
powershell_output = obj.BaseObject.ToString();
}
websiteState.Status = powershell_output;
因此,如果您的網站名稱從未從 Get-Website 獲得結果,您將始終擁有一個沒有按預期設置的屬性的對象。 如果你從 Get-Website 得到結果,你只能從最后一個迭代對象中從 BaseObject.ToString() 中得到一些東西。 在嘗試分配值之前,您可能需要多做一點檢查,看看是否真的得到了一些東西。
更新評論
你可能想建立你的字符串
ps.Commands.AddScript($"Get-Website -Name {websiteName} | %{{$_.state}}");
我不確定您是否可以像您在 powershell 中期望的那樣訪問管道結果。 所以也許嘗試將數組存儲在您在腳本中返回顯式的 OutVariable 中。
謝謝你們。 我知道我是個白痴。 我的代碼 ps.Commands.AddScript(@"Get-Website -Name """ + websiteName + @""" | %{$_.state}"); // 添加一個腳本是在 IIS Express 中作用的,這就是為什么總是返回空
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.