开发者

PowerShell Set-Item oddity when using values from the $matches array

开发者 https://www.devze.com 2023-03-21 05:13 出处:网络
I\'m working on some functions to set the environment variables for Visual Studio within PowerShell and went down the path of executing the vcvarsXXX.bat batch file and then parsing the output of set

I'm working on some functions to set the environment variables for Visual Studio within PowerShell and went down the path of executing the vcvarsXXX.bat batch file and then parsing the output of set and look for name=value, then use Set-Item to set those environment variables on the PS side.

The function that does开发者_C百科 this looks like:

#   from Bruce Payette's book to set the environment variables, slightly modified
function Get-Batchfile ($file) {
    $cmd = "`"$file`" & set"
    cmd /c $cmd | Foreach-Object {
        #   variation from Payette's book, use a regex in case the batch file writes some output, only take name=value
        if ($_ -match "^(.*?)=(.*)$") {
            #   make sure they look good
            write-host $matches[1] "=" $matches[2]
            $name=$matches[1]
            $value=$matches[2]
            write-host ">>> $name = $value"
            Set-Item -path env:$name -value $value
            #   for some reason the set item below does not seem to work even though the values of $matches look good
            #Set-Item -path env:$matches[1] -value $matches[2]
        }
    }
}

The problem I noticed is that after the regex matches, if I invoke:

Set-Item -path env:$matches[1] -value $matches[2]

but if I assign the $matches to $name and $value and then invoke:

Set-Item -path env:$name -value $value

It works as expected.

I have 'worked around' this but I would like to understand why the first from does not seem to work. I'd rather keep the code more compact and not have to create the two temporary variables.


I believe it's the same situation as if you'd used those hashtable references in a string. If it's a property of an object you have to use a subexpression - $($variable.property). If you assign $variable.property to a variable, the you can use that variable without using a subexpression. It works the same for hash table entries and array slices.

See if this doesn't work better:

Set-Item -path env:$($matches[1]) -value $($matches[2])
0

精彩评论

暂无评论...
验证码 换一张
取 消