At the moment, I've created a really, really basic PS script that simply checks the default connection and connects to the VPN if the default isn't the one specified in the script:

$DefaultNetworkIndex = Get-NetRoute -DestinationPrefix | Sort-Object {$_.RouteMetric+(Get-NetIPInterface -AssociatedRoute $_).InterfaceMetric} | Select-Object -First 1 -ExpandProperty InterfaceIndex
$DefaultNetwork = (Get-NetConnectionProfile -InterfaceIndex $DefaultNetworkIndex).Name

if ($DefaultNetwork -ne 'Some Connection Name') {
    Invoke-Expression 'rasdial VPN username password /phonebook:rasphone.pbk'

I want to flesh it out to:

  1. constantly monitor network changes and do stuff in response
  2. block any network access if it's in an unspecified network until the VPN is running

But my Google-fu did not find me any way to let do the above points. Any pointers to let me accomplish them (some networking library for PS, maybe?) would be very welcome.


I see 2 ways you could do this.

One is running a PowerShell script continuously, so you check for changed network conditions in a loop every N seconds (using the sleep command to idle).

Another and probably better is to have your script startup from Windows Task Scheduler events. You can for example trigger checks when the user logs on or the machine starts up. You can also define specific triggers using events from the system event log, which might contain network related events that you can use (I haven't used this for network related things so I'd have to check myself). By using the right triggers you might be able to have your script run only when network conditions change.

Hope this helps.

  • Well, I already am using the Task Scheduler to run the above whenever the network state changes... – Oxwivi Oct 27 '15 at 11:44
  • Oh well, that's pretty much all you can do with PS I think. Except rewriting it as a native service that monitors the network specs in real-time. – jurgenb Oct 27 '15 at 15:36
  • ... I overestimated PS... – Oxwivi Oct 27 '15 at 15:43
  • 1
    Don't get me wrong. PS is a very powerful scripting language. But it's not something you'd want to write a Windows service in (or even can) or a desktop application. You can access any .NET object from PS as well, so you can do almost everything you can in a .NET application as well. It's just rather tedious to write it all out in a script file. It's about finding the right tool for the job, and sometimes PS ain't the right tool. – jurgenb Oct 27 '15 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.