You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用PowerShell控制显示器定时开关的参数错误求助

解决PowerShell调用SendMessage的语法错误

问题出在你误用了cmd的换行转义符^,PowerShell不识别这个符号,它会被当作C#代码的一部分,引发编译失败。

修正方案1:将^替换为PowerShell换行符`n

直接把代码里的^换成PowerShell的换行转义符`n(注意是反引号),让C#代码的属性和方法分行:

# 开启显示器函数
def turn_monitor_on():
    subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")]`npublic static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)"])
# 关闭显示器函数
def turn_monitor_off():
    subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")]`npublic static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"])

修正方案2:写成单行合法C#代码

C#允许属性和方法在同一行(用空格分隔),直接去掉^即可:

# 开启显示器函数
def turn_monitor_on():
    subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)"])
# 关闭显示器函数
def turn_monitor_off():
    subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"])

额外优化:用Here-String简化PowerShell代码

如果想让C#代码更易读,可以用PowerShell的Here-String来定义多行代码,避免转义麻烦:

import subprocess

def turn_monitor_on():
    ps_cmd = """(Add-Type @'
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
'@ -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)"""
    subprocess.run(["powershell", ps_cmd])

def turn_monitor_off():
    ps_cmd = """(Add-Type @'
[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
'@ -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"""
    subprocess.run(["powershell", ps_cmd])

内容的提问来源于stack exchange,提问作者Murat Sadyrbekov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:12:23