PowerShell - Check if there is internet
/Find out if there is internet, with Power!
Say you were following along with my PowerShell backup with timestamp tutorial, however before running the script you wanted to make sure there was internet. Maybe you are backing up to a network location that needs internet, or pushing data to a database?
In my case, I had a PowerShell script that gathered data from a local database, then opened Excel, ran some macros before finally uploading it to a server. There was no point doing any of this if there was no internet, when the script came to upload it, it would throw an error. Instead of doing fancy error handing, I decided to keep it simple. If no Internet, abort script.
Is it simple?
Yes.
### Define functions ### function copyexcellen { write-host "Copying Files!" #Gets Time $timestamp = Get-Date -Format "dd-MMM-yyyy HH-mm-ss" #Define File and Copy Location $file = "C:\CopyCopy\ExcellenCopy.txt" $copyto = "C:\CopyCopy\CopyInhere\ExcellenCopy "+$timestamp+".txt" #Copy File Copy-Item $file -Destination $copyto } ### Run Functions ### $online = test-connection 8.8.8.8 -Count 1 -Quiet if ($online) {"There's Internet, proceeding" copyexcellen exit } else {"No Internet" exit}
I create my function up the top (simple copy script), down below I have a simple if statement that checks to make sure there is internet, before running the PowerShell script.
Functions are just like Excel macros. You can then call them like Excel macros, just without the call tag!
If this scares you:
### Run Functions ### $online = test-connection 8.8.8.8 -Count 1 -Quiet if ($online) {"There's Internet, proceeding" "COPY CODE HERE" exit } else {"No Internet" exit}
Just copy your code over “COPY CODE HERE”. Will work fine!
“test-connection 8.8.8.8” is pinging one of Google’s public DNS servers, this is a common test the world over. “Quiet” make the function return TRUE or FALSE, as opposed to a report. “Count” specifies how many echo requests to send - we only need one.
Easy, Powerful, PowerShell
Sky is the limit. For example maybe create a script that checks your computers idle time, if less than 5 minutes don’t launch the script (as a CPU intensive script can incredibly annoy you). Or if there is no internet, why not restart your computer automatically?
if this confuses you, read my introduction to PowerShell, which also tells you how to schedule scripts.