Batch/Shell 用于更新文本文件参数的脚本

Batch/Shell script to update to text file arguments

我有一个包含内容的文本文件 example.txt

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

我应该如何编写 Batch/shell 脚本来将参数传递给 example.txt 文件

您不需要创建文本文件。我给一个 用于创建文本文件并将参数传递给它的批处理文件代码。

@echo off
echo My name is %1 >example.txt
echo I live in %2 >>example.txt
echo These are all the parameters passed to batch scripts %* >>example.txt
goto :eof

保存为param.bat,运行保存为param.bat param1 param2

警告:仅对您信任的输入文件使用以下解决方案,因为可以在文本中嵌入任意命令(防止这种情况是可能的,但需要更多的工作):

PowerShell 脚本 中,命名为 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 '\{', '${'))

调用 .\Expand-Text.ps1 a b c 然后产生:

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

批处理文件 中,命名为 expandText.cmd,使用 PowerShell 的 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%