我有一个Python脚本可以使用输入模拟来启用/禁用
Airplane mode
,效果很好:
import pyautogui
pyautogui.hotkey('win', 'a')
pyautogui.press('right', presses=2)
pyautogui.press('space')
pyautogui.hotkey('win', 'a')
我尝试使用 PowerShell 来做到这一点:
$shell = New-Object -ComObject WScript.Shell
$shell.SendKeys("^{ESC}")
$shell.SendKeys("{RIGHT}")
$shell.SendKeys("{RIGHT}")
$shell.SendKeys(" ")
$shell.SendKeys("^{ESC}")
不过,好像没啥作用。
因为
$shell.SendKeys("^{ESC}")
打开Start Menu
,不是我想要的Action Center
。
正确的命令是什么?
Win + A
GUI 脚本,即交互式用户输入的编程模拟,始终是脆弱(可能会失败),因此最好寻找其他解决方案:
这个答案显示了用于切换飞行模式的 C# 代码,您可以通过
Add-Type
在 PowerShell 中进行调整和使用
这个 SU 答案展示了一种
wmic.exe
方法,通过启用或禁用 Wi-Fi 网络适配器来模拟打开或关闭飞行模式,但请注意,它需要 elevation(以管理员身份运行);由于语法原因,PowerShell 中需要稍作调整:
# REQUIRES ELEVATION
# Disables the Wi-Fi adapte; to enable, use "enable"
wmic.exe path win32_networkadapter where --% NetConnectionID="Wi-fI" call disable
如果您无法避免 GUI 脚本解决方案:
上面链接的 SU 答案提供了一种 GUI 脚本方法,不需要需要 WinKey(Windows 键)按键;适应PowerShell(未经测试):
# Start the Settings app and open the relevant page.
Start-Process ms-settings:network-airplanemode
# Give the app some time to open.
Start-Sleep -Milliseconds 1000
# Send a <space> char. to toggle, then Alt+F4 to close the window.
(New-Object -ComObject WScript.Shell).SendKeys(" %{F4}")
否则:
如果您可以假设已安装 Python,请通过 Python CLI 调用您的 Python 代码:
python -c 'import pyautogui; pyautogui.hotkey('win', 'a'); ...'
否则或替代地,编译一个使用 P/Invoke 的帮助程序类以允许发送基于 WinKey 的键和弦:请参阅这个答案。