Is it possible to write self-modifying PowerShell scripts?
Suppose I have a script named foo.ps1
:
"Write-Host `"Goodbye world`"" | Set-Content "foo.ps1"
Write-Host "Hello world"
This script prints out Hello world
. What techniques could I use to get it to print out Goodbye world
?
To me it does not make sense, after you have modified a script, you need to re-dotsource it in order to get new statments.
This script changes itself three times:
Write-Host "Hello world" "Write-Host `"Goodbye world`"" | Set-Content "foo.ps1" . .\foo.ps1 "Write-Host `"Is really useful?`"" | Set-Content "foo.ps1" . .\foo.ps1
and prints:
Hello World Goodbye World Is really useful?
Another possibility is to write a script which accepts as input parameters script blocks.