Reputation: 1
i wanna do a script which first checks the internet connection and if the computer has internet downloads a file. If the computer has no internet, the shell should write "You are not connected with the internet". The script does not work with
connection test-netconnection www.hawk.de -CommonTCPPort HTTP{}
My script is:
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
Thanks for your help.
Upvotes: 0
Views: 3152
Reputation: 462
Windows tracks Internet connection status as part of Network Location Awareness; you can check this status using something like this:
If ((Get-NetConnectionProfile).IPv4Connectivity -contains "Internet" -or (Get-NetConnectionProfile).IPv6Connectivity -contains "Internet") {
# Do something here
}
Upvotes: 2
Reputation: 15480
You can use try..catch block for this:
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"
}
if..fi syntax refers to bash that's not powershell. Try..Catch is used to handle exceptions and errors.
Upvotes: 0
Reputation: 833
Try this for your if block..
IF (((Test-NetConnection www.site.com -Port 80 -InformationLevel "Detailed").TcpTestSucceeded) -eq $true)
Change the web address to suit obviously...
Upvotes: 1