powershellpowershell-4.0

add string as a prefix to extracted string (PowerShell)


I have a script that extract set of sha256 hash from csv and save it in txt file, I want to add string (as a prefix) before each sha256 hash

the script:

$csvfileImport = "C:\test.csv"
$txtfileExport = "C:\result.txt"
$csv = Import-CSV $csvfileImport -Delimiter ","
$csv."sha256" -replace '^.\*?\\' | Set-Content $txtfileExport

output in txt file seem like that:

58cb1ef132fbdd1855f75c2886666275d1bb75a9fb3fed88d05feee4230afd32 8fdd00243ba68cadd175af0cbaf860218e08f42e715a998d6183d7c7462a3b5b

The string that I want to add as a prefix to each sha256 hash seem like this:

curl -X POST https://xxx..:xxx..@xxxx../xx/xxx../xxx.../xx../Here the HASH256 should be inserted

How can I achieve that in my existing script ?


Solution

  • A simple and efficient technique for prefixing each string in an input array with a fixed string is to use -replace '^', $prefix: regex ^ matches the position at the start of each input string, and the value of $prefix is placed there, effectively prefixing the input string.

    A simple example:

    # -> @('prefix=foo', 'prefix=bar')
    'foo', 'bar' -replace '^', 'prefix='
    

    Thus, you're probably looking for something like:

    $csv.sha256 -replace '^.\*?\\' -replace '^', 'curl -X POST https://xxx..:xxx..@xxxx../xx/xxx../xxx.../xx../' |
      Set-Content $txtfileExport