扩展文件内容中的变量 [英] Expanding variables in file contents

查看:28
本文介绍了扩展文件内容中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 template.txt,其中包含以下内容:

I have a file template.txt which contains the following:

Hello ${something}

我想创建一个 PowerShell 脚本来读取文件并扩展模板中的变量,即

I would like to create a PowerShell script that reads the file and expands the variables in the template, i.e.

$something = "World"
$template = Get-Content template.txt
# replace $something in template file with current value
# of variable in script -> get Hello World

我怎么能这样做?

推荐答案

另一种选择是使用 ExpandString() 例如:

Another option is to use ExpandString() e.g.:

$expanded = $ExecutionContext.InvokeCommand.ExpandString($template)

Invoke-Expression 也可以使用.不过要小心.这两个选项都能够执行任意代码,例如:

Invoke-Expression will also work. However be careful. Both of these options are capable of executing arbitrary code e.g.:

# 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 作业和受限运行空间来做到这一点,例如:

If you want to have a "safe" string eval without the potential to accidentally run code then you can combine PowerShell jobs and restricted runspaces to do just that e.g.:

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 的字符串中使用表达式,则不会执行该命令:

Now if you attempt to use an expression in the string that uses a cmdlet, this will not execute the command:

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 参数.

If you would like to see a failure if a command is attempted, then use $ExecutionContext.InvokeCommand.ExpandString to expand the $str parameter.

这篇关于扩展文件内容中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆