系统相关
首页 > 系统相关> > PowerShell教程 - 编程结构(Program Struct)- 第四部分

PowerShell教程 - 编程结构(Program Struct)- 第四部分

作者:互联网

更新记录
转载请注明出处。
2022年8月21日 发布。
2022年8月18日 从笔记迁移到博客。

分支结构(Branching)

if语句(if Statement)

if(条件)
{
	#code
}

实例:

$userInput = Read-Host "Input Number";
if([int]$userInput -eq 666)
{
    "Panda666.com" | Out-Default;
}

if-else语句(if-else Statement)

if(条件)
{
	#code
}
else
{
	#code
}

实例:

$userInput = Read-Host "请输入你的长度";
if([int] $userInput -ge 18)
{
    "很长" | Out-Host;
}
else
{
    "一般般" | Out-Host;
}

if-elseif-else语句(if-elseif-else Statement)

if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
}elseif(Boolean_expression 2) {
   // Executes when the Boolean expression 2 is true
}elseif(Boolean_expression 3) {
   // Executes when the Boolean expression 3 is true
}else {
   // Executes when the none of the above condition is true.
}

实例:

$x = 30
if($x -eq 10){
   write-host("Value of X is 10")
} elseif($x -eq 20){
   write-host("Value of X is 20")
} elseif($x -eq 30){
   write-host("Value of X is 30")
} else {
   write-host("This is else statement")
} 

switch语句(Switch Statement)

形式1:

switch [-regex|-wildcard][-casesensitive] (<value>) {
 <condition> { <statements> }
 <condition> { <statements> }
}

形式2:处理文件

switch [-regex|-wildcard][-casesensitive] -File <Name> {
 <condition> { <statements> }
 <condition> { <statements> }
}

匹配数值

switch(3){
   1 {"One"}
   2 {"Two"}
   3 {"Three"}
   4 {"Four"}
   3 {"Three Again"}
}

测试数值

switch(3){
   1 {"One"}
   2 {"Two"}
   3 {"Three"; break }
   4 {"Four"}
   3 {"Three Again"}
}

测试多个数值

switch(4,2){
   1 {"One"}
   2 {"Two"}
   3 {"Three"; break }
   4 {"Four"}
   3 {"Three Again"}
}

测试变量

$value = 2
switch ($value) {
   1 { Write-Host 'value is 1' }
   default { Write-Host 'No conditions matched' }
}

测试多个值

switch (1, 2) {
 1 { Write-Host 'Equals 1' }
 2 { Write-Host 'Equals 2' }
}

测试正则表达式

switch -Wildcard ('cat') {
 'c*' { Write-Host 'The word begins with c' }
 '???' { Write-Host 'The word is 3 characters long' }
 '*t' { Write-Host 'The word ends with t' }
}
switch -Regex ('cat') {
 '^c' { Write-Host 'The word begins with c' } '[a-z]{3}' { Write-Host 'The
word is 3 characters long' } 't$' { Write-Host 'The word ends with t' } }

测试表达式

switch (Get-Date) {
 { $_ -is [DateTime] } { Write-Host 'This is a DateTime type' }
 { $_.Year -ge 2017 } { Write-Host 'It is 2017 or later' }
}

循环结构(Looping)

for语句(for Statement)

和C#中的for语句没有两样,但注意数据类型

for (<intial>; <exit condition>; <repeat>){
 <body-statements>
}

实例:
遍历输出数值

$userInput = Read-Host "Input Number";
for([int]$i = 0; $i -lt [int]$userInput; $i++)
{
    "Number = $i" | Out-Default;
}

遍历输出数组

$array = @("item1", "item2", "item3")
for($i = 0; $i -lt $array.length; $i++)
{ 
$array[$i];
}

while语句(while Statement)

和C#中的for语句没有两样,但注意数据类型

while (<condition>) {
 <body-statements>
}

实例:
打印小于用户输入数值的数值

$userInput = Read-Host "Input Number";
[int]$i = 0;
while($i -lt [int]$userInput)
{
    "Number = $i" | Out-Default;
    $i++;
}

将数值的元素值自增1

$array = @("item1", "item2", "item3")
$counter = 0;
while($counter -lt $array.length){
   $array[$counter]
   $counter += 1
}

等待文件存在检测

while (-not (Test-Path $env:TEMP\test.txt -PathType Leaf)) {
 Start-Sleep -Seconds 10
}

do-while语句(do-while Statement)

和C#中的for语句没有两样,但注意数据类型

do {
 <body-statements>
} <until | while> (<condition>)

注意:分为until和while
Loops based on do until will exit when the condition evaluates to true
Loops based on do while will exit when the condition evaluates to false

实例:
遍历输出小于指定值的数值

[int]$i = 10
do
{
  "Number = $i" | Out-Default;
  $i--;
}while($i -gt 0)

遍历输出数组元素

$array = @("item1", "item2", "item3")
$counter = 0;
do {
   $array[$counter]
   $counter += 1
} while($counter -lt $array.length) 

foreach语句(foreach Statement)

foreach (<element> in <collection>) {
 <body-statements>
}

实例:
遍历数组

$array = @("item1", "item2", "item3")
foreach ($element in $array) { $element }
$array | foreach { $_ }

遍历命令结果

foreach ($process in Get-Process) {
 Write-Host $process.Name
}

跳出结构(Jump Struct)

break语句

和C#中的break语句没有两样

实例:

[int]$i = 10
do
{
  "Number = $i" | Out-Default;
  $i--;
  if($i -eq 5)
  {
    break;
  }
}while($i -gt 0)

continue语句

和C#中的break语句没有两样

实例:

[int]$i = 10
do
{
  $i--;
  if($i -eq 5)
  {
    continue;
  }
  "Number = $i" | Out-Default;
}while($i -gt 0)

分支和赋值(Branching and assignment)

分支和循环语句可以直接返回值

实例:

获得计算后的值

$value = 20
$units = 'TB'
$bytes = switch ($Units) {
 'TB' { $value * 1TB }
 'GB' { $value * 1GB }
 'MB' { $value * 1MB }
 default { $value }
}

获得正在运行的服务

$serviceProcesses = foreach ($service in Get-CimInstance Win32_Service -
Filter 'State="Running"') {
 Get-Process -Id $service.ProcessId
}

异常处理

try-finally

try
{
    
}
finally
{
    
}

try-catch-finally

try
{
    1/0
}
catch [DivideByZeroException]
{
    Write-Host "除数为零异常"
}
catch [System.Net.WebException],[System.Exception]
{
    Write-Host "其他异常"
}
finally
{
    Write-Host "正在清理..."
}

脚本块(Script Block)

定义脚本块

{
 #code
}

使用脚本块

&脚本块

实例:
定义和执行脚本块

$panda = { Get-ChildItem }
&$panda

直接执行脚本块

&{ Get-ChildItem }

函数(Functions)

说明

Functions can be described as building blocks in PowerShell
Functions are often grouped together in modules
The functions within a module often share a common purpose or act on a single system

定义函数

格式

简单格式

function Get-Panda
{
}

带参数格式

function Get-Panda
{
     param ( 
        $Parameter1, 
        $Parameter2 
     )
}

参数带类型格式

function Get-Panda
{
     param ( 
        [Version]$Parameter1, 
        [int]$Parameter2 
     )
}

参数设置默认值

function Get-Panda
{
     param ( 
        [Version]$Parameter1, 
        [int]$Parameter2 = 666 
     )
}

实例

定义简单函数

function Get-PandaWebSiteUrl{
    return 'www.Panda666.com'
}

定义带一个参数的函数

function Set-Version {
 		param(
 			[Version]$version
 		)
 		$Script:Version = $version
}
Set-Version 0.2

函数指定参数类型

function Test-DateTime {
 param(
 [DateTime]$Date
 )
 $Date
}
Test-DateTime -Date "11/10/2000"

可以Nullable的参数

function Test-Nullable {
 param (
 [Nullable[DateTime]]$Date
 )
}

函数内定义函数

注意:这是非常不推荐的实践

function Outer {
    param (
        $Parameter1
    )
    function Inner1 {
    }
    function Inner2 {
    }
    Write-Host 'Hello world'
}

函数注释

说明

函数有一套特别的注释描述格式
叫做Microsoft Assistance Markup Language,是一种XML格式的描述语
支持的描述段包括:
.SYNOPSIS
.DESCRIPTION
.PARAMETER
.EXAMPLE
.INPUTS
.OUTPUTS
.NOTES
.LINK

注意:.SYNOPSIS 和 .DESCRIPTION是强制的,其他是可选的

实例

简单的函数注释

function Get-Something {
 <#
 .SYNOPSIS
  Briefly describes the main action performed by Get-Something
 .DESCRIPTION
  A detailed description of the activities of Get-Something.
 #>
}

带参数描述的函数注释

function Get-Something {
 <#
 .SYNOPSIS
 Briefly describes the main action performed by Get-Something
 .DESCRIPTION
 A detailed description of the activities of Get-Something.
 .PARAMETER Parameter1
 Describes the purpose of Parameter1.
 .PARAMETER Parameter2
 Describes the purpose of Parameter2.
  #>
 param (
 $Parameter1,
 $Parameter2
 )
}

也可以将参数的描述放在参数前面

function Get-Something {
     <#
     .SYNOPSIS
     Briefly describes the main action performed by Get-Something
     .DESCRIPTION
     A detailed description of the activities of Get-Something.
     #>
     param (
     # Describes the purpose of Parameter1.
     $Parameter1,
     # Describes the purpose of Parameter2.
     $Parameter2
     )
} 

使用帮助命令查看函数的参数信息

因为我们已经给函数进行了注释,所以可以使用帮助命令查看函数的帮助信息

Get-Help Get-Something -Parameter Parameter1

函数之内的代码块

函数最开始执行的代码块

使用begin块即可

function Show-Pipeline {
 begin {
 Write-Host 'Pipeline start'
 }
}

函数执行的代码块

使用process块即可

function Show-Pipeline {
 begin {
 $position = $myinvocation.PipelinePosition
 Write-Host "Pipeline position ${position}: Start"
 }
 process {
 Write-Host "Pipeline position ${position}: $_"
 $_
 }
}

函数最后执行的代码块

使用End块即可

function Show-Pipeline {
 begin {
 $position = $myinvocation.PipelinePosition
 Write-Host "Pipeline position ${position}: Start"
 }
 process {
 Write-Host "Pipeline position ${position}: $_"
 $_
 }
 end {
 Write-Host "Pipeline position ${position}: End"
 }
}

变量共享

各个代码块之间的变量是互同的,即都在函数作用域之下

function Measure-Item {
 begin {
 $count = 0
 $count | Write-Host
 }
 process {
 $count++
 $count | Write-Host
 }
 end {
 $count
 $count | Write-Host
 }
}

标签:function,语句,Struct,Get,while,Write,Host,Program,PowerShell
来源: https://www.cnblogs.com/cqpanda/p/16589959.html