[Powershell] Powershell簡明教程


Visual Studio Code搭建Powershell環境

  1. 下載並安裝Visual Studio Code。
    https://code.visualstudio.com/

  2. 安裝powershell擴展。
    width=200px

  3. 關閉,重新打開Visual Studio Code。

  4. 新建文件並另存為Powershell擴展名。系統自動加載Powershell插件來進行編譯。
    上面代碼區,使用F5編譯執行; 下面是交互模式。

Powershell模塊

服務器添加角色的時候,對應的Powershell Module也一並安裝。

默認的模塊存放位置: C:\Windows\system32\windowspowershell\v1.0\modules

一個module包含:

  • Command Let
  • Alias
  • Function
  • Application

使用module的流程:獲取Module -> 安裝Module -> 使用Module中的命令

查看當前加載的Module

get-module

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Manifest   1.0.0.0    NetTCPIP                            {Find-NetRoute, Get-NetCompartment, Get-NetIPAddress, Get-...
Script     2.0.0      PSReadline                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PS...

查看命令所屬於的Module

get-command get-alias | ft name, commandtype, module

Name      CommandType Module
----      ----------- ------
Get-Alias      Cmdlet Microsoft.PowerShell.Utility

Powershell會隨着運行命令,而自動加載命令所屬的模塊。

查看系統中所有可用的Module

get-module -ListAvailable

    目錄: C:\Program Files\WindowsPowerShell\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.1.1      HackSql
*忽略中間部分*
Manifest   2.1.0.0    xMySql                              {Get-ArchitectureName, Get-MySqlExe, Get-ShortVersion, Get...


    目錄: C:\Windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.0.0    AppBackgroundTask                   {Disable-AppBackgroundTaskDiagnosticLog, Enable-AppBackgro...
*忽略中間部分*
Manifest   1.0.0.0    WindowsUpdate                       Get-WindowsUpdateLog

從Powershell Gallery中查找Module

Find-Module -name *qrcode*

Version    Name                                Repository           Description
-------    ----                                ----------           -----------
2.6.0      QRCodeGenerator                     PSGallery            creates QR codes offline
1.2.0.80   QrCodes                             PSGallery            PowerShell module that uses the Google ZXing.Net library to generate QRCodes.
1.0.1      QRCodeSt                            PSGallery            Automatically Creates QR codes as PNG images filled with whatever info you want. Works on all PowerShell versions and editions 
'''

從Powershell Gallery中安裝Module
···
Find-Module -name QRcodeGenerator  |Save-Module -Path C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

獲取一個Module中的命令

Get-Command -Module QRCodeGenerator -noun QR*

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           New-QRCodeGeolocation                              2.6.0      QRCodeGenerator
Alias           New-QRCodeText                                     2.6.0      QRCodeGenerator
Alias           New-QRCodeTwitter                                  2.6.0      QRCodeGenerator

Powershell命令

Powershell命令的形式
Powershell命令的格式是Verb-Noun的形式存在。

Powershell命令的幫助
Get-Command -module -verb -noun命令獲取命令的名稱。
Get-Help 命令查看命令的幫助。
Update-Help更新命令的幫助文件。

命令幫助的解釋
Get-Process [[-Name] <System.String[]>] [-ComputerName <System.String[]>] [-FileVersionInfo] [-Module] [ ]

  • 參數兩邊的中括號,代表這個參數是可選的。
  • [-name] <System.String[]>中, [-name]代表參數名稱可以省略,所以就是位置參數。 <System.String[]>是字符串數組。

Powershell的別名
Alias的目的為了符合管理員的操作習慣或者向后兼容。

Get-Alias獲取系統中的所有別名。

get-alias

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           Add-AppProvisionedPackage                          3.0        Dism
Alias           Add-ProvisionedAppPackage                          3.0        Dism

Get-Alias 別名 顯示出別名的詳細信息

Get-Alias cat | fl


DisplayName       : cat -> Get-Content
CommandType       : Alias
Definition        : Get-Content
ReferencedCommand : Get-Content
ResolvedCommand   : Get-Content

Powershell Provider

Powershell所支持的層次化結構數據,例如:文件系統,注冊表、證書服務。 都是建立在powershell的provider之上的。

導入模塊Import-Module的時候,也可能會添加新的PSProvider,例如ActiveDirectory模塊。

Get-PSProvider 查看系統所支持的Provider。

Get-PSProvider

Name                 Capabilities                                      Drives
----                 ------------                                      ------
Registry             ShouldProcess, Transactions                       {HKLM, HKCU}
Alias                ShouldProcess                                     {Alias}
Environment          ShouldProcess                                     {Env}
FileSystem           Filter, ShouldProcess, Credentials                {C, D, E}
Function             ShouldProcess                                     {Function}
Variable             ShouldProcess                                     {Variable}

Get-PSDrive 查看PSProvider所提供的結構化目錄。

Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                              
----           ---------     --------- --------      ----                                               
Alias                                  Alias
C                 180.90         19.10 FileSystem    C:\
Cert                                   Certificate   \
D                 218.18         57.51 FileSystem    D:\
E                   0.87         28.85 FileSystem    E:\
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

Powershell的變量

Powershell定義的變量,會臨時存儲到PSProvider的Variable中。

Powershell的對象

對象的屬性類型:

  • Property: dotnet定義對象的原生屬性。
  • AliasProperty: dotnet定義對象屬性的別名。
  • ScriptProperty:通過執行一些腳本來獲取信息。

對象的方法:
可以在微軟的dotnet中類的說明中查看幫助。

Powershell與對象操作相關的命令

Powershell導出內容

out系命令

get-command -Module Microsoft.Powershell.* -verb out

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Out-Default                                        3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-File                                           3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-GridView                                       3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-Host                                           3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-Null                                           3.0.0.0    Microsoft.PowerShell.Core
Cmdlet          Out-Printer                                        3.1.0.0    Microsoft.PowerShell.Utility
Cmdlet          Out-String                                         3.1.0.0    Microsoft.PowerShell.Utility

Out-Host: 將內容直接輸出到屏幕上。所有命令執行的時候,都是默認將命令Pipeline到out-host的InputObject參數。
Out-host的Paging開關參數可以讓輸出進行分頁和分行顯示。

Out-host -InputObject (Get-Service) -Paging

Status   Name               DisplayName
------   ----               -----------
Running  AarSvc_1b4f241     Agent Activation Runtime_1b4f241
Running  AdobeUpdateService AdobeUpdateService
Running  AGMService         Adobe Genuine Monitor Service

Out-File: 將輸出的內容放置到文件。主要是接受Pipeline過來的內容。

Out-File -FilePath d:\service.txt -InputObject (Get-Service)

Out-Gridview: 將數據導出到一個圖形化的界面顯示。
image

Out-Null:接收到的對象不會再不進行pipeline傳輸,屏幕也不顯示所有的輸出內容。

Out-String: 將獲得的對象轉為文本並顯示到屏幕。

Export系命令

Export-Csv:導出csv文件。

get-process | export-csv -path d:\leo.csv
-append 附加信息到現有文件
-encoding:調整編碼,解決亂碼問題

Export-Clixml: 導出xml文件

Get-Service |Export-Clixml -path d:\leo.xml

Export-Clixml導出的信息比Export-Csv導出的更加全面。

Powershell信息的格式化輸出

Format-List:以列表的形式顯示內容。

Get-Service | Format-List -Property DisplayName,StartType,Status
DisplayName : Agent Activation Runtime_958d60
StartType   : Manual
Status      : Running

Format-Table: 用表格的形式顯示內容。

Get-Service | Format-Table -Property DisplayName,Status

DisplayName                                                   Status
-----------                                                   ------
Agent Activation Runtime_958d60                              Running
AdobeUpdateService                                           Running
Adobe Genuine Monitor Service                                Running
Adobe Genuine Software Integrity Service                     Running
AllJoyn Router Service                                       Stopped

當內容超過屏幕的寬度的時候,無法顯示出所有的列內容。

Format-Wide:只能顯示一個屬性的值,使用類似於填充寬度的方式進行顯示,類似於dos的dir /w。使用價值不大。

Powershell的內容過濾

Where-Object對於管道傳遞過來的對象集合進行篩選,保留符合條件的對象。

get-process | Where-Object -Property name -eq notepad

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    365      25     8680      27612       0.31  22192   4 notepad

比較運算符 -eq , -ne, -le, -lt, -ge, -gt, -like, -in

get-service | Where-Object -Property name -in @('winrm', 'windefend')

Status   Name               DisplayName
------   ----               -----------
Stopped  WinDefend          Microsoft Defender Antivirus Service
Running  WinRM              Windows Remote Management (WS-Manag...

遍歷集合中的對象

Foreach-Object 遍歷對象集合中的所有對象。

$all_service = get-service | Where-Object status -eq 'running'
ForEach($service in $all_service){
          $service.name | Out-Host
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM