簡體   English   中英

驗證參數 powershell 中沒有使用空格

[英]Validate that no spaces have been used in parameter powershell

所以我正在努力尋找解決方案。 我正在研究一些不同的功能,並正在實施一些驗證步驟。

我正在尋找的是一個解決方案,以便我可以驗證我的兩個參數中沒有使用空格,因為底層屬性不接受它。

我知道我可以檢查並刪除空格,但希望它能刪除錯誤並通知用戶不允許使用空格並更改值。 我試圖這樣做的價值觀是:

$GroupMailSuffix $ValidatedDomainName

function Add-DistributionGroup {  
 param (

        [Parameter(Mandatory=$true)]
        [ValidateLength(5,256)]
        $DistributionGroupName,

        [Parameter(Mandatory=$true)]
        $GroupMailSuffix,

        [Parameter(Mandatory=$true)]
        $ValidatedDomainName

    )
    New-DistributionGroup -Name $DistributionGroupName -PrimarySmtpAddress "$GroupMailSuffix@$($ValidatedDomainName)"
}

使用[ValidateScript()]參數屬性來驗證參數作為參數綁定的一部分。 如果提供的腳本塊返回$false ,則調用失敗並出現語句終止錯誤。

# IMPORTANT: ErrorMessage only supported in PowerShell (Core) 7+
[ValidateScript({ $_ -notmatch ' ' }, ErrorMessage = 'Value must not contain spaces.')]

需要注意的是,在Windows PowerShell中,您無法提供用戶友好的錯誤消息- 用戶將看到用於驗證的腳本塊( {... } ) 的源代碼。

但是,有一個解決方法(適用於 PowerShell 兩個版本):如果驗證失敗,請在腳本塊內使用throw和所需的錯誤消息:

[ValidateScript({ if ($_ -notmatch ' ') { return $true }; throw 'Value must not contain spaces.' })]

把它們放在一起:

# NOTE: PowerShell (Core) 7+, due to use of the ErrorMessage property
#       See Windows PowerShell alternative above.
function Add-DistributionGroup {  
  param (
         [Parameter(Mandatory)]
         [ValidateLength(5,256)]
         [string] $DistributionGroupName,
 
         [Parameter(Mandatory)]
         [ValidateScript({ $_ -notmatch ' ' }, ErrorMessage = 'Value must not contain spaces.')]
         [string] $GroupMailSuffix,
         
         [Parameter(Mandatory)]
         [ValidateScript({ $_ -notmatch ' ' }, ErrorMessage = 'Value must not contain spaces.')]
         [string] $ValidatedDomainName
 
     )
  New-DistributionGroup -Name $DistributionGroupName -PrimarySmtpAddress "$GroupMailSuffix@$($ValidatedDomainName)"
 }

請注意,為概念清晰起見,參數類型為[string] ,並且在$DistributionGroupName的情況下,還允許使用[ValidateLength()]屬性。

如果用戶傳遞帶空格的值,他們將看到如下錯誤:

Add-DistributionGroup: Cannot validate argument on parameter 'ValidatedDomainName'. 
Value must not contain spaces

請注意,因為錯誤是語句終止錯誤,所以[1]默認情況下繼續執行下一條語句。

中止腳本,要么(可能是暫時的)先設置$ErrorActionPreference = 'Stop' ,要么使用try / catch語句或trap語句退出。


[1] 這甚至適用於使用throw的解決方法,即使throw通常會產生腳本終止(致命)錯誤。 但是,在這種情況下,捕獲底層 .NET 異常的是 PowerShell 本身(參數綁定器),這有效地將其轉換為語句終止錯誤。
有關 PowerShell 令人眼花繚亂的復雜錯誤處理的全面概述,請參閱GitHub 文檔問題 #1583

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM