Powershell 入门参数属性(2)

前面我们讲了怎么通过参数的属性限制参数的个数和长度。今天我们来看看,通过参数的属性,限制参数的格式以及参数的可选集(特定的值)。

首先我们来看看今天的示例脚本:

function test-net_port {
    [cmdletbinding()]
    param(
        [parameter(mandatory=$true,Helpmessage="Enter the name of a computer to check connectivity to.")]
        [ValidateCount(1,5)]
        [ValidateLength(1,15)]
        [ValidatePattern("SZ[A-Z]{2,3}\d{1,2}$")]  #computerName 必须要满足正则表达式
        [string[]]$computerName,
        [parameter(mandatory=$false)]
        [ValidateSet(80,443,22)]    # port 的值,只能是 80,443 和 22 其中的一个
        [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
        }
    }
}

运作结果:

PS C:\Users> test-net_port -computerName SZSVR1
False

PS C:\Users> test-net_port -computerName SZSVR001
test-net_port : Cannot validate argument on parameter 'computerName'. The argument "SZSVR001" does not match the "SZ[A-Z]{2,3}\d{1,2}$" pattern. Supply an argument that matches 
"SZ[A-Z]{2,3}\d{1,2}$" and try the command again.
At line:1 char:29
+ test-net_port -computerName SZSVR001
+                             ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port

PS C:\Users> test-net_port -computerName SZSVR01 -port 23
test-net_port : Cannot validate argument on parameter 'port'. The argument "23" does not belong to the set "80,443,22" specified by the ValidateSet attribute. Supply an argument that is in 
the set and then try the command again.
At line:1 char:43
+ test-net_port -computerName SZSVR01 -port 23
+                                           ~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port
 

PS C:\Users> test-net_port -computerName SZSVR01 -port 22

<<:  小蛙借钱给你的交易概念!!

>>:  [Day28] Tableau 轻松学 - TabPy 备份与还原

[Golang]go test指令说明-心智图总结

1. -cpu a. 用途: 模拟程序在不同CPU核心数的计算机,效能表现。 b. 用来设定测试执行...

冒险村19 - Activerecord-import

19 - Activerecord-import 在写入资料的时候,时常会有大量资料一次 impor...

【Day 17】递回 Recursion

前言 在解题时可能会遇到一些问题不是正常的回圈就可以解决的,可能需要用到前面的答案来运算,像是计算阶...

安装MLFlow

第一天的简介中, 我们提到会整合training、tracking与serving(如下图). 现在...

Day18

传值与传址,但C++是一个特别的语言比C语言更复杂真要细分可分成3类(传值,传址,传参考),同时指标...