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

求助:Python调用PowerShell脚本并实现菜单选择执行功能

Python Script to Launch PowerShell Scripts via Menu: Troubleshooting & Working Example

Hey there! Let's get your Python menu script working properly. First, here's a complete, tested version that handles folder scanning, menu generation, user input validation, and safe PowerShell execution:

import os
import subprocess

def main():
    # 替换成你的PowerShell脚本文件夹路径(绝对路径更可靠)
    ps_script_dir = r"C:\Your\PowerShell\Scripts\Folder"
    
    # 筛选出文件夹中的.ps1文件
    ps_scripts = [f for f in os.listdir(ps_script_dir) if f.endswith(".ps1")]
    
    if not ps_scripts:
        print("No PowerShell scripts found in the specified folder.")
        return
    
    # 生成数字菜单
    print("Available PowerShell Scripts:")
    for idx, script in enumerate(ps_scripts, 1):
        print(f"{idx}. {script}")
    
    # 获取并验证用户输入
    while True:
        try:
            choice = int(input("\nEnter the number of the script to run: "))
            if 1 <= choice <= len(ps_scripts):
                break
            else:
                print(f"Please enter a number between 1 and {len(ps_scripts)}.")
        except ValueError:
            print("Invalid input! Please enter a valid number.")
    
    # 构建完整的脚本路径
    selected_script = os.path.join(ps_script_dir, ps_scripts[choice - 1])
    
    # 运行PowerShell脚本(捕获输出和错误,方便调试)
    try:
        # 使用powershell.exe(Windows默认)或pwsh(PowerShell Core),根据你的环境调整
        result = subprocess.run(
            ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", selected_script],
            capture_output=True,
            text=True,
            check=True
        )
        print("\nScript ran successfully! Output:")
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"\nScript failed with error code {e.returncode}. Error output:")
        print(e.stderr)
    except FileNotFoundError:
        print("Error: Could not find powershell.exe. Check if PowerShell is installed or use 'pwsh' instead.")

if __name__ == "__main__":
    main()

Common Issues & Fixes

If your original code wasn't working, here are the most likely culprits to check:

  • Incorrect Folder Path: Always use absolute paths (like C:\Scripts) instead of relative paths unless you're 100% sure the working directory is correct. Use os.path.abspath() to convert relative paths to absolute if needed.
  • PowerShell Execution Policy: By default, Windows blocks unsigned scripts. The -ExecutionPolicy Bypass flag in the example bypasses this for the current run (safer than changing the system-wide policy permanently).
  • Unvalidated User Input: If your original code didn't check if the input was a valid number or within the menu range, it would crash when users enter non-numbers or out-of-range values. The example uses a while loop with try-except to handle this.
  • Missing Error Handling: Without capturing subprocess errors, you wouldn't know if the PowerShell script failed or why. The example uses check=True and catches CalledProcessError to show error output.
  • Incorrect PowerShell Executable: If you're using PowerShell Core (not the Windows default), replace powershell.exe with pwsh in the subprocess.run call.

Test this example first with a simple PowerShell script (like one that just writes Write-Host "Hello World"), then adapt it to your folder path. If you hit specific error messages, feel free to share them and I can help troubleshoot further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:15:41