Расширение переменных в содержании файла

По-моему, необходимо всегда использовать автосвойства вместо общедоступных полей. Однако вот компромисс:

Начинаются с внутренний поле с помощью соглашения о присвоении имен, которое Вы использовали бы для свойства. Когда Вы сначала или

  • доступ потребности к полю снаружи его блока, или
  • потребность присоединить логику к методу get/методу set

Делают это:

  1. переименовывают поле
  2. , делают, оно частный
  3. добавляет общественную собственность

, Ваш клиентский код не должен будет изменяться.

Когда-нибудь, тем не менее, Ваша система вырастет, и Вы разложите ее на отдельные блоки и несколько решений. Когда это произойдет, любые представленные поля заставят Вас пожалеть, потому что, как Jeff упомянул, , изменение общедоступного поля к общественной собственности является повреждающимся изменением API .

29
задан Matt 17 September 2015 в 14:12
поделиться

2 ответа

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

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

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

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

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

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

32
ответ дан 28 November 2019 в 01:54
поделиться

Я нашел это решение:

$something = "World"
$template = Get-Content template.txt
$expanded = Invoke-Expression "`"$template`""
$expanded
5
ответ дан 28 November 2019 в 01:54
поделиться
Другие вопросы по тегам:

Похожие вопросы: