Windows Powershell 變數的幕後管理_PowerShell

來源:互聯網
上載者:User

在Powershell中建立一個變數,會在後台產生一個PSVariable對象,這個對象不僅包含變數的值,也包含變數的其它資訊,例如”唯寫保護”這樣的描述。
如果在Powershell中輸出一個變數,只會輸出這個變數的值。不能夠顯示它的其它資訊,如果想查看一個變數的其它保留資訊,就需要變數的基類PSVariable對象,這個可以通過Get-Variable命令得到,下面的例子示範如何查看一個變數的全部資訊。

PS> $a=get-datePS> Get-Variable aName              Value----              -----a               2011/12/8 17:52:02PS> Get-Variable a | fl *Name    : aDescription :Value    : 2011/12/8 17:52:02Visibility : PublicModule   :ModuleName :Options   : NoneAttributes : {}

修改變數的選項設定
Powershell處理一個變數的PSVariable對象,主要是為了能夠更新變數的選項設定。既可以使用命令Set-Variable,也可以在擷取PSvariable對象後直接更改。比如更改一個變數的描述:

PS> $str="我是一個變數"PS> $var=Get-Variable strPS> $varName              Value----              -----str              我是一個變數PS> $var | fl *Name    : strDescription :Value    : 我是一個變數Visibility : PublicModule   :ModuleName :Options   : NoneAttributes : {}PS> $var.Description="我知道你是一個變數"PS> $var | fl *Name    : strDescription : 我知道你是一個變數Value    : 我是一個變數Visibility : PublicModule   :ModuleName :Options   : NoneAttributes : {}如果你不想多加一個臨時變數$var來儲存PSVariable,可以使用Powershell子運算式PS> (Get-Variable str).Description="變數的描述已更改;"PS> Get-Variable str | Format-Table Name,DescriptionName                            Description----                            -----------str                             變數的描述已更改;

啟用變數的防寫保護
可以操作一個變數的選項設定 ,比如給一個變數加上防寫保護,需要將Option設定為“ReadOnly”

PS> $var="mossfly"PS> Set-Variable var -Option "ReadOnly"PS> (Get-Variable var).OptionsReadOnlyPS> Set-Variable var -Option "None" -ForcePS> (Get-Variable var).OptionsNone

變數的選項
變數的選項是一個枚舉值,包含:
“None”:預設設定
“ReadOnly”:變數唯讀,但是可以通過-Force 選項更新。
“Constant”:常量一旦聲明,在當前控制台不能更新。
“Private”:只在當前範圍可見,不能貫穿到其它範圍
“AllScope”:全域,可以貫穿於任何範圍

變數的類型規範
每個變數的都有自己的類型,這個具體的類型存放在PsVariable對象的Attributes[System.Management.Automation.PSVariableAttributeCollection]屬性,如果這個Attributes為空白,可以給這個變數存放任何 類型的資料,Powershell會自己選擇合適的類型。一旦這個Attributes屬性確定下來,就不能隨意存放資料了。例如給$var存放一個整數,屬於弱類型,所以Attributes屬性為空白,這時還可以給它賦值一個字串。但是如果給$var增加強型別,存放一個整數,再給它賦值一個其它類型,解譯器會自動嘗試轉換,如果不能轉換就會拋出異常。這時如果你非得更新$var變數的類型,可以使用 (Get-Variable var).Attributes.Clear(),清空Attributes,這樣強型別就又轉換成弱類型了。

PS> $var=123PS> (Get-Variable var).AttributesPS> $var.GetType().FullNameSystem.Int32PS> $var="字串"PS> (Get-Variable var).AttributesPS> $var.GetType().FullNameSystem.StringPS> [int]$var=123PS> (Get-Variable var).AttributesTypeId------System.Management.Automation.ArgumentTypeConverterAttributePS> $var.GetType().FullNameSystem.Int32PS> $var="2012"PS> $var2012PS> $var.GetType().FullNameSystem.Int32PS> $var="2012世界末日"Cannot convert value "2012世界末日" to type "System.Int32". Error: "Input string was not in a correct format."At line:1 char:5+ $var <<<< ="2012世界末日"   + CategoryInfo     : MetadataError: (:) [], ArgumentTransformationMetadataException   + FullyQualifiedErrorId : RuntimeException PS> (Get-Variable var).Attributes.Clear()PS> (Get-Variable var).AttributesPS> $var="2012世界末日"PS> $var.GetType().FullNameSystem.String

驗證和檢查變數的內容
變數PSVariable對象的Attributes屬效能夠儲存一些附件條件,例如限制變數的長度,這樣在變數重新賦值時就會進行驗證,下面示範如何限制一個字串變數的長度為位於2-5之間。

PS> $var="限制變數"PS> $condition= New-Object System.Management.Automation.ValidateLengthAttribute -ArgumentList 2,5PS> (Get-Variable var).Attributes.Add($condition)PS> $var="限制"PS> $var="射鵰英雄傳"PS> $var="看射鵰英雄傳"The variable cannot be validated because the value 看射鵰英雄傳 is not a valid value for the var variable.At line:1 char:5+ $var <<<< ="看射鵰英雄傳"  + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException  + FullyQualifiedErrorId : ValidateSetFailure

常用的變數內容驗證還有5種,分別為:
ValidateNotNullAttribute:限制變數不可為空
ValidateNotNullOrEmptyAttribute:限制變數不等為空白,不可為空字串,不可為空集合
ValidatePatternAttribute:限制變數要滿足制定的Regex
ValidateRangeAttribute:限制變數的取值範圍
ValidateSetAttribute:限制變數的取值集合

ValidateNotNullAttribute 例子

PS> $a=123PS> $con=New-Object System.Management.Automation.ValidateNotNullAttributePS> (Get-Variable a).Attributes.Add($con)PS> $a=8964PS> $a=$null


無法驗證此變數,因為值  不是變數 a 的有效值。
所在位置 行:1 字元: 3

+ $a <<<< =$null  + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException  + FullyQualifiedErrorId : ValidateSetFailureValidateNotNullOrEmptyAttribute 

例子,注意@()為一個空數組。

PS> $con=New-Object System.Management.Automation.ValidateNotNullOrEmptyAttributePS> (Get-Variable a).Attributes.clear()PS> (Get-Variable a).Attributes.add($con)PS> $a=$nullThe variable cannot be validated because the value is not a valid value for the a variable.At line:1 char:3+ $a <<<< =$null   + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException   + FullyQualifiedErrorId : ValidateSetFailure PS> $a=""The variable cannot be validated because the value is not a valid value for the a variable.At line:1 char:3+ $a <<<< =""   + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException   + FullyQualifiedErrorId : ValidateSetFailure PS> $a=@()The variable cannot be validated because the value System.Object[] is not a valid value for the a variable.At line:1 char:3+ $a <<<< =@()  + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException  + FullyQualifiedErrorId : ValidateSetFailureValidatePatternAttribute 例子,驗證Email格式PS> $email="test@mossfly.com"PS> $con=New-Object System.Management.Automation.ValidatePatternAttribute "b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b"PS> (Get-Variable email).Attributes.Add($con)PS> $email="abc@abc.com"PS> $email="abc@mossfly.com"PS> $email="author@gmail.com"PS> $email="www@mossfly"The variable cannot be validated because the value www@mossfly is not a valid value for the email variable.At line:1 char:7+ $email <<<< ="www@mossfly"  + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException  + FullyQualifiedErrorId : ValidateSetFailureValidateRangeAttribute 例子,驗證月份1-12PS> $month=1PS> (Get-Variable month).Attributes.Add( $( New-Object System.Management.Automation.ValidateRangeAttribute -ArgumentList 1,12) )PS> $month=10PS> $month=12PS> $month=18The variable cannot be validated because the value 18 is not a valid value for the month variable.At line:1 char:7+ $month <<<< =18   + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException   + FullyQualifiedErrorId : ValidateSetFailure ValidateSetAttribute 例子,驗證性別 PS> $sex="男"PS> $con=New-Object System.Management.Automation.ValidateSetAttribute -ArgumentList "男","女","保密"PS> (Get-Variable sex).Attributes.Add($con)PS> $sex="女"PS> $sex="不男不女"The variable cannot be validated because the value 不男不女 is not a valid value for the sex variable.At line:1 char:5+ $sex <<<< ="不男不女"  + CategoryInfo     : MetadataError: (:) [], ValidationMetadataException  + FullyQualifiedErrorId : ValidateSetFailure

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.