Reputation: 23
I have a Commands.csv file like:
| Command |
| -----------------------------------------------|
|(Get-FileHash C:\Users\UserA\Desktop\File1).Hash|
|(Get-FileHash C:\Users\UserA\Desktop\File2).Hash|
|(Get-FileHash C:\Users\UserA\Desktop\File3).Hash|
Header name is "Command"
My idea is to:
ForEach ($line in Get-Content C:\Users\UserA\Desktop\Commands.csv ) {echo $line}
Can you give me some directions and suggestions to implement this idea? Thanks!
Upvotes: 2
Views: 554
Reputation: 437698
Important:
Only use the technique below with input files you either fully control or implicitly trust to not contain malicious commands.
To execute arbitrary PowerShell statements stored in strings, you can use Invoke-Expression
, but note that it should typically be avoided, as there are usually better alternatives - see this answer.
There are advanced techniques that let you analyze the statements before executing them and/or let you use a separate runspace with a restrictive language mode that limits what kinds of statements are allowed to execute, but that is beyond the scope of this answer.
Given that your input file is a .csv
file with a Commands
column, import it with Import-Csv
and access the .Commands
property on the resulting objects.
Get-Content
only if your input file is a plain-text file without a header row, in which case the extension should really be .txt
. (If it has a header row but there's only one column, you could get away with Get-Content Commands.csv | Select-Object -Skip 1 | ...
). If that is the case, use $_
instead of $_.Commands
below.To also use the CSV format for the output file, all commands must produce objects of the same type or at least with the same set of properties. The sample commands in your question output strings (the value of the .Hash
property), which cannot meaningfully be passed to Export-Csv
directly, so a [pscustomobject]
wrapper with a Result
property is used, which will result in a CSV file with a single column named Result
.
Import-Csv Commands.csv |
ForEach-Object {
[pscustomobject] @{
# !! SEE CAVEAT AT THE TOP.
Result = Invoke-Expression $_.Commands
}
} |
Export-Csv -NoTypeInformation Results.csv
Upvotes: 5