如何从Windows批处理文件中的PowerShell正确设置变量? [英] How to properly set a variable from PowerShell in Windows batch file?

查看:67
本文介绍了如何从Windows批处理文件中的PowerShell正确设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些未知原因,我无法在Windows批处理文件中检索此变量.

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

PowerShell:

PowerShell:

$datePattern = [Regex]::new('value=(\S+)')
$datePattern = [Regex]::new('(\d\d\.\d)')
$matches = $datePattern.Matches("/ start=2010 / height=1 / value=12.2 / length=0.60 / users=264 / best=Adam /")
$matches.Value

它工作得很好.但是,这在批处理文件上失败了.

It works perfectly fine. However, this fails miserably on batch file.

for /f %%i in ("PowerShell -NoProfile -ExecutionPolicy Bypass -Command $datePattern = [Regex]::new(value=(\S+)); $datePattern = [Regex]::new((\d\d\.\d)); $matches = $datePattern.Matches(tmpFile); $matches.Value") do ( set newValue=%%i )

目标是使%newValue% value = 返回 12.2 .如果可以直接在批处理文件上完成操作,那就更好了.这些值因文件而异.

The goal is to be able to have %newValue% return 12.2 from value=. If it can be done directly on batch file, then that's even better. The values differentiate from file to file.

推荐答案

为文件 tmpfile IS 提供了单个行文件,并且不超过最大cmd行长度.

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

批次

:: Q:\Test\2018\12\30\SO_53977221_.cmd
@Echo off
set /P "string="<tmpfile
set "string=%string:*value=%"
set "newvalue=%string:~1,4%"
set newvalue


>  SO_53977221_.cmd
newvalue=12.2

这使用字符串替换(带有通配符)和子字符串来获得所要查询的值.

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

也可以使用批处理/powershell组合解决方案,但是转义和引用比尝试花费更多的精力.

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

此PowerShell一个衬板将输出

This PowerShell one liner will output

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

正确分批包装

:: 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

示例输出:

> .\SO_53977221.cmd
newvalue=12.2

这篇关于如何从Windows批处理文件中的PowerShell正确设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆