2017-01-11 29 views
2

我想獲得一個PowerShell命令輸出到一個數組,但它似乎不工作。實際上,我想用行和列索引來解決輸出問題。 例如如何獲取PowerShell命令輸出到數組

$a=Get-Service 

隨着輸出(部分)

Status Name    DisplayName       
------ ----    -----------       
Stopped AeLookupSvc  Application Experience     
Stopped ALG    Application Layer Gateway Service  
Stopped AppIDSvc   Application Identity     
Running Appinfo   Application Information    
Stopped AppMgmt   Application Management  

欲解決對第二行中的顯示名稱,例如

$a[2][2] 

而且也應該給然後

Application Layer Gateway Service 

但這似乎並沒有工作。

任何人都可以幫忙嗎?

回答

4

這種類型的問題讓我覺得你可能來自Unix背景,習慣於處理索引和列索引等等。

從根本上說,PowerShell是一種面向對象的腳本語言。你根本不需要去做你在這裏問的問題。例如,如果你想捕獲結果,那麼爲一個對象獲取一個屬性,以下就是這樣做的。

首先捕獲輸出。

$a=Get-Service 

現在,您需要特定實體的特定屬性。爲了得到這個,索引到你想要的對象。

>$a[2] 
Status Name    DisplayName       
------ ----    -----------       
Stopped AJRouter   AllJoyn Router Service     

要選擇.DisplayName,所有你需要做的就是追加,爲你的前一個命令的結束。

> $a[2].DisplayName 
AllJoyn Router Service 

如果你想選擇多個值,你可以使用這種方法。

#Select multiple values from one entity 
$a[2] | select DisplayName, Status 

>DisplayName      Status 
-----------      ------ 
Application Layer Gateway Service Stopped 

#Select multiple values from each in the array 
$a | select DisplayName, Status 

>DisplayName            Status 
-----------            ------ 
Adobe Acrobat Update Service        Running 
AllJoyn Router Service         Stopped 
Application Layer Gateway Service      Stopped 
Application Identity          Stopped 
+0

謝謝,解決方案的工作原理! –

3

您在控制檯中看到的Get-Service的輸出可能看起來像一個數組(因爲它在發送到控制檯時被格式化爲表),但它實際上是一個'System.ServiceProcess.ServiceController'對象。

而不是使用行和列的名稱,你需要使用屬性的名稱進行檢索,所以對你的例子:

$a[2].DisplayName將返回Application Layer Gateway Service

6

這也不是沒有可能從一個映射屬性名稱到數組索引。請注意,您在輸出中看到的只是部分屬性列表(在某處的XML文件中定義)。因此,甚至沒有簡單的方法將它們轉換爲數組索引。

不過,我也不太瞭解你的需要這裏。如預期的那樣,您可以使用$a[1]獲得第二項服務。然後你可以用$a[1].DisplayName得到它的DisplayName屬性值。 PowerShell始終使用對象。根本沒有必要退回到文本解析或神祕的列索引來獲取您的數據。有一個更簡單的方法。

相關問題