0

I have a function in Powershell which given a path to a folder, returns a computed hash. I need it to work within a Python script. My question is: how can I convert it to work within Python? Thanks.

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"
s123
  • 461
  • 1
  • 4
  • 18

1 Answers1

0

A simple option can let Python execute Powershell and capture the std_out:

import subprocess, sys

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

p.communicate()

reference

But perhaps you can also try to take out Powershell and let Python handle everything

DeDenker
  • 397
  • 3
  • 14
  • Thanks for your answer. I'd rather have the powershell code within the script to avoid file dependencies. I must use Powershell because I actually want to perform this command on a remote system, which I cannot do with Python. – s123 Feb 21 '19 at 10:01
  • Depending on what remote means in that context you could also just setup a file share on the remote side and use that ... clunky but works in various circumstances. – Seth Feb 21 '19 at 10:10