Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows powershell脚本检查internet连接,然后执行其他操作_Windows_Powershell_Google Chrome - Fatal编程技术网

Windows powershell脚本检查internet连接,然后执行其他操作

Windows powershell脚本检查internet连接,然后执行其他操作,windows,powershell,google-chrome,Windows,Powershell,Google Chrome,我想做一个脚本,首先检查互联网连接,如果计算机有互联网下载文件。如果电脑没有互联网,外壳上应该写上“你没有连接互联网”。该脚本不适用于 连接测试netconnection www.hawk.de-CommonTCPPort HTTP{} 我的剧本是: if() { $client = new-object System.Net.WebClient $client.Credentials = Get-Credential $client.DownloadFile(“https://www.myd

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

连接测试netconnection 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:\Users\Ole\Downloads\Github\bild.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)

更改网站地址以适应

您可以为此使用try..catch块:

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:\Users\Ole\Downloads\Github\bild.JPG”) 
}
catch {
  write-host "Not connected to the internet"
}

如果..fi语法指的是bash,那就不是powershell。Try..Catch用于处理异常和错误。

Windows将跟踪Internet连接状态作为网络位置感知的一部分;您可以使用以下方式检查此状态:

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

请比“不起作用”更详细一点-会发生什么?你在观察什么行为?是否抛出任何错误?如果是这样,请在此处发布:)记住,我们看不到您的屏幕
fi
不是powershell。您的
if
在最后一个大括号处结束。
-eq$true
是多余的
TcpTestSuccessed
已经是一个布尔值。可能-但它使其他人更容易阅读和理解代码。。。。如果其他人希望在失败时发生某些事情,它还允许他们轻松地更改代码/逻辑。因此,有了它,代码更容易阅读,更容易重构,也更容易让那些不太懂powershell的人理解。永远不要发布速记代码。。。每次你这么做,上帝都会杀了一只小狗。然后我建议你再加一个
-eq$true
来测试那句话的真值,再加一个
-eq$true
来测试那句话的真值,还有一个…只有一句话兄弟。。。如果事情是真的还是假的,你想让它发生吗?在任何情况下,您都可以根据所需的结果轻松地将true更改为false。我发布的内容通过一个易于阅读、简单灵活的代码块解决了OP的问题。你在吹毛求疵,因为我的代码可能和你写的不太一样。那很好,但是这对谈话没有任何影响。如果你投了赞成票,因为答案是正确的。但是对我来说,
if(x.tcptestsucceed)
读起来像普通英语,而
if(x.tcptestsucceed)-eq$true则不是。我不会问我的孩子“你做作业了吗-eq$true?”。