首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

PowerShell 學習筆記:陣列操作與 Cmdlet 範例匯出技巧

     編輯:關於.NET

PowerShell 陣列基礎

建立陣列

使用逗號分隔即可建立陣列,元素型別可混合:

520, 'abc', 2MB, 0xFFFE
# 輸出:
520
abc
2097152
65534

陣列屬性與索引

$array = 1,2,3,4,5
$int = 1

$array.count   # 5
"$array"       # 顯示所有元素 (以空格分隔)
$int.count     # 1 (標量視為單元素陣列)
"$int"         # 1

$array.GetType().FullName  # System.Object[]

$array.Length  # 3
$array[0]      # 1 (第一個元素)
$array[2]      # 3 (第三個元素)
$array[4]      # $null (越界不報錯,回傳 null)

修改與新增元素

$a = "I", "am"
$a[0] = "We"          # 修改現有元素 OK
$a[2] = "Lihua"       # 錯誤:索引超出範圍,陣列大小固定

# 正確新增方式:建立新陣列
$a = $a + "Lihua"     # $a 變為 "I", "am", "Lihua"

Cmdlet 學習技巧:批次匯出範例程式碼

PowerShell 內建 Get-Help -Examples 提供豐富範例。以下腳本將所有 Cmdlet 的範例匯出至獨立 .ps1 檔案,方便離線閱讀:

匯出所有系統 Cmdlet 範例

$d = Get-Command -CommandType Cmdlet
"Total: " + $d.Count
$i = 0
$d | ForEach-Object -Process {
    $i++
    "Printing " + $i
    $cmdlet = $_.Name
    $path = ".\EXAMPLE\" + $cmdlet + ".ps1"
    Get-Help -Examples $cmdlet > $path
}
"Successfully"

執行結果示意

匯出腳本執行輸出畫面

匯出內容範例 (ForEach-Object.ps1)

NAME
    ForEach-Object
SYNOPSIS
    Performs an operation against each of a set of input objects.
-------------------------- EXAMPLE 1 --------------------------
C:\PS>30000,56798,12432 | foreach-object -process {$_/1024}
    This command accepts an array of integers, divides each one of them by 1024, and displays the results.
-------------------------- EXAMPLE 2 --------------------------
C:\PS>get-childitem C:\ | foreach-object -process { $_.length / 1024 }
    This command retrieves the files and directories in the root of the C: drive and returns and displays the size of each of them.
-------------------------- EXAMPLE 3 --------------------------
C:\PS>$events = get-eventlog -logname system -newest 1000
$events | foreach-object -begin {get-date} -process {out-file -filepath events.txt -append -inputobject $_.message} -end {get-date}
    This command retrieves the 1000 most recent events from the system log ...
-------------------------- EXAMPLE 4 --------------------------
C:\PS>get-itemproperty -path hkcu:\Network\* | foreach-object {set-itemproperty -path $_.pspath -name RemotePath -value $_.RemotePath.ToUpper();}
    This command updates a set of registry entries ... changes the characters in the UNC path to uppercase.

僅匯出自訂 Cmdlet (排除系統內建)

# 需先註冊 PSSnapin
$d = Get-Command -PSSnapin Zivsoft.PowerShell.Cmdlets
"Total: " + $d.Count
$i = 0
$d | ForEach-Object -Process {
    $i++
    "Printing " + $i
    $cmdlet = $_.Name
    $path = ".\CmdletsUsage\" + $cmdlet + ".ps1"
    Get-Help -Examples $cmdlet > $path
}
"Successfully"

小結

  • PowerShell 陣列以逗號建立、索引從 0 起、大小固定需重建才能新增元素。
  • 標量也視為單元素陣列,擁有 .Count 與 .Length 屬性。
  • 善用 Get-Help -Examples 批次匯出,能快速建立個人化 Cmdlet 範例庫,加速學習與查閱。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved