我希望我的 Windows 在加载后立即连接到 VPN 服务器。我如何使用 Powershell 来做到这一点?
4 回答
试试这个适用于 Windows 10
$vpnName = "YOUR_VPN_NAME";
$vpn = Get-VpnConnection -Name $vpnName;
if($vpn.ConnectionStatus -eq "Disconnected"){
rasdial $vpnName;
}
你可以尝试这样的事情:
我还没有测试它是否有效。我安装了PowerShell V3 Beta - 可能需要运行这些命令。
Register-ScheduledJob -name ConnectVPN -ScriptBlock { & rasphone MyVpnConnection
$trigger = New-JobTrigger -AtLogOn
Add-JobTrigger -Name ConnectVPN -Trigger $trigger
Get-ScheduledJob -Name ConnectVPN | Get-JobTrigger
除了其他答案外,Windows 10 还通过名为 Always On 的配置原生支持此功能。有关始终开启的更多详细信息,请访问https://docs.microsoft.com/en-us/windows/access-protection/vpn/vpn-auto-trigger-profile
您可以通过 MDM 甚至使用 WMI/Powershell 进行部署
部署参考
VPN 2 CSP:https ://docs.microsoft.com/en-us/windows/client-management/mdm/vpnv2-csp
Windows VPN 设置中的“自动连接”复选框对我来说效果很好。但是在配置拆分隧道以连接到锁定到 VPN IP 地址的 VM 后,需要断开/重新连接 VPN 连接才能生效。问题在于rasdial /disconnect
禁用 AutoTrigger 设置。以下似乎可以重新启用自动触发。
在此处设置特定的 VPN 配置文件名称或使用从 Get-VpnConnection 返回的第一个:
$vpnProfileName = Get-VpnConnection | select -first 1 -ExpandProperty Name
显示如何设置拆分隧道的可选示例:
# Enable split-tunneling to a specific address
# Name of VM restricted to VPN IP addresses
$vmName = "myserver.eastus.cloudapp.azure.com"
$ip = $(Resolve-DnsName -name $vmName | where section -eq answer).IPAddress
Add-VpnConnectionRoute -Name $vpnProfileName -DestinationPrefix "$ip/32"
# Rasdial disconnect will turn off AutoTriggering
rasdial $vpnProfileName /disconnect
# Check VPN status
Get-VpnConnection | select Name, IsAutoTriggerEnabled, ConnectionStatus
重新启用自动触发并启动 VPN 连接:
# Remove Disabled Profile
$disabledProfiles = [string[]](Get-ItemPropertyValue HKLM:SYSTEM\CurrentControlSet\Services\RasMan\Config -name AutoTriggerDisabledProfilesList)
$disabledProfiles = $disabledProfiles | where { $_ -ne $vpnProfileName }
Set-ItemProperty HKLM:SYSTEM\CurrentControlSet\Services\RasMan\Config -name AutoTriggerDisabledProfilesList -Type MultiString -Value $disabledProfiles
# Remove AutoTriggeringDisabled
Remove-ItemProperty HKLM:SYSTEM\CurrentControlSet\Services\RasMan\Config -name AutoTriggeringDisabled
# Add trigger to a process that is certain to be running. Will trigger on process launch as well as if it is already running.
# Adding trigger even it already exists seems to be necessary to get it to trigger after rasdial /disconnect
Add-VpnConnectionTriggerApplication -Name $vpnProfileName –ApplicationID "C:\Windows\explorer.exe" -ErrorAction Ignore
# Check VPN status
Get-VpnConnection | select Name, IsAutoTriggerEnabled, ConnectionStatus