Home > OS >  Send result of powershell script in file
Send result of powershell script in file

Time:01-21

Am I doing something wrong with the following code : if yes, please, how can i fix it ?

$currentDir = Get-Location
$output = Write-Host "$currentDir\computedMD5.txt"
Get-FileHash $currentDir\* -Algorithm MD5 | Format-List | Out-File -FilePath $output

CodePudding user response:

When trying the same code (ofcourse adjusted to my folders) I get an error about the target file can't be read.

I then tried encapsulating the main operations in brackets and all was fine and dandy:

( Get-FileHash * | Format-List ) | Out-File t.txt -Force

I'm no expert on PS pipelines, but I suspect that the problem is something like a racing condition, that the target file is opened before the filehash is calculated. When using the brackets, the code inside is run first, and then outputs that result to the pipeline.

Although, I can only guess this is a solution, since there are no errors in the question to guide us to what is actually happening for you.

CodePudding user response:

Just a guess as you don't explain what exactly you're trying to do but regardless you're overcomplicating things:

$currentDir = Get-Location
Get-FileHash "$currentDir\*" -Algorithm MD5 | Out-File -FilePath "$currentDir\computedMD5.txt"

It's probably not a good idea to use a wildcard for input though unless you specifically code for multiple matches. So a better appproach if you have multiple files is as follows:

$currentDir = Get-Location
Get-ChildItem -Path $currentDir | ForEach-Object {
Get-FileHash $_.FullName -Algorithm MD5 | Out-File -FilePath ($_.FullName   "_computedMD5.txt")
}
  •  Tags:  
  • Related