从GitHub获取PowerShell脚本并执行i

2024-06-30 15:48:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中执行PowerShell脚本时遇到问题。在

Python本身很简单,但它似乎是在调用时传入\n,并输出错误。在

['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL

以下是完整的代码:

^{pr2}$

所以我有两个问题:

  1. 如何在不写入磁盘的情况下正确地将脚本存储为变量,同时避免\n?在
  2. 从Python中调用PowerShell以运行存储在$script中的脚本的正确方法是什么?在

Tags: 代码test脚本url错误usernamepasswordexe
2条回答

我相信这是因为你正在打开PowerShell,它会自动以特定的方式格式化它。在

你可以做一个for循环,在不带/n的情况下遍历命令输出和打印

  1. How do I correctly store the script as a variable without writing to disk while avoiding \n?

这个问题本质上是this one的重复。在您的示例中,可以简单地删除换行符。更安全的选择是用分号代替它们。在

script = fetch.read().replace('\n', ';')
  1. What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?

命令必须作为数组传递。另外,您不能通过-File参数运行一系列PowerShell语句。使用-Command代替:

^{pr2}$

相关问题 更多 >