[英]Trouble getting result of PowerShell command in C#
對於C#來說還很陌生,我正在嘗試編寫一個簡單的工具來檢查服務器上的特定角色和功能,並顯示是否已安裝。 簡單!
問題是我一生都無法弄清楚如何捕獲此Powershell命令(以C#字符串格式)的Installed State值:
"Get-WindowsFeature | ? {$_.Name -match \"Web-Mgmt-Console\"} | Select -exp Installed State"
該命令本身在Powershell中運行(刪除\\時),並且僅返回“ false”。 我的代碼嘗試捕獲此結果。
cmd = "Get-WindowsFeature | ? {$_.Name -match \""+winFeatures[i]+
"\"} | Select -exp Installed State";
cmdout = ps.AddScript(cmd).Invoke().ToString();
代替“安裝狀態”,cmdout的VS中的值顯示為"System.Collections.ObjectModel.Collection1[System.Management.Automation.PSObject]"
,這很酷。 我知道.Invoke()將返回一個集合,因此.ToString()
應該采用結果(“ True”或“ False”,並將其作為字符串返回給cmdout)。
我在這里想念什么? 令人驚奇的是,Powershell在shell中如此簡單,而在C#
卻如此困難。 我已經搜尋和閱讀2天了,還沒弄清楚。
調用后,您需要嘗試使用其變量名來獲取輸出值,如下所示:ps.Runspace.SessionStateProxy.GetVariable(“ counter”)。
您需要檢查結果的變量名稱。
否則您可以像下面這樣進行操作,因為結果將是PSObject的集合
foreach (PSObject result in ps.Invoke())
{
MessageBox.Show(result.BaseObject.ToString() + "\n");
}
只是直接獲取值字符串與集合並嘗試強制cmd中的字符串怎么辦...
(Get-WindowsFeature | ? {$_.Name -match 'Web-Mgmt-Console'})
Display Name Name Install State
------------ ---- -------------
[X] IIS Management Console Web-Mgmt-Console Installed
(Get-WindowsFeature | ? {$_.Name -match 'Web-Mgmt-Console'}) | Get-Member
TypeName: Microsoft.Windows.ServerManager.Commands.Feature
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj), bool IEquatable[Feature].Equals(Microsoft.Windows.ServerManager.Commands.Feature ot...
GetHashCode Method int GetHashCode()
GetType Method type GetType()
SetProperties Method void SetProperties(string displayName, string description, bool installed, Microsoft.Windows.ServerManager.Commands...
ToString Method string ToString()
AdditionalInfo Property hashtable AdditionalInfo {get;}
BestPracticesModelId Property string BestPracticesModelId {get;}
DependsOn Property string[] DependsOn {get;}
Depth Property int Depth {get;}
Description Property string Description {get;}
DisplayName Property string DisplayName {get;}
EventQuery Property string EventQuery {get;}
FeatureType Property string FeatureType {get;}
Installed Property bool Installed {get;}
InstallState Property Microsoft.Windows.ServerManager.Commands.InstallState InstallState {get;}
Name Property string Name {get;}
Notification Property Microsoft.Windows.ServerManager.ServerComponentManager.Internal.Notification[] Notification {get;}
Parent Property string Parent {get;}
Path Property string Path {get;}
PostConfigurationNeeded Property bool PostConfigurationNeeded {get;}
ServerComponentDescriptor Property psobject ServerComponentDescriptor {get;}
SubFeatures Property string[] SubFeatures {get;}
SystemService Property string[] SystemService {get;}
(Get-WindowsFeature | ? {$_.Name -match 'Web-Mgmt-Console'}).Installed
True
(Get-WindowsFeature | ? {$_.Name -match 'Web-Mgmt-Console'}).InstallState
Installed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.