PowerShell 學習筆記 - 3 使用 cmdlet

PowerShell 學習筆記 - 3 使用 cmdlet

本章主要探討 PowerShell 中 cmdlet 的使用方法,單獨拿出這一部分正是爲沒有 UNIX Shell 經驗的同窗設計的,例如必須參數與非必需參數以及篩選技巧等。數組

cmdlet 命令行參數

Get-Process 爲例,於 PowerShell Core Docker 容器中運行會獲得以下的結果:dom

PS /> Get-Process

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00      99.55       1.61       1   1 pwsh

同時對比 ps 命令的輸出結果,發現他們都可以獲得對着同一個進程的描述:函數

PS /> ps aux |grep -v ps
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  4.9 3204676 101356 pts/0  SLsl+ Sep18   0:01 pwsh

Linux 系統附加的 ps 是一個功能輸入過於複雜的程序反例,很大程度上違反了 UNIX 設計哲學中的 小便是美,以其能夠接受的命令行參數爲例:學習

This version of ps accepts several kinds of options:

       1   UNIX options, which may be grouped and must be preceded by a dash.
       2   BSD options, which may be grouped and must not be used with a dash.
       3   GNU long options, which are preceded by two dashes.

它直接支持 UNIX / BSD / GNU 三種風格的參數,且其幫助手冊 man ps 對其語法的描述爲:命令行

SYNOPSIS
       ps [options]

由於支持的參數形式實在太多,很難寫的詳細。這樣作的初衷由於描述一個進程的維度太多,而 UNIX 管道傳遞的是字符串ps 才提供大量正交的功能用以描述進程的方方面面,反觀 PowerShell 中的面向對象理念,獲取的進程對象能夠經過管道傳遞給下一個 cmdlet 用以操做:設計

# Get-Process 返回結果爲一個 System.ComponentModel.Component 類型的對象
PS /> (Get-Process).GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Process                                  System.ComponentModel.Component

# Get-Process 返回的對象擁有 93 個屬性
PS /> (Get-Process -Id 1 -IncludeUserName | Get-Member).Length
93

所以 Get-Process 中的語法部分也至關簡單(WIndows PowerShell 上面要複雜的多),只進行 getter 函數的功能:code

SYNTAX
    Get-Process [[-Name] <string[]>] [-Module] [-FileVersionInfo] [<CommonParameters>]

    Get-Process [[-Name] <string[]>] -IncludeUserName [<CommonParameters>]

    Get-Process -Id <int[]> [-Module] [-FileVersionInfo] [<CommonParameters>]

    Get-Process -Id <int[]> -IncludeUserName [<CommonParameters>]

    Get-Process -InputObject <Process[]> -IncludeUserName [<CommonParameters>]

    Get-Process -InputObject <Process[]> [-Module] [-FileVersionInfo] [<CommonParameters>]

該版本下默認給出了6種用法,這樣的標準語法描述與 UNIX Shell 是相同的,即:orm

  • 未直接包被 - 用戶可選擇加上該參數,這常會觸發必須參數或非必須參數
  • [] - 非必需參數
  • <> - 必須參數

以其中一條爲例:對象

# Get-Process -Id <int[]> -IncludeUserName [<CommonParameters>]
# -Id 爲用戶可選,後必須加 Id 構成的數組
# -IncludeUserName 爲用戶可選
# [<CommonParameters>] 表明常規參數

# -id 後不附加參數提示 Specify a parameter of type 'System.Int32[]' and try again. 即缺乏參數
PS /> Get-Process -Id
Get-Process : Missing an argument for parameter 'Id'. Specify a parameter of type 'System.Int32[]' and try again.
At line:1 char:13
+ Get-Process -Id
+             ~~~
+ CategoryInfo          : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.GetProcessCommand

# 附加參數便可
PS /> Get-Process -Id 1

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
      0     0.00      99.84       2.24       1   1 pwsh
      
# -IncludeUserName 是非必選的
PS /> Get-Process -Id 1 -IncludeUserName

     WS(M)   CPU(s)      Id UserName                       ProcessName
     -----   ------      -- --------                       -----------
     99.85     2.26       1 root                           pwsh

Select-Object 與格式化輸出

上文已經提到 PowerShell 管道傳遞的是對象,那麼如何基於對象去生成輸出,則須要藉助管道與 Format-* cmdlet 族,仍以 Get-Process 爲例,顯示所有屬性即爲藉助 Format-List 將經過管道傳遞的進程對象展開爲 List:排序

# 結果較長截取前幾項
PS /> Get-Process -Id 1 | Format-List *

Name                       : pwsh
Id                         : 1
PriorityClass              : Normal
FileVersion                :
HandleCount                : 119
WorkingSet                 : 107376640
PagedMemorySize            : 0
PrivateMemorySize          : 0
...

進一步的篩選屬性等則能夠經過 Select-Object / select 完成,例如從對象中選取某些字段生成新的對象:

# 選取部分屬性
PS /> Get-Process | select -Property PM,CPU

PM  CPU
--  ---
 0 6.11

# 經過 Select-Object 將對象依屬性篩選
PS /> Get-Process | select -Property PM,CPU | Get-Member
   TypeName: Selected.System.Diagnostics.Process
Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
CPU         NoteProperty System.Double CPU=6.1
PM          NoteProperty long PM=0

同時,select 還支持模擬 Linux 下的 head / last 的做用:

# 生成列,相似於 seq 1 10 的效果
PS /> 1..10
1
2
3
4
5
6
7
8
9
10

# Head
PS /> 1..10 | select -First  2
1
2

# Tail
PS /> 1..10 | select -Last 2
9   
10

結合 Sort-Object 等,可進一步的完成基本的文本排序篩選功能:

# 生成一個包含 10 個隨機數的數組
PS /> $array = foreach ($n in 1..10)
>> {
>>     Get-Random
>> }

# head / tail
PS /> $array | select -First 3
850010005
1643404153
1052124830
PS /> $array | select -Last 3
1845560963
1964683853
153356516

# sort
PS />  $array |Sort-Object | select -Last 3
1845560963
1934390288
1964683853

# 按屬性排序
PS /> Get-Module -ListAvailable | select -Property Version, Name| Sort-Object -Property Version

Version Name
------- ----
0.0     PSDesiredStateConfiguration
1.1.0.0 Microsoft.PowerShell.Archive
1.1.2   ThreadJob
1.1.7.2 PackageManagement
1.6.7   PowerShellGet
2.0.0   PSReadLine
6.1.0.0 Microsoft.PowerShell.Host
6.1.0.0 Microsoft.PowerShell.Management
6.1.0.0 Microsoft.PowerShell.Security
6.1.0.0 Microsoft.PowerShell.Utility

關於用於生成格式化輸出的 Format-* cmdlet 家族,請參考 Get-Help 中的相關內容,並不須要特別的背記,隨用隨查就能夠了。

相關文章
相關標籤/搜索