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


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

预定义变量

预定义的布尔值

$True
$False

预定义变量

预定义变量					描述(Description)
$^								表示当前会话的使用过的最后一条命名的最前部分
$$								表示当前会话的使用过的最后一条命名的最后部分
$?             表示最后一条命令的执行状态
返回true 表示执行成功,返回false表示执行失败
$_					等同于$PSItem
					包含管道对象中的当前对象
					可以在管道中的每个对象或选定对象执行操作的命令中使用此变量
$ARGS	Represents an array of the undeclared parameters and/or parameter values that 
	are passed to a function, script, or script block.
$CONSOLEFILENAME	Represents the path of the console file (.psc1) that was most recently used in the session.
$ERROR	Represents an array of error objects that represent the most recent errors.
$EVENT	Represents a PSEventArgs object that represents the event that is being processed.
$EVENTARGS	Represents an object that represents the first event argument that derives from EventArgs of the event that is being processed.
$EVENTSUBSCRIBER	Represents a PSEventSubscriber object that represents the event subscriber of the event that is being processed.
$EXECUTIONCONTEXT	Represents an EngineIntrinsics object that represents the execution context of the PowerShell host.
$FALSE	Represents FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false".
$FOREACH	Represents the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable.
$HOME	Represents the full path of the user's home directory.
$HOST	Represents an object that represents the current host application for PowerShell.
$INPUT	Represents an enumerator that enumerates all input that is passed to a function.
$LASTEXITCODE	Represents the exit code of the last Windows-based program that was run.
$MATCHES	The $Matches variable works with the -match and -notmatch operators.
$MYINVOCATION	$MyInvocation is populated only for scripts, function, and script blocks. PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.
$NESTEDPROMPTLEVEL	Represents the current prompt level.
$NULL	$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
$PID	Represents the process identifier (PID) of the process that is hosting the current PowerShell session.
$PROFILE	Represents the full path of the PowerShell profile for the current user and the current host application.
$PSCMDLET	Represents an object that represents the cmdlet or advanced function that is being run.
$PSCOMMANDPATH	Represents the full path and file name of the script that is being run.
$PSCULTURE	Represents the name of the culture currently in use in the operating system.
$PSDEBUGCONTEXT	While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value.
$PSHOME	Represents the full path of the installation directory for PowerShell.
$PSITEM	Same as $_. Contains the current object in the pipeline object.
$PSSCRIPTROOT	Represents the directory from which a script is being run.
$PSSENDERINFO	Represents information about the user who started the PSSession, including the user identity and the time zone of the originating computer.
$PSUICULTURE	Represents the name of the user interface (UI) culture that is currently in use in the operating system.
$PSVERSIONTABLE	Represents a read-only hash table that displays details about the version of PowerShell that is running in the current session.
$SENDER	Represents the object that generated this event.
$SHELLID	Represents the identifier of the current shell.
$STACKTRACE	Represents a stack trace for the most recent error.
$THIS	In a script block that defines a script property or script method, the $This variable refers to the object that is being extended.

环境变量管理

获得环境变量

获得全部环境变量

Get-ChildItem env:

或者

dir env:

获得单个环境变量

变量语法形式格式:

$env:环境变量名称

使用Get-Item形式:

Get-Item env:temp

获得TEMP变量

$env:TEMP

获得APPDATA变量

$env:APPDATA

获得HOME目录

$env:HOMEPATH

获得处理器个数NUMBER_OF_PROCESSORS
注意:这是处理器的线程数

$env:NUMBER_OF_PROCESSORS

获得处理器的架构

$env:PROCESSOR_ARCHITECTURE

获得OS类型

$env:OS

获得Path信息

$env:Path

获得Windows目录

$env:windir

设置环境变量

$env:ASPNETCORE_ENVIRONMENT="Production"

cmd设置环境变量

set ASPNETCORE_ENVIRONMENT=Production

输入输出

获得用户输入

Read-Host

实例:

$userInput = Read-Host "请输入你的长度"

输出内容到标准输出

image

Write-Host

实例:
输出文本

Write-Host "panda"

设置前景色和背景色

Write-Host "COLORFUL!" -Fore Yellow -Back Magenta

输出警告信息

Write-Warning

实例:
输出警告信息

Write-Warning "cmdlet is used to write warning messages" 

输出警告信息

Write-Warning "Test Warning" 

执行应用文件默认行为

perform a default action on specified item

Invoke-Item

实例:

Invoke-Item "D:/test.txt"

执行字符串表达式

Invoke-Expression

实例:

$Command = 'Get-Process'
Invoke-Expression $Command

测试命令执行的时间

Measure-Command

实例:

Measure-Command { Get-EventLog "Windows PowerShell" }

运算符(Operators)

算术运算符(Arithmetic Operators)

说明
Arithmetic operators are used to perform numeric calculations
Arithmetic operator also be used with strings, arrays, and hash tables
注意:加号+除了进行算数运算,还用于连接字符串
注意:加号+还可以用于为数组添加元素
注意:The division and remainder operators perform mathematical operations only
注意:求余运算和C#一样,结果的符号取决于第一个运算数

算数运算符

+ 		    Addition					
- 		    Subtraction				
* 		    Multiplication				
/ 		    Division					
% 		    Remainder				
-shl		Shift left					
-shr		Shift right	

Addition Operator实例:
简单算数运算

2.71828 + 3.14159          #5.85987

连接字符串

'www.' + 'Panda666.com'    #www.Panda666.com

连接字符串和数值(数值如果在前面会报错,需要进行类型转换)

'Hello Panda ' + 666       # Hello Panda 666
[string]666 + 'Panda'      #666Panda

为数组添加元素

@(666, 888) + 999 + 'Panda' + $True `

连接两个数组

@(1, 2) + @(3, 4)
(1, 2) + (3, 4)
1, 2 + 3, 4

连接HashTable(注意:如果Key是相同的,会报错)

@{Name = 'Panda'} + @{Code = 666} 

Multiplication Operator实例:
简单乘法:

2.5 * 2

字符串重复连接

'Panda666' * 3

用于重复数组的元素

@('one', 'two') * 2
('one', 'two') * 2
'one', 'two' * 2

Division operator实例:
简单除法:

20 / 5

Remainder operator实例:

3 % 2

链式使用

1..100 | Where-Object { $_ % 5 -eq 0 } | ForEach-Object {Write-Host $_}

Shift left and shift right operators实例:
简单左移

78 -shl 1

可以指定数据类型的大小

([Byte]255) -shl 1
([Int16]255) -shl 1

有符号数如果左移超过范围会导致循环

([SByte]64) -shl 1   #-128

比较运算符(Comparison Operators)

-eq and -ne                 	Equal to and not equal to
-gt and -ge                 	Greater than and greater than or equal to
-lt and -le                 	Less than and less than or equal to
-like and -notlike          	Like and not like
-contains and -notcontains  	Contains and not contains
-in and -notin              	In and not in

注意,当比较文本字符串时默认会忽略大小写,大写字母与小写字母等价
也可以显式的声明为不区分大小写,只需要在运算符前加上i即可

-ieq,-ine,-igt,-ilt,-ige,-ile

对于字符串的比较,如果需要区分大小写,在运算符前,加上c即可

-ceq,-cne,-cgt,-clt,-cge,-cle

实例:
相等比较

"Panda666" -eq "Panda666"   #True
"panda666" -eq "Panda666"   #True
"panda666" -ceq "Panda666"  #False

大小比较

(5 -gt 10) -or (10 -lt 100) #True

检测包含

1, 2 -contains 2 # Returns true
1, 2, 3 -contains 4 # Returns false

检测存在

1 -in 1, 2, 3 # Returns true
4 -in 1, 2, 3 # Returns false

比较运算符与数组混用(Comparison operators and arrays)
默认情况下比较运算符返回true或false
如果与数组混用,则返回满足条件的元素

1, $null -ne $null 		# Returns 1
1, 2, 3, 4 -ge 3 		# Returns 3, 4
'one', 'two', 'three' -like '*e*' # Returns one and three 

这也会造成一些问题,比如:检测数组是否为null

$array = 1, 2, $null, $null
if ($array -eq $null) { Write-Host 'No values in array' } 

以上的比较将会成功,但是数组又是有元素的
可以通过以下方式来解决

$array = 1, 2, $null, $null
if ($null -eq $array) { Write-Host 'Variable not set' }

逻辑运算符(Logical Operators)

-and			与运算
-or			    或运算
-not			非运算
-xor			异或

提示:-not也可以使用!,是等价的

实例:

(5 -gt 10) -or (10 -lt 100) #True
(5 -gt 10) -or $True         #True
-not $false
-not (Test-Path X:/)
-not ($true -and $false)
!($true -and $false)

赋值运算符(Assignment Operators)

赋值运算符:

=		Assign
+=		Add and assign
-=		Subtract and assign
*=		Multiply and assign
/=		Divide and assign
%=		Modulus and assign

实例:
数值运算

$num = 666;
$num +=222;

字符串连接

$string = 'panda'
$string += '666' 

混合字符串和数值类型进行运算

$var = 'Panda'
$var += 666;

如果是数值类型在前面,记得转为字符串再进行运算

[string]$var = 666  #将数值转为字符串
$var += 'Panda';

数组添加元素

$array = 666,888
$array += 888

数组合并数组

$array = 666,888
$array += 888,666

合并HashTable

$hashtable = @{Name = 'Panda'}
$hashtable += @{Code = 666} 

重复字符串

$string = 'one'
$string *= '2' 

重复数组

$arr = 1, 2
$arr *= 2

正则表达式运算符(Regular expression-based operators)

-match          	    Match
-notmatch       	    Not match
-replace        		Replace
-split          		Split

提示:还有区分大小写的-creplace命令、-csplit命令

实例:
匹配字符串

'The cow jumped over the moon' -match 'cow' # Returns true
'The cow' -match 'The +cow' # Returns true

匹配字符串中的数字

'1234567689' -match '[0-4]*'

匹配数组的元素

"one", "two", "three" -match 'e'

替换

'abababab' -replace 'a', 'c'

替换为空,等价于移除

'abababab' -replace 'a'

分割

'a1b2c3d4' -split '[0-9]'

位运算符(Bitwise operators)

-band   	Binary and
-bor    	Binary or
-bxor   	Binary exclusive or
-bnot   	Binary not

实例:
按位与

11 -band 6

按位或

11 -bor 12

按位异或

6 -bxor 13
512 -bxor 2 		# Result is 514 (Disabled, 2 is set)
514 -bxor 2 		# Result is 512 (Enabled, 2 is not set)

按位非

-bnot 122

重定向运算符(Redirection operators)

具体查看管道笔记

实例:
重定向到文件中

Get-Process -Id $pid > process.txt

警告输出流重定向到文件

function Test-Redirect{
 Write-Warning "Warning $i"
}
Test-Redirect 3> 'warnings.txt' # Overwrite
$i++
Test-Redirect 3>> 'warnings.txt' # Append

类型运算符(Type operators)

说明
Type operators are designed to work with .NET types
These operators may be used to convert an object of one type into another, or to test whether or not an object is of a given type

类型运算符(Type operators):
-as As运算符,将一种已存在的对象转换为新的对象类型,从而产生一个新的对象
-is Is运算符,判断某个对象是否为特定类型,如果是,则返回True,否则为False
-isnot Is not运算符,-is运算的反向

-as实例:
简单类型转换

"1" -as [Int32]

转为System.Reflection.MemberInfo类型

'String' -as [Type]

运算结果转为指定类型

1000 / 3 –AS [INT]
$panda = 1000 / 3 –AS [INT];

导入类型(程序集)

if (-not ('System.Web.HttpUtility' -as [Type])) {
    Write-Host 'Adding assembly' -ForegroundColor Green
    Add-Type -Assembly System.Web
}

-is、-isnot实例:
检测是否指定类型

'string' -is [String]
123.45 -IS [INT]                #False
(Get-Date) -IS [DateTime]       #True

检测是否[Int32]类型

1 -is [Int32]

检测是否类型

[String] -is [Type]

检测是否不是[string]类型

123 -isnot [String]

其他运算符(Other operators)

&				Call,用于执行命令,执行代码块
,				Comma,逗号运算符,用于分隔数组元素等
-f 				Format,用于格式化字符串,和C#基本相同
++ and --		Increment and decrement
-join 			Join

&实例:
执行cmd命令

$command = 'ipconfig'
& $command

执行Powershell命令:

$command = 'Get-Location'
& $command

执行代码块:

$scriptBlock = { Write-Host 'Panda666.com' }
& $scriptBlock

还支持指定参数

& 'ipconfig' '/displaydns'

-f实例:
简单格式化

'1: {0}, 2: {1}, 3: {2}'  -f  1, 2, 3

使用格式化字符

'1: {0:F}, 2: {1:C2}, 3: {2:F3}'  -f  1, 2, 3
'The pass mark is {0:P}' -f 0.8
'244 in Hexadecimal is {0:X2}' -f 244

-f会转换{}符号,如果需要保留{}可以使用{{}}即可

'The value in {{0}} is {0}' -f 1

++ and –实例:
常用于循环变量中

for ($i = 0; $i -le 15; $i++) {
 Write-Host $i -ForegroundColor $i
}

-join实例:
将数组转化为分隔列表的字符串

$Array = "one","two","three","four","five"
$Array -Join "|"

分割后再连接起来

"a,b,c,d" -split ',' -join "`t"

还可以使用这种格式

-join ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')

..(范围运算符)

1..10会返回1到10的十个对象

1..10
?(问号)是Where-Object Cmdlet的别名
%(百分号)是ForEach-Object Cmdlet的别名
>(右尖括号)类似Out-File Cmdlet的别名
&(与符号)是PowerShell中的一个调用运算符,使得PowerShell可以将某
些字符识别为命令,并运行这些命令。例如,$a="Dir"命令将“Dir”赋给了变
量$a,然后&$a就会执行Dir命令。
;(分号)一般用作分隔PowerShell中同一行的两个命令:Dir;Get-Process。
这个命令会先执行Dir命令,之后执行Get-Process命令。它们的执行结果会发送
给一个管道,但是Dir命令的执行结果并不会通过管道发送给Get- Process命令

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/281414.html

(0)
上一篇 2022年8月21日 18:01
下一篇 2022年8月21日 18:10

相关推荐

发表回复

登录后才能评论