这是我的第一个 Powershell 脚本,所以在这里学习。但我遇到了一个问题,如果我将脚本粘贴到以管理员身份运行的 powershell 中,它会完美运行,但当我单击 ps1 文件时,它不会像我只切换单个适配器时那样提升为管理员。
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
$Connection = Get-CimInstance -Class Win32_NetworkAdapter -Property NetConnectionID,NetConnectionStatus | Where-Object { $_.NetConnectionStatus -eq 2 } | Select-Object -Property NetConnectionID -ExpandProperty NetConnectionID
if( $Connection -eq "Wi-Fi"){
Disable-NetAdapter -Name Wi-Fi -Confirm:$false
Enable-NetAdapter -Name Ethernet -Confirm:$false
} elseif( $Connection -eq "Ethernet"){
Disable-NetAdapter -Name Ethernet -Confirm:$false
Enable-NetAdapter -Name Wi-Fi -Confirm:$false
}
虽然单适配器交换机可以完美地提升至管理员权限,但我不明白为什么这在切换脚本上不起作用!以下是有效的方法:
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
exit;
}
Disable-NetAdapter -Name Wi-Fi -Confirm:$false
Enable-NetAdapter -Name Ethernet -Confirm:$false
答案1
您的 If 语句未正确处理字符串。以下行:
if($Connection -eq Wi-Fi){
和
elseif($Connection -eq Ethernet){
应该:
if($Connection -eq "Wi-Fi"){
和
elseif($Connection -eq "Ethernet"){
注意琴弦无线上网和以太网用双引号引起来。单引号也可以。
答案2
尝试这样的事情。
#Up is the status for a connected network adapter and Disconnected is the status for one that isn't.
$up = "Up"
$wifi = "Wi-Fi"
$lan = "Ethernet"
$wifiUp = Get-NetAdapter | select Name,Status | where { $_.Status -match $up -and $_.Name -match $wifi }
$lanUp = Get-NetAdapter | select Name,Status | where { $_.Status -match $up -and $_.Name -match $lan }
if ($lanUp)
{
Write-Host("Ethernet is Connected")
}
elseif ($wifiUp)
{
Write-Host("Wifi is Connected")
Disable-NetAdapter -Name "Wi-Fi" -Confirm:$false
Enable-NetAdapter -Name "Ethernet" -Confirm:$false
}
elseif ($wifiUp -And $lanup)
{
Write-Host("Both are Connected")
Disable-NetAdapter -Name "Wi-Fi" -Confirm:$false
}
else
{
Write-Host("All Disconnected")
}