5.Powershell变量

在指令执行过程中,会有一些数据产生,这些数据被用于以后的语句,需要一个存储单元暂时的存放这些数据,这个时候定义一个变量来存储数据。例如$string = “Hello Powershell!”

Powershell中无需declare声明,定义变量前缀有”$”符号

常见变量类型

数值型(int)

字符型(char)

布尔型(bool)

定义变量

$a = 100 #变量$a值赋予100

Set-Variable -Name a -Value 100 为变量$a赋值100 或者

New-Varibale –Name a –Value 100 创建变量$a并赋值100 (有关New-Variable还有更多的参数,例如设置变量写保护,为变量写描述信息等等)

打印变量值

$a或者write-host $a

同时为多个变量赋相同值

$a = $b = $c = 1

交换变量内容

例如,有两个变量$a=1和$b=2,现在叫唤两个变量的值

$a = 1

$b = 2

$temp = $a #定义一个变量$temp用于数据交换

$a = $b

$b = $temp

$a

$b

另外还有一种更加简便的方式:

$a,$b = $b,$a

在一行中如何为多个变量赋予不同的值,例如:

$a,$b = 1,2

查看在使用的变量

在指令中,我们会使用到相应的变量来暂时的存放数据,用过的变量Powershell会存有历史记录,如何查看我们使用过的变量以及它们的值?

clip_image002

查找变量

在原来的指令中,如果定义过相应的变量,此时想查看变量值为多少,这时就需要把变量找出来,并显示出值来。例如:在前面定义了两个变量$value1,$value2,想查看下两个变量值,此时使用dir variable:value* ,配合使用通配符找出两个变量,并显示变量值。

clip_image004

校验变量是否存在

在使用变量时,有时会首先确认此变量是否在以前有使用过,避免变量数值被覆盖。可以使用Test-Path来进行校验,和文件的校验很类似,变量也有路径。返回值为布尔值,如果存在则返回True,如果不存在则返回False。

在下面的例子中,$value1变量存在,$value变量不存在。

clip_image005

删除变量

当退出Powershell时,定义的变量会自动删除,一般情况下没必要做删除变量的操作,如果需要立即删除变量。可以使用delete variable: est命令删除,其中test为变量名。

环境变量

Powershell依赖于Windows自身的环境变量,对于Powershell来说环境变量是非常重要的信息来源,因为它包括许多操作系统细节,而且环境变量是永久保留的,因此不担心Powershell在关闭时,变量丢失问题,从而可以被其他应用程序读取。

clip_image007

如何定义新的环境变量

$env:test = 12 #定义了一个名为test的环境变量,并赋值12

如果想删除定义的这个环境变量使用del env: est即可

变量作用域

$global The variable is valid in all scopes and is preserved when a script or a

function ends its work.

$script The variable is valid only within a script, but everywhere within it.

Once the script is executed, the variable is removed.

$private The variable is valid only in the current scope, either a script or a

function. It cannot be passed to other scopes.

$local The variable is valid only in the current scope. All scopes called with

it can read, but not change, the contents of the variable.

Modifications are also stored in new local variables of the current

scope.

$local: is the default if you don't specify a particular scope

例:

$global:a = 1000 #定义全局变量$a,并赋值1000

变量类型转换

在一些情况下,需要转换变量的类型,例如datetime转字符串,字符串转datetime等情况,首先还是看一下如何查看变量的类型:

在这个例子中,我们可以看到使用gettype()方法可以查看$a变量为字符串类型。

clip_image008

将$a强制转换成datetime类型

clip_image009

校验变量值是否满足条件

在定义的变量中,有些变量必须要满足一定的条件,例如不能为空值,不能少于3个字符等等,在Powershell中如果对定义的变量进行值的校验呢?下面让我们看一个例子:

clip_image011

$a = "hello" #定义变量$a

$aa = Get-Variable a #在当前console获取变量$a的属性

$aa.Attributes.Add($(New-Object system.Management.Automation.ValidateLengthAttribute -ArgumentList 2,8)) #为变量$a添加校验属性,字符长度不能小于2大于8

$a = "testtesttest" #测试

除了以上长度校验外,还有其他校验方法:

邮件校验方式:

$email = "tobias.weltner@powershell.com"

$v = Get-Variable email

$pattern = "[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}"

$v.Attributes.Add($(New-Object `

System.Management.Automation.ValidatePatternAttribute `

-argumentList $pattern))

clip_image012

特殊变量(检测最后执行的命令是否成功)

$LastExitCode 返回数字(退出码或错误级别)

$? 返回布尔值

原文地址:https://www.cnblogs.com/motools/p/3300036.html