Powershell 入门之函数

前面,我们已经知道了,如何去编写 powershell 脚本,今天我们就一起来看看,其他的功能。通过这些功能来丰富我们的脚本。

首先我们来看一下 Function。和其他编程语言一样,Powershell 也提供了 function 功能,通过该功能,我们可以在不同的场景中,重复使用我们的脚本。

下面我们来看一个具体的示例:

# 编写一个名为 test-net 的函数
function test-net {
    foreach ($computer in $args) {
        $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet

        if ($ping){
            Write-Output $ping
        } else {
            Write-Output $ping
        }
    }
}
调用 test-net 函数,并传递参数
test-net www.bing.com

我们还可以像运行 powershell 命令一样,运行我们的函数,并且给它传递参数,实现 -verbose 功能。

下面我们来看一下具体的示例:

function test-net {
    [cmdletbinding()]   # 通过 cmdletbinding() 实现函数的高级功能
    param(              # 指定具体的参数
        [string[]]$computerName   # 参数的名称,以及数据类型,[] 该数据是一个数组(有多个参数)
    )
    foreach ($computer in $computerName) {
        Write-Verbose "Now testing $computer."  # 加 -verbose 才会被输出
        $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue

        if ($ping){
            Write-Output $ping
        } else {
            Write-Verbose "Ping failed on $computer. Check the network connection."
            Write-Output $ping
        }
    }
}

在 Powershell ISE 下面的命令行窗口中输入:

PS C:\Users\v-peizhiyu> test-net -computerName www.bing.com -Verbose
VERBOSE: Now testing www.bing.com.
True

<<:  Kotlin Android 第20天,从 0 到 ML - RecyclerView - GradView

>>:  C# 入门之格式化输出字符串

[NestJS 带你飞!] DAY21 - HTTP Module

很多时候我们会需要去串接第三方的 API,例如:绿界科技的金流服务、Binance 的 API 等,...

[Day 19] Facial Recognition: 使用孪生网路做辨识

只要你资料集越完整,辨识模型就越强大 这个系列偏重於方法的介绍与使用,因此今天我们不会重头开始训练...

课堂笔记 - 物联网概论 课後测验

课後测验 单选题 感知层(单选题) 1.下列哪一项不属於物联网的应用? A.洗衣机於电费最低时段自...

Day10 Let's ODOO: View(3) Search View

Search View在Odoo内非常常见,可以帮助使用者快速搜寻、过滤、分类需要的资料,因此透过设...

[DAY8] 与 ActiveRecord 分手

先来看看目前我们专案的资料夹结构: 前面有提到,ActiveRecord 所建立的 model 与 ...