Ole
Ole

Reputation: 1

powershell script check internet connection then do if else

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

Answers (3)

Minkus
Minkus

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
}

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

Upvotes: 2

wasif
wasif

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

Zack A
Zack A

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

Related Questions