How can I source variables from a .bat file into a PowerShell script?

后端 未结 5 1456
春和景丽
春和景丽 2020-12-10 02:25

I\'m replacing parts of a .bat script with PowerShell. Configuration for the batch files is done via files that set appropriate environment variables. I\'m look

5条回答
  •  余生分开走
    2020-12-10 03:07

    The preferred option would be to change the configuration to a .ps1 file and change the variable definitions to PowerShell syntax:

    $VAR_ONE = 'some_value'
    $VAR_TWO = '/other-value'
    

    Then you'll be able to dot-source the file:

    . filename.ps1
    

    If you want to stick with the format you currently have, you'll have to parse the values, e.g. like this:

    Select-String '^set ([^=]*)=(.*)' .\filename.bat | ForEach-Object {
        Set-Variable $_.Matches.Groups[1].Value $_.Matches.Groups[2].Value
    }
    

    Note: The above won't work in PowerShell versions prior to v3. A v2-compatible version would look like this:

    Select-String '^set ([^=]*)=(.*)' .\filename.bat | ForEach-Object {
        $_.Matches
    } | ForEach-Object {
        Set-Variable $_.Groups[1].Value $_.Groups[2].Value
    }
    

提交回复
热议问题