How to properly set a variable from PowerShell in Windows batch file?

后端 未结 3 370
夕颜
夕颜 2021-01-16 14:15

For someone unknown reasons, I am unable to retrieve this variable on Windows batch file.

PowerShell:

$datePattern = [Regex]::new(\'value=(\\S+)\')
$         


        
3条回答
  •  有刺的猬
    2021-01-16 15:00

    Provided the file tmpfile IS a single line file and doesn't exceed max cmd line length.

    Batch

    :: Q:\Test\2018\12\30\SO_53977221_.cmd
    @Echo off
    set /P "string="

    >  SO_53977221_.cmd
    newvalue=12.2
    

    This uses string substitution (with a wildcard) and substring to get the desried value.

    A combined batch/powershell solution is also possible but requires a bit more effort with escaping and quoting than your try.

    This PowerShell one liner will output

    PoSh> if((Get-Content .\tmpfile) -match 'value=(\d\d\.\d)'){$Matches[1]}
    12.2
    

    Properly wrapped in batch

    :: Q:\Test\2018\12\30\SO_53977221.cmd
    @Echo off
    for /f "usebackq" %%A in (`
        powershell -NoP -C "if((Get-Content .\tmpfile) -match 'value=(\d\d\.\d)'){$Matches[1]}"
    `) Do set "newvalue=%%A"
    set newvalue
    

    Sample output:

    > .\SO_53977221.cmd
    newvalue=12.2
    

提交回复
热议问题