【问题标题】:How to call a powershell regex command from a batch script如何从批处理脚本调用 powershell 正则表达式命令
【发布时间】:2019-01-06 15:37:30
【问题描述】:

我在批处理脚本中有一个字符串。我不想创建 Powershell 脚本或其他文件。

我想知道的是,如何在通过批处理传递给 powershell 的字符串上获取正则表达式替换。

我的解决方法::

 powershell -Command " replace "%insert regex pattern%" , "%string_from_batch_file%"

我希望 this%string_from_batch_file% 被正则表达式匹配替换。同样,我不处理此命令之外的文件或 powershell,我只需要对字符串进行正则表达式替换。

提前致谢

【问题讨论】:

  • 你到底想在哪里替换什么?替换操作总是由三个因素组成:源字符串、匹配模式和替换字符串。
  • @AnsgarWiechers 我不是要斜体括号,我是新手,因此不要介意这种模式,我无法正确使用 ps 语法,因为我以前从未使用过 Powershell
  • 这并没有说明什么。请提供输入和预期输出的示例。
  • edit您的问题。不要将您问题的相关信息隐藏在 cmets 中。
  • @phoenyx 我的问题中究竟缺少什么? 例如您之前评论中的输入、输出和正则表达式信息。

标签: regex powershell batch-file


【解决方案1】:

您可以像这样在命令行上替换调用 powershell 的字符串

PowerShell -Command "& {'yourstring' -replace 'your', 'my'}"

甚至更短的 cudo 到 mklement

PowerShell -Command "'yourstring' -replace 'your', 'my'"

【讨论】:

  • @mklement0,可能是因为它“应该”是correct syntax
  • @Compo:确实,在撰写本文时,文档可能会让人们相信这种用法始终是必要的,但事实并非如此。一个revision is pending,有望很快出现在网上(离线帮助必须更新为Update-Help)。
【解决方案2】:

以你的评论为例:

@Echo off
set "input=abced__xyz.ghi23"
set "regex=_[^]+$"
Echo expected output: [xyz.ghi23]
powershell -Command " replace "%insert regex pattern%" , "%string_from_batch_file%"

这不起作用,因为您使用了错误的语法。
内部双引号也必须转义,因此 cmd 让我们将它们传递给 powershell
(或改为单引号)。

我看到(至少)两个正确的正则表达式来解决这个问题

  1. 使用 RE 匹配部件以删除 '^.*?_+' 并替换为空 ''
    (可以省略,因为它是隐含的)
  2. 使用捕获组来匹配要保留的部分并用它替换输入。

:: Q:\Test\2018\07\30\SO_51593067.cmd
@Echo off
set "input=abced__xyz.ghi23"
Echo expected output: [xyz.ghi23]
Echo 1st
powershell -NoP -C "'%input%' -replace '^.*?_+'"
Echo 2nd
powershell -NoP -C "'%input%' -replace '^.*?_+(.*)$','$1'"

样本输出:

> Q:\Test\2018\07\30\SO_51593067.cmd
expected output: [xyz.ghi23]
1st
xyz.ghi23
2nd
xyz.ghi23

如果您想进一步处理批处理文件中的 powershell 输出,
您必须使用 for /f 解析 powershell 命令并存储在批处理变量中:

:: Q:\Test\2018\07\30\SO_51593067.cmd
@Echo off
set "input=abced__xyz.ghi23"
Echo expected output: [xyz.ghi23]

for /f "usebackq delims=" %%A in (`
  powershell -NoP -C "'%input%' -replace '^.*?_+'"
`) Do Set "first=%%A"

for /f "usebackq delims=" %%A in (`
  powershell -NoP -C "'%input%' -replace '^.*?_+(.*)$','$1'"
`) Do Set "second=%%A"

Echo first =%first%
Echo second=%second%

样本输出:

> Q:\Test\2018\07\30\SO_51593067.cmd
expected output: [xyz.ghi23]
first =xyz.ghi23
second=xyz.ghi23

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多