简体   繁体   中英

Powershell Validate Range Parameter Error

I have a script that automates Windows USMT backups but I am running into an issue with Powershell 2.0. Basically I have a script parameter that requires a positive integer and the validation works in Powershell 3.0+ but not in 2.0, which ships in Windows 7.

Parameter Code:

[CmdletBinding()]
Param (
    [ValidateScript({
        if( -Not ($_ | Test-Path) ){
            throw "File or folder does not exist"
        }
        if($_ | Test-Path -PathType Leaf){
            throw "The Path argument must be a folder. file paths are not allowed."
        }
        if( -not (($_ | Get-ChildItem | Measure-Object).Count -eq 0) ) {
            throw "The Folder '$_' Has Content/Files! USMT will not run against a non-empty backup folder!!"
        }
        return $true
    })]
    [System.IO.FileInfo]$BackupPath,

    [switch]$OfflineUSBDock,

    [ValidateRange(1, [int]::MaxValue)][int]$UEL
)

The Error: 在此处输入图片说明

So my question is how do I fix this to work correctly in Powershell 2.0? The goal is for the $UEL parameter to only accept a positive Integer.

Full Script

Here 2 workarounds from the comments (thanks @TheIncorrigible for the recommendations):

[ValidateScript({
    if ($_ -eq 0) {
        throw "UEL requires a positive integer greater then 0!"
    }
    return $true
})]    
[uint32]$UEL

or

 [ValidateRange(1, 2147483647)][int]$UEL

Not as clean as using [int]::MaxValue but it gets the job done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM