1

I want to write a Powershell script that acts as a toggle for a connection to the internet each time it is run. I wrote this, which works:

$isconnected = netsh wlan show interfaces | select-string SSID | Out-String

if($isconnected.length -eq 0)
{  
  netsh wlan connect "My Network Name"
}
else
{
  netsh wlan disconnect
}

but I'm not sure if there are situations where this might fail. One that comes to mind is whenever the computer is on a new network whose name isn't specified in the script. Is there some way to get around specifying the network name? Are there better ways to do this?

1
  • "Is there some way to get around specifying the network name?", do you want to enter the network name dynamically? Jun 23, 2021 at 9:32

2 Answers 2

0

Unfortunately, netsh is for known networks.

This has already been answered here:

How to connect to WIFI with NETSH

0
0

One that comes to mind is whenever the computer is on a new network whose name isn't specified in the script. Is there some way to get around specifying the network name?

You can can get the network name dynamically by piping the output of the select-string to select-object and select the first one line of the output. Then remove any characters before its name.

$network = $isconnected -replace '.*: ',''

Your code will look like this:

$isconnected = netsh wlan show interfaces | select-string SSID | select-object -First 1 | Out-String

if($isconnected.length -eq 0)
{ 
  $network = $isconnected -replace '.*: ',''
  netsh wlan connect $network
}
else
{
  netsh wlan disconnect
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .