適合初學者的 PowerShell

使用 PowerShell 時,我們首先遇到的是命令 (Cmdlet)。
命令調用如下所示:

Verb-Noun -Parameter1 ValueType1 -Parameter2 ValueType2[]

尋求幫助

使用 Get-Help 命令訪問 PowerShell 中的幫助。 可以指定其中一個參數:example、detailed、full、online、showWindow。

Get-Help Get-Service -full 將返回 Get-Service 命令操作的完整描述
Get-Help Get-S* 將顯示所有以 Get-S* 開頭的可用命令和函數

微軟官方網站上也有詳細的文檔。

這是 Get-Evenlog 命令的示例幫助

適合初學者的 PowerShell

如果參數括在方括號 [] 中,則它們是可選的。
即本例中需要日誌本身的名稱,參數的名稱 不。 如果參數類型和它的名字一起用括號括起來,那麼這個參數是可選的。

如果查看 EntryType 參數,您可以看到用大括號括起來的值 \uXNUMXb\uXNUMXb。 對於這個參數,我們只能使用花括號中預定義的值。

有關該參數是否必需的信息可以在下面的 Required 字段中的描述中看到。 在上面的示例中,After 屬性是可選的,因為 Required 設置為 false。 接下來,我們看到對面的 Position 字段,上面寫著 Named。 這意味著您只能通過名稱引用參數,即:

Get-EventLog -LogName Application -After 2020.04.26

由於 LogName 參數的編號為 0 而不是 Named,這意味著我們可以在沒有名稱的情況下引用該參數,但可以按所需順序指定它:

Get-EventLog Application -After 2020.04.26

讓我們假設這個順序:

Get-EventLog -Newest 5 Application

別名

為了讓我們可以在 PowerShell 中從控制台使用常用的命令,有別名(Alias)。

Set-Location 命令的一個示例別名是 cd。

也就是說,而不是調用命令

Set-Location “D:”

我們可以用

cd “D:”

發展歷程

要查看命令調用的歷史記錄,可以使用 Get-History

從歷史執行命令 Invoke-History 1; 調用歷史 2

清除歷史記錄

管道

powershell 中的管道是第一個函數的結果傳遞給第二個函數的時候。 這是使用管道的示例:

Get-Verb | Measure-Object

但為了更好地理解管道,讓我們舉一個更簡單的例子。 有一個團隊

Get-Verb "get"

如果調用 Get-Help Get-Verb -Full 幫助,那麼我們將看到 Verb 參數接受管道輸入,並且 ByValue 寫在括號中。

適合初學者的 PowerShell

這意味著我們可以將 Get-Verb "get" 重寫為 "get" | 獲取動詞。
也就是說,第一個表達式的結果是一個字符串,它通過按值輸入的管道傳遞給 Get-Verb 命令的 Verb 參數。
管道輸入也可以是 ByPropertyName。 在這種情況下,我們將傳遞一個對象,該對象具有一個名稱與 Verb 相似的屬性。

變量

變量不是強類型的,並且在前面用 $ 指定

$example = 4

符號>表示將數據放入
例如,$example > File.txt
使用此表達式,我們會將 $example 變量中的數據放入文件中
與 Set-Content -Value $example -Path File.txt 相同

數組

數組初始化:

$ArrayExample = @(“First”, “Second”)

空數組初始化:

$ArrayExample = @()

通過索引獲取價值:

$ArrayExample[0]

獲取整個數組:

$ArrayExample

添加一個元素:

$ArrayExample += “Third”

$ArrayExample += @(“Fourth”, “Fifth”)

排序方式:

$ArrayExample | Sort

$ArrayExample | Sort -Descending

但是數組本身在這種排序中保持不變。 如果我們希望數組有排序的數據,那麼我們需要分配排序後的值:

$ArrayExample = $ArrayExample | Sort

在 PowerShell 中無法從數組中刪除元素,但您可以這樣做:

$ArrayExample = $ArrayExample | where { $_ -ne “First” }

$ArrayExample = $ArrayExample | where { $_ -ne $ArrayExample[0] }

刪除數組:

$ArrayExample = $null

循環

循環語法:

for($i = 0; $i -lt 5; $i++){}

$i = 0
while($i -lt 5){}

$i = 0
do{} while($i -lt 5)

$i = 0
do{} until($i -lt 5)

ForEach($item in $items){}

退出中斷循環。

跳過繼續元素。

條件陳述

if () {} elseif () {} else

switch($someIntValue){
  1 { “Option 1” }
  2 { “Option 2” }
  default { “Not set” }
}

功能

函數定義:

function Example () {
  echo &args
}

功能推出:

Example “First argument” “Second argument”

在函數中定義參數:

function Example () {
  param($first, $second)
}

function Example ($first, $second) {}

功能推出:

Example -first “First argument” -second “Second argument”

例外

try{
} catch [System.Net.WebException],[System.IO.IOException]{
} catch {
} finally{
}

來源: www.habr.com

添加評論