我有一个包含内容的文本文件 example.txt
My name is {param1}
I live in {param2}
These are all the parameters passed to batch scripts {params}
我应该如何编写和批处理/ shell脚本以将参数传递给example.txt文件
我有一个包含内容的文本文件 example.txt
My name is {param1}
I live in {param2}
These are all the parameters passed to batch scripts {params}
我应该如何编写和批处理/ 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
在批处理文件中,使用PowerShell的CLI命名为expandText.cmd
,
@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,$args; $ExecutionContext.InvokeCommand.ExpandString(($txt -replace '\{','${')) }" ^
%params%