Home > database >  How to use cmdlet inside an expression
How to use cmdlet inside an expression

Time:03-01

As explained in this previous question, I would like to have the name and the file version of a list of files inside a directory.

Until now, thanks to Theo, I already have this:

$result = 
  Get-ChildItem -Path 'X:\path with spaces' | 
    Where-Object {$_.Extension -match '\.(dll|exe)'} |
    Select-Object Name, 
                  @{Name = 'FileVersion'; 
                    Expression = {$_.VersionInfo.FileVersion}}

Now I would like to add the checksum to that.
In order to achieve this, this is what I have tried:

$result = 
  Get-ChildItem -Path 'X:\path with spaces' | 
    Where-Object {$_.Extension -match '\.(dll|exe)'} |
      Select-Object Name, 
                    @{Name = 'FileVersion'; 
                      Expression = {$_.VersionInfo.FileVersion}}, 
                    @{Name = 'CheckSum'; 
                      Expression = {Get-FileHash($_).Hash}}

So, basically, I have added another "thing" with a name and an expression, which I tried to add (in case this seems ridiculous: this is my first Powershell day :-) ).
This does not work, but there is no error message: it's just as if the question for the checksum is not even there.

Does anybody know how I can solve this?
Thanks in advance

CodePudding user response:

Your code is actually giving an error however errors inside the expression script block are quietly ignored. See Notes of the official docs.

PS /> @{} | Select-Object @{Name = 'Something'; Expression = { throw }}

Something
---------

If you inspect the your $Error automatic variable you would likely see something like:

PS /> $Error[0]

Get-FileHash: Cannot bind argument to parameter 'Path' because it is null.

The right expression should be:

Expression = {(Get-FileHash $_.FullName).Hash}
  • Related