I'm not fluent into PowerShell, and I struggle on a somewhat simple problem:
I want to encrypt a (small) random file with DPAPI and write the result into another file.
I can encrypt an immediate string:
'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
--> the result is a bunch of digits: 1000000d08c9d[...]0e35854
Same thing, output into a file:
'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path output.txt
--> the file is created, and contains the right data
But I don't understand how to get data from a file:
# content of a file
Get-Content -Path input.txt
# --> 1st line
# blah
# last line
# pipe it into a command
Get-Content -Path input.txt | Measure-Object -line -word
# --> Lines Words Characters Property
# ----- ----- ---------- --------
# 3 5
# but can not pipe it into ConvertTo-SecureString
Get-Content -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
# + ... -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | Conve ...
# + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# + CategoryInfo : InvalidData : (:PSObject) [ConvertTo-SecureString], ParameterBindingValidationException
# + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
Question: how can I make ConvertTo-SecureString to read a file's content?
Thanks to @Santiago Squarzon
for the answer: Get-Content
by default return an array of strings.
To get the "real" data, the "-raw" parameter must be used.
Get-Content -Path input.txt -Raw | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> 1000000d08c9d[...]0e35854
The issue here is data type mismatch. ConvertTo-SecureString takes String input and not arrays. When in doubt run GetType() method on your object:
'cleartext'.GetType().Name
String
whereas return from vanilla Get-Content is array of objects:
(Get-Content .\input.txt).GetType().Name
Object[]
You don't have to use the Name property but its so much cleaner.
So as proposed in the comments using the " -Raw " switch will give you what you need:
(Get-Content .\input.txt -Raw).GetType().Name
String
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.