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


<<:  EP16 - 用生活化的例子解释容器,是否搞错了些什麽

>>:  第一次参加社群志工

Day_18 : 让 Vite 来开启你的Vue 之 toRef & toRefs

Hi Dai Gei Ho~ 我是Winnie~ 今天文章要来说的是 toRef 与 toRefs ...

CMoney工程师战斗营weekly2

在现实世界与抽象空间游走的一周 匆匆忙忙行军式的步伐迈向抽象类别的世界,老实说真的有点挫折,跟不太上...

【C# 群益 API 开发教学】帐号登入、取得下单帐号教学 #CH2 (附范例)

群益 API 是利用自己开发的程序,结合群益 API 在群益券商下单的一种方式,通常是做程序交易下单...

Day-22 树(Tree), 二元搜寻树(Binary Search Tree)

前言 对於大量的资料处理,使用串列的走访是一种十分没有效率的方法,其效率会根据串列的长度而不断线性成...

整合架构说明

从第一天到今天, 主轴是从training、tracking到serving. 在第一个范例(fas...