Search code examples
powershellbatch-filestring-interpolation

Batch/Shell script to update to text file arguments


I have a text file with the contents example.txt

My name is {param1}
I live in {param2}
These are all the parameters passed to batch scripts {params}

How should i write and Batch/shell script to pass arguments to example.txt file


Solution

  • Caveat: Use the following solutions only with input files that you trust, because it is possible to embed arbitrary commands inside the text (preventing that is possible, but requires more work):

    In a PowerShell script, named, say Expand-Text.ps1:

    # Define variables named for the placeholders in the input file,
    # bound to the positional arguments passed.
    $param1, $param2, $params = $args[0], $args[1], $args
    
    # Read the whole text file as a single string.
    $txt = Get-Content -Raw example.txt
    
    # Replace '{...}' with '${...}' and then use
    # PowerShell's regular string expansion (interpolation).
    $ExecutionContext.InvokeCommand.ExpandString(($txt -replace '\{', '${'))
    

    Calling .\Expand-Text.ps1 a b c then yields:

    My name is a
    I live in b
    These are all the parameters passed to batch scripts a b c
    

    In a batch file, named, say expandText.cmd, using PowerShell's CLI:

    @echo off
    
    :: # \-escape double quotes so they're correctly passed through to PowerShell
    set params=%*
    set params=%params:"=\"%
    
    :: "# Call PowerShell to perform the expansion.
    powershell.exe -executionpolicy bypass -noprofile -c ^
      "& { $txt = Get-Content -Raw example.txt; $param1, $param2, $params = $args[0], $args[1], $args; $ExecutionContext.InvokeCommand.ExpandString(($txt -replace '\{', '${')) }" ^
      %params%