iT邦幫忙

2021 iThome 鐵人賽

DAY 11
0
自我挑戰組

Powershell 入门系列 第 11

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.

上一篇
Powershell 入门之循环(下)
下一篇
Powershell 入门之函数
系列文
Powershell 入门21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言