I've got a powershell script where the end goal is to just print the BitLocker Recovery Key to a text file, but I want to use the Where-Object to get only the RecoveryPassword, as opposed to the TPM information.
If I run the last line, it works fine. If I try to run the command passed to a variable, I get an error stating ".KeyProtectorType : The term '.KeyProtectorType' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
I think it's some issue with directory changing because it's being passed in a variable, but I do not know how to work around it.
$location = "$env:UserProfile\Desktop\BitLockerRecoveryKey.txt"
$args = "Get-BitLockerVolume -MountPoint C:| Select-Object -ExpandProperty KeyProtector | Where-Object{$_.KeyProtectorType -eq 'RecoveryPassword'}| Select-Object KeyProtectorID,RecoveryPassword >" $location
# Get the ID and security principal of the current user account
iex $args
Get-BitLockerVolume -MountPoint C:| Select-Object -ExpandProperty KeyProtector | Where-Object{$_.KeyProtectorType -eq 'RecoveryPassword'}| Select-Object KeyProtectorID,RecoveryPassword
CodePudding user response:
Invoke-Expression
(iex
) should generally be avoided; definitely don't use it to invoke an external program or PowerShell script, even if you need to construct its arguments programmatically - the latter is best done via splatting.Don't use the automatic
$args
variable for custom purposes.If you do need to embed
$
characters verbatim in a expandable (double-quoted) string ("..."
), escape them as`$
. If you string doesn't actually require expansion (string interpolation), use a verbatim (single-quoted) string ('...'
)- Neglecting to escape the
$
characters as`$
in your"..."
string is what caused your problem:$_
was expanded beforeiex
saw the resulting string, and - outside a pipeline - the automatic$_
variable doesn't have a value.
- Neglecting to escape the
In your case, you can use the value of variable $location
directly to pass the output file path to >
, the redirection operator
$location = "$env:UserProfile\Desktop\BitLockerRecoveryKey.txt"
Get-BitLockerVolume -MountPoint C:|
Select-Object -ExpandProperty KeyProtector |
Where-Object KeyProtectorType -eq RecoveryPassword |
Select-Object KeyProtectorID, RecoveryPassword > $location
Note that I've used simplified syntax in the Where-Object
call above.