iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

Powershell 入门系列 第 13

Powershell 入门之 可选参数和必选参数

前面我们给我们的脚本添加了参数,今天我们来看看,怎么定义这些参数,使其称为必选参数或可选参数。

我们知道,test-netconnection 命令,不仅可以通过 ping 的方式测试网络,它还可以用于测试端口。下面我们将脚本做一些更改,添加一个端口,作为可选参数,将计算机名作为必选参数:

function test-net_port {
    [cmdletbinding()]
    param(      # computerName 为必选参数,而 port 为可选参数
        [parameter(mandatory=$true)]
        [string[]]$computerName,
        [parameter(mandatory=$false)]
        [int] $port
    )
    foreach ($computer in $computerName) {
        Write-Verbose "Now testing $computer."
        if ($port -eq "")     # 由于 port 是可选参数,在这里我们要加一个逻辑判断,决定使用哪个命令
        {
            $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\v-peizhiyu> test-net_port -computerName www.bing.com
True

PS C:\Users\v-peizhiyu> test-net_port -computerName www.bing.com -port 443
True

PS C:\Users\v-peizhiyu> test-net_port -computerName www.bing.com -port 34
False

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

尚未有邦友留言

立即登入留言