0

I'm looking to be able to call this a function. If VPN check = true then execute the script. Ideally, I would like to check the VPN status and then execute the whole script. After this runs and returns true or fault I don't know how to reference it moving forward. This seemed simple when I was trying to come up with a plan. Any help would be much appreciated, I am very much a rookie writing powershell.

       #check VPN
      $vpnCheck = Get-WmiObject -Query "Select Name,NetEnabled from Win32_NetworkAdapter where 
      (Name like 'Juniper Networks Virtual Adapter' or Name like 'PANGP Virtual Ethernet 
       Adapter' or Name like '%VPN%') and NetEnabled='True'"

        # If it returns a value it's true, 
        # if it does not return a value it's false.
        $vpnCheck = [bool]$vpnCheck

        # Check if $vpnCheck is true or false.
        if ($vpnCheck) {
            return $vpnCheck
            exit(0)
        }
        else {
            return $vpnCheck
            exit(1)
mklement0
  • 382,024
  • 64
  • 607
  • 775
Justin E
  • 35
  • 7
  • As an aside: The CIM cmdlets (e.g., `Get-CimInstance`) superseded the WMI cmdlets (e.g., `Get-WmiObject`) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) v6+, where all future effort will go, doesn't even _have_ them anymore. Note that WMI still _underlies_ the CIM cmdlets, however. For more information, see [this answer](https://stackoverflow.com/a/54508009/45375). – mklement0 Dec 01 '21 at 22:52
  • At least to me, it's not clear what you're asking: What should be the parameter(s) to you function? And what is the _whole script_ you're referring to? And what are you looking to reference moving forward, aside from the Boolean `$vpnCheck` variable? Please update your question to clarify. – mklement0 Dec 01 '21 at 23:00

1 Answers1

0

Writing a parameter-less function to call a single cmdlet when you only need to invoke it once, is a bit overkill.

You can use the return keyword to return control to the caller if you don't want the rest of your script to execute:

$vpnCheck = Get-WmiObject -Query "Select Name,NetEnabled from Win32_NetworkAdapter where 
      (Name like 'Juniper Networks Virtual Adapter' or Name like 'PANGP Virtual Ethernet 
       Adapter' or Name like '%VPN%') and NetEnabled='True'"

if(-not $vpnCheck){
  # nothing below will ever execute if we reach this statement
  return
}

# rest of script ...
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206