@mcp.tool(name="open_powershell", description="打开新的 PowerShell 窗口")
def open_new_powershell(working_directory:
Annotated[str, Field(description="可选的工作目录,为空则使用当前目录", examples="C:\\Users")] = "") -> str:
"""打开新的 PowerShell 窗口"""
try:
# 1. 检查并修复执行策略(关键步骤!)
fix_execution_policy()
# 2. 使用 Windows 'start' 命令启动 PowerShell,这是最可靠的方法
import subprocess
import os
# 构建 start 命令
if working_directory and os.path.exists(working_directory):
# 切换到指定目录并启动 PowerShell
command = f'start cmd /c "cd /d "{working_directory}" && powershell.exe -NoExit"'
else:
# 直接启动 PowerShell
command = 'start powershell.exe -NoExit'
# 使用 CREATE_NEW_CONSOLE 标志启动新控制台
subprocess.Popen(
command,
shell=True,
creationflags=subprocess.CREATE_NEW_CONSOLE
)
time.sleep(2) # 等待窗口初始化
processes = get_powershell_processes()
return f"PowerShell 已打开,当前运行进程数: {len(processes)}"
except Exception as e:
return f"打开 PowerShell 失败: {str(e)}" return f"打开 PowerShell 失败: {str(e)}"相似问题