适用于初学者的Powerhell

使用PowerShell时,我们遇到的第一件事是命令(Cmdlet)。
命令调用如下所示:


Verb-Noun -Parameter1 ValueType1 -Parameter2 ValueType2[]

帮帮我


使用Get-Help命令在PowerShell中调用帮助。您可以指定以下参数之一:示例,详细,完整,在线,showWindow。

Get-Help Get-Service -full将返回Get-Service命令的完整说明。Get
-Help Get-S *将显示以Get-S开头的所有可用命令和功能*


Microsoft官方网站上也有详细的文档。


这是Get-Evenlog命令的帮助示例


图片

[], .
, . , .


EntryType, . .


Required. After , Required false. Position Named. , :


Get-EventLog -LogName Application -After 2020.04.26

LogName Named 0 , :


Get-EventLog Application -After 2020.04.26

:


Get-EventLog -Newest 5 Application

Alias


PowerShell (Alias).


Set-Location cd.



Set-Location “D:\”


cd “D:\”

History


Get-History


Invoke-History 1; Invoke-History 2


Clear-History


Pipeline


powershell . :


Get-Verb | Measure-Object

.


Get-Verb "get"

Get-Help Get-Verb -Full, Verb pipline input ByValue.


图片

Get-Verb «get» «get» | Get-Verb.
Verb Get-Verb pipline input .
pipline input ByPropertyName. Verb.


Variables


$


$example = 4

>
, $example > File.txt
$example
Set-Content -Value $example -Path File.txt


Arrays


数组初始化:


$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{
}

All Articles