【发布时间】:2021-11-24 10:14:36
【问题描述】:
我需要连接到 VPN 连接才能访问内部网站。 VPN 软件没有任何自动连接机制,因此我希望使用 PowerShell 将其自动化。 我的 PowerShell 技能非常基础,我需要帮助才能让我的脚本正常工作。我从网上获取了一些代码片段,当我将每个函数作为单独的脚本启动时它可以工作,但是当我尝试使用 If Else 语句检查 VPN 状态时,它似乎以错误的顺序启动函数。
我为我的脚本中的每个任务创建了单独的函数。
- VPN-Check:检查网站是否可访问。如果 HTTP 响应正常,则返回 true。如果无法访问,则返回 false。
- VPN-Connect:启动 VPN 客户端软件,然后发送按键以模拟输入密码并单击连接。
- VPN-Disconnect:模拟在 VPN 软件上断开连接并停止 VPN 服务。
- VPN-Cleanup:终止所有剩余的 VPN 进程和服务
定义完所有函数后,这是我的代码:
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"}
【问题讨论】:
-
=是 assignment 运算符 - 它不会进行比较 :) 你想要if(-not $Isconnected){ <# cleanup and connect#> }else{ <# already connected #>}
标签: powershell automation