powershell - 在文件内容中扩展变量

标签 powershell variables

我有一个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/

相关文章:

variables - 在 jekyll include 中传递多个变量并检测分配了哪些变量

c - 变量只读

powershell - 编辑 CSV 标题

PowerShell:为什么 "Get-Content <file> | Out-File -Append <file>"会进入循环?

regex - AS3将动态变量包含到regexp对象中

c++ - 在 C switch/case 中声明变量

variables - 传递 Javascript Alert 一个值

bash - cd-vs cd ..说明

powershell - DNS 记录数据作为 DnsServerResourceRecordA 出现

powershell - 使用 Begin/Process/End block 时如何一次性获取所有对象?