I need to be connected to a VPN connection in order to access an internal website. The VPN software does not have any mechanism for automatically connecting so I am looking to automate it using PowerShell. My PowerShell skills are very basic and I need help getting my script working. I have taken bits and pieces of code from the web and it works when I launch each function as a separate script but when I try an If Else statement to check the VPN status it seems to launch the functions in the wrong sequence.
I have made separate functions for each task in my script.
- VPN-Check: Check if website is accessible. If HTTP response is OK return true. If inaccessible return false.
- VPN-Connect: Launch the VPN client software and then send keypresses to simulate entering in the password and clicking connect.
- VPN-Disconnect: Simulate hitting disconnect on the VPN software and stop the VPN services.
- VPN-Cleanup: Kills any remaining VPN processes and services
After defining all my functions this is my code:
function VPN-Check {
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('https://portal.domain.com/portal/login.jsp')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
#Write-Host "Site is OK!"
return $true
}
Else {
#Write-Host "The Site may be down, please check!"
return $false
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
}
function VPN-Connect {
write-host "Connecting to the VPN..."
Start-Process "C:\Program Files (x86)\AT&T Global Network Client\NetClient.exe"
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('AT&T Global Network Client')
Sleep 10
#$wshell.SendKeys('~')
#sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('MyPassw0rd')
Sleep 1
$wshell.SendKeys('~')
}
function VPN-Disconnect {
write-host "Disconnecting from VPN..."
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('AT&T Global Network Client')
Sleep 1
$wshell.SendKeys('~')
sleep 1
$wshell.SendKeys('{TAB}')
sleep 1
$wshell.SendKeys('~')
sleep 1
taskkill /im "NetClient.exe"
net stop "AT&T Network Configuration Service"
net stop "AT&T Global Network Client Service"
}
function VPN-Cleanup {
write-host "Killing the VPN..."
taskkill /f /im "NetClient.exe"
net stop "AT&T Network Configuration Service"
net stop "AT&T Global Network Client Service"
}
$Isconnected = VPN-Check
If ($Isconnected = "False") {
write-host "Connecting to VPN..."
VPN-Cleanup
VPN-Connect
}
else ($Isconnected = "True") {write-host "Already connected. Nothing to do"}