Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Substitution inside a PowerShell Scriptblock run as Administrator

Tags:

powershell

I'm writing code in PowerShell. I want to change the port in a configuration file as administrator, but it doesn't work.

Here's my code:

$port=8888

$ScriptBlock = {
    function bar($port) {
        $config = Get-Content -Path "c:\Users\Me\foo.xml"
        $NewConfig = $Config -replace 'httpPort=[0-9]*\s',"httpPort=$port "
        Set-Content -Path c:\ProgramFiles(x86)\foo.xml -Value $NewConfig -Force
    }
};
Start-Process -FilePath powershell.exe -ArgumentList $ScriptBlock,"bar('$port')" -Verb RunAs -Wait

I think its having trouble with the second part of the -replace ("httpPort=$port ").

What am I missing?

like image 762
DumbNewbie Avatar asked May 15 '26 23:05

DumbNewbie


1 Answers

You can try the following:

Start-Process -Verb RunAs -Wait -FilePath powershell.exe -ArgumentList '-Command',
  "$($ScriptBlock -replace '"', '\"'); bar $port"

As an aside:
* The regex you're using to match the port number suggests that it is an unquoted attribute value, which, while acceptable in HTML, is not well-formed XML.
* Don't invoke your function with method syntax (bar($port)) - PowerShell functions are called like shell commands, without parentheses and with arguments separated by whitespace rather than ,: bar $port

As for what you tried:

  • Start-Process invariably interprets the arguments passed to -ArgumentList as strings, and while a script block conveniently stringifies to its literal string content, you need to escape the embedded " chars. as \" (sic) in order for the target PowerShell instance to recognize them properly with the (implied in Windows PowerShell) -Command option.

  • Since -Command simply concatenates all subsequent arguments with a space as the separator before interpreting the resulting string as a piece of PowerShell source code, it is generally preferable to pass a single string, for conceptual clarity.

like image 181
mklement0 Avatar answered May 18 '26 16:05

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!