【问题标题】:Can't import AzureRM module in PowerShell while running from Python从 Python 运行时无法在 PowerShell 中导入 AzureRM 模块
【发布时间】:2017-12-28 13:27:32
【问题描述】:

我编写了一个 PowerShell 脚本,当我从 cmd as 运行它时它运行良好

powershell . C:\\scripts\\Azure.ps1; Review-Subscriptions -args xyz .\\output xxx-xxx-xxx 2017-23-07-01-04 

Azure.ps1 使用 AzureRM PowerShell 模块中的一些函数。

但是当我从 Python 运行相同的命令时,

path = "C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"
script_path = "C:\\scripts\\Azure.ps1"
function_name = "Review-Subscriptions"
subscription_id = 'xxx-xxx-xxx'
file_path = '.\\output"'
now = datetime.datetime.now().strftime("%Y-%d-%m-%H-%M")

cmd = '. %s; %s -args xyz %s %s %s' % \
      (script_path,
       function_name,
       file_path,
       subscription_id,
       now)
process = subprocess.Popen(
    [path, '-ExecutionPolicy', 'Unrestricted',
     cmd
     ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print process.communicate()

在这种情况下,PowerShell 没有加载 AzureRM 模块;这导致整个脚本失败。

我们如何强制加载 AzureRM 模块?

尝试关注但没有成功。

a) 在文件 Azure.ps1 的开头添加了Import-Module AzureRM
b) 将 cmd 更改为

cmd = 'Import-Module AzureRM; . %s; %s( %s, %s, "%s")' % \
          (script_path,
           function_name,
           file_path,
           subscription_id,
           now)

【问题讨论】:

  • 您运行的是哪个版本的 Python?鉴于 print 语句,我猜测 2.x 中的某些内容,但这会有所帮助,因为 subprocess 随着时间的推移发生了变化。
  • 我的 Python 版本是 3.6.1,p = subprocess.Popen(["powershell.exe", "-ExecutionPolicy", "Unrestricted", "C:\\Users\\jason\\Desktop \\11\\jasonlogin.ps1"], stdout=sys.stdout) 对我有用,我可以使用 ARM 命令获取信息,能否请您显示您的 ps1 和错误日志?
  • @DavidMetcalfe Python2.7 是的,它可以工作,我需要使用 python64 位。

标签: python powershell azure


【解决方案1】:

Powershell 模块安装在 x64 系统中。

我只需要安装 Pythonx64 并使用它与 PowerShell 进行通信。

我认为原因是,当我们使用 Pythonx86 时,它通过 x86 进程与 Powershell 通信,而在 Pyhonx64 的情况下,它使用 x64 进程与 PowerShell 通信。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多