your programing

파일 내용에서 변수 확장

lovepro 2023. 8. 30. 23:54
반응형

파일 내용에서 변수 확장

파일이 있습니다.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

실수로 코드를 실행할 가능성이 없는 "안전한" 문자열 평가를 원하는 경우 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를 사용합니다.명령을 호출합니다.String을 확장하여 $str 매개 변수를 확장합니다.

이 솔루션을 찾았습니다.

$something = "World"
$template = Get-Content template.txt
$expanded = Invoke-Expression "`"$template`""
$expanded

PS가 변수를 평가하고 템플릿에 포함된 모든 명령을 실행한다는 것을 기억하면서, 저는 이것을 하는 다른 방법을 찾았습니다.

템플릿 파일의 변수 대신 토큰을 직접 구성합니다. HTML을 처리하지 않을 경우 예를 들어 사용할 수 있습니다.<variable>이와 같이:

Hello <something>

기본적으로 고유한 토큰을 사용합니다.

그런 다음 PS 스크립트에서 다음을 사용합니다.

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

스트레이트업된 InvokeCommand보다 번거롭지만 단순 템플릿을 처리할 때 보안 위험을 피하기 위해 제한된 실행 환경을 설정하는 것보다 더 명확합니다.요구사항에 따른 YMMV :-)

언급URL : https://stackoverflow.com/questions/1667023/expanding-variables-in-file-contents

반응형