我有一个template.txt
文件,其中包含以下内容:
Hello ${something}
我想创建一个PowerShell脚本来读取文件并扩展模板中的变量,即
$something = "World"
$template = Get-Content template.txt
# replace $something in template file with current value
# of variable in script -> get Hello World
我该怎么办?
最佳答案
另一种选择是使用ExpandString()例如:
$expanded = $ExecutionContext.InvokeCommand.ExpandString($template)
调用表达也将起作用。但是要小心。这两个选项都能够执行任意代码,例如:
# Contents of file template.txt
"EvilString";$(remove-item -whatif c:\ -r -force -confirm:$false -ea 0)
$template = gc template.txt
iex $template # could result in a bad day
如果您希望拥有一个“安全”的字符串eval而不会意外运行代码,则可以将PowerShell作业和受限制的运行空间结合使用,例如:
PS> $InitSB = {$ExecutionContext.SessionState.Applications.Clear(); $ExecutionContext.SessionState.Scripts.Clear(); Get-Command | %{$_.Visibility = 'Private'}}
PS> $SafeStringEvalSB = {param($str) $str}
PS> $job = Start-Job -Init $InitSB -ScriptBlock $SafeStringEvalSB -ArgumentList '$foo (Notepad.exe) bar'
PS> Wait-Job $job > $null
PS> Receive-Job $job
$foo (Notepad.exe) bar
现在,如果您尝试在使用cmdlet的字符串中使用表达式,则不会执行以下命令:
PS> $job = Start-Job -Init $InitSB -ScriptBlock $SafeStringEvalSB -ArgumentList '$foo $(Start-Process Notepad.exe) bar'
PS> Wait-Job $job > $null
PS> Receive-Job $job
$foo $(Start-Process Notepad.exe) bar
如果尝试执行命令时希望失败,请使用$ ExecutionContext.InvokeCommand.ExpandString扩展$ str参数。
关于powershell - 在文件内容中扩展变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1667023/