iT邦幫忙

2021 iThome 鐵人賽

DAY 15
0
自我挑戰組

Powershell 入门系列 第 15

Powershell 入门参数属性(1)

对于 Powershell 脚本的参数,我们可以通过一些属性来限制参数。

今天我们就来看看,怎么通过参数属性来限制某个参数的个数,限制某个参数的长度。

下面来看看今天的示例脚本:

function test-net_port {
    [cmdletbinding()]
    param(
        [parameter(mandatory=$true,Helpmessage="Enter the name of a computer to check connectivity to.")]
        [ValidateCount(1,5)]   # 限制参数的个数,在 1 到 5 个之间(包括 5 个)
        [ValidateLength(1,15)]   # 单个参数的长度在 1 到 15 之间
        [string[]]$computerName,
        [parameter(mandatory=$false)]
        [int] $port
    )
    foreach ($computer in $computerName) {
        Write-Verbose "Now testing $computer."
        if ($port -eq "")
        {
            $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue
        } else {
            $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue -Port $port
        }
        if ($ping){
            Write-Output $ping
        } else {
            Write-Verbose "Ping failed on $computer. Check the network connection."
            Write-Output $ping
        }
    }
}

在 ISE 下面运行:

PS C:\Users\> test-net_port -computerName www.bing.com
True

 # 当单个参数的长度超过 15 时
PS C:\Users\> test-net_port -computerName www.opscoffee.com  
test-net_port : Cannot validate argument on parameter 'computerName'. The character length of the 17 argument is too long. Shorten the character length of the argument so it is fewer than 
or equal to "15" characters, and then try the command again.
At line:1 char:29
+ test-net_port -computerName www.opscoffee.com
+                             ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port

# 当参数个数超过 5 个时
PS C:\Users\> test-net_port www.bing.com,www.baidu.com,www.google.com,www.yahoo.com,www.bing.com,www.baidu.com
test-net_port : Cannot validate argument on parameter 'computerName'. The number of provided arguments, (6), exceeds the maximum number of allowed arguments (5). Provide fewer than 5 
arguments, and then try the command again.
At line:1 char:15
+ ... st-net_port www.bing.com,www.baidu.com,www.google.com,www.yahoo.com,w ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port


上一篇
Powershell 入门添加参数帮助信息
下一篇
Powershell 入门参数属性(2)
系列文
Powershell 入门21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言