powershell脚本检查互联网连接,然后执行if-else



我想做一个脚本,首先检查互联网连接,以及计算机是否有互联网下载文件。如果电脑没有互联网,外壳应该写上"你没有连接到互联网"。该脚本不适用于

连接测试网络连接www.hawk.de-CommonTCPPort HTTP{}

我的脚本是:

if() {
$client = new-object System.Net.WebClient
$client.Credentials = Get-Credential
$client.DownloadFile(“https://www.mydomain.de/sites/default/files/styles/xs_12col_16_9_retina/public/DSC_6947.JPG”,“C:UsersOleDownloadsGithubbild.JPG”)
}else {
Write-Host "Could not connect to the Internet."
}
fi

谢谢你的帮助。

为if块尝试此操作。。

IF (((Test-NetConnection www.site.com -Port 80 -InformationLevel "Detailed").TcpTestSucceeded) -eq $true)

更改网址以明显适应。。。

Windows作为网络位置感知的一部分跟踪Internet连接状态;你可以使用类似的东西来检查这个状态:

If ((Get-NetConnectionProfile).IPv4Connectivity -contains "Internet" -or (Get-NetConnectionProfile).IPv6Connectivity -contains "Internet") {
# Do something here
}

https://learn.microsoft.com/en-us/windows/win32/winsock/network-location-awareness-service-provider-nla--2

您可以使用try。。捕获块:

try {
$client = new-object System.Net.WebClient $client.Credentials = Get-Credential $client.DownloadFile(“https://www.mydomain.de/sites/default/files/styles/xs_12col_16_9_retina/public/DSC_6947.JPG”,“C:UsersOleDownloadsGithubbild.JPG”) 
}
catch {
write-host "Not connected to the internet"
}

如果。。fi语法指的是不是powershell的bash。尝试Catch用于处理异常和错误。

最新更新