Powershell 入门之初识脚本

Powershell 的基础内容已经讲解的差不多了,从今天开始,我们将学习通过脚本来自动化执行批量操作。学习通过编写脚本,实现自动化。

写脚本也好,程序开发也好,都需要一个 IDE(集成开发环境)。对于 Powershell,你可以使用文本编辑器来写脚本,但系统自带的 Windows Powershell ISE,可以让我们更加方便地写脚本。

Powershell 脚本和 Shell 脚本一样,其实本质上就是堆命令,然后加一些软件判断,以实现批量操作和自动化。

下面我们来看一下,我们的第一个脚本:测试网络的连接
说明:在 Powershell 中,我们可以通过 Test-NetConnection 这个命令来测试网络连接(ping),更多详细的用户,可以查看官方文档。
在 Powershell ISE 中,输入下面内容。

$ping = Test-NetConnection -ComputerName www.baidu.com -InformationLevel Quiet
if($ping)
{
    Write-Host "The network connect is OK."
}else{
    Write-Host "The network connect is failed."
}

运行结果:

The network connect is OK.

这个脚本很简单,就是通过 Test-NetConnection 测试网络的连接,如果网络可以 ping 通,则 $ping 的值为 TRUE,如果不能 ping 通,则 $ping 的值为 FALSE。然后通过 if 进行逻辑判断,根据判断结果输出对应的内容。

如果我们的地址(或者主机名) 有多个,我们还可以使用前面 foreach 遍历,或者所有地址,然后挨个进行测试,以实现一次性测试多个地址:

$addresses = "www.baidu.com","www.google.com","ithelp.ithome.com.tw","www.opscoffee.com"

foreach ( $i in $addresses)
{
    $ping = Test-NetConnection -ComputerName $i -InformationLevel Quiet -WarningAction SilentlyContinue
    if($ping)
    {
        Write-Host "The network connect of $i  is OK."
    }else{
        Write-Host "The network connect of $i is failed."
    }
}

运行结果:

The network connect of www.baidu.com  is OK.
The network connect of www.google.com  is OK.
The network connect of ithelp.ithome.com.tw is failed.
The network connect of www.opscoffee.com  is OK.

对于几个地址,我们可以用数组的方式来实现,但如果是几十个,甚至几百个地址,通过数组明显不是很方便,我们可以把这些地址放到一个 txt 文件中,然后进行遍历:
新建一个 txt 文件,并将要测试网络连接的地址放到这个文件里:
https://ithelp.ithome.com.tw/upload/images/20210924/20099494KCkVxsIagH.png

$PATH = "D:\Powershell script\addresses.txt"

$addresses = Get-Content -path $PATH

foreach ( $i in $addresses)
{
    $ping = Test-NetConnection -ComputerName $i -InformationLevel Quiet -WarningAction SilentlyContinue
    if($ping)
    {
        Write-Host "The network connect of $i  is OK."
    }else{
        Write-Host "The network connect of $i is failed."
    }
}

运行结果:

The network connect of www.baidu.com  is OK.
The network connect of www.google.com  is OK.
The network connect of ithelp.ithome.com.tw is failed.
The network connect of www.opscoffee.com  is OK.

<<:  [Day 12] 决策树 (Decision tree)

>>:  [Android Studio 30天自我挑战] ImageView元件介绍

Day03:Set User Name(存放使用者名称)

全文同步於个人 Docusaurus Blog 在这一章中,主要处理下述两个问题: 初始进入页面的建...

事件—天外飞来一个e

刚开始学JavaScript的时候,在书上看到事件绑定的范例: //HTML <a id=&...

第35天~

这个得上一篇:https://ithelp.ithome.com.tw/articles/10258...

Day10. 深入了解 Block - Block Part3

在Block系列文章里面 Day8 提到了Block, Proc Day9 提到了yield Day...

[2021铁人赛 Day-02] 嵌入式学习模式 and 系统分类

引言 今天介绍嵌入式系统学习的模式,并说明未来的撰写模式 = ) 学习十字路口 学习新知识必定会有...