首页 > 解决方案 > 如何将 Powershell 函数转换为在 Python 脚本中工作?

问题描述

我在 Powershell 中有一个函数,它给出了一个文件夹的路径,返回一个计算的哈希值。我需要它在 Python 脚本中工作。我的问题是:如何将其转换为在 Python 中工作?谢谢。

function Get-FolderHash ($folder) {
 dir $folder -Recurse | ?{!$_.psiscontainer} | %{[Byte[]]$contents += [System.IO.File]::ReadAllBytes($_.fullname)}
 $hasher = [System.Security.Cryptography.SHA1]::Create()
 $a = [string]::Join("",$($hasher.ComputeHash($contents) | %{"{0:x2}" -f $_}))
 Write-Host $a
}
Get-FolderHash "PATH_TO_FOLDER"

标签: python-2.7powershell

解决方案


一个简单的选项可以让 Python 执行 Powershell 并捕获 std_out:

导入子进程,系统

p = subprocess.Popen(["powershell.exe", "C:\Users\USER\Desktop\helloworld.ps1"], stdout=sys.stdout)

p.communicate()

参考

也许你也可以尝试拿出 Powershell 让 Python 处理一切


推荐阅读