【问题标题】:Running a powershell command inside cmd script and replacing string content在 cmd 脚本中运行 powershell 命令并替换字符串内容
【发布时间】:2015-06-09 14:10:47
【问题描述】:

我正在尝试在 cmd 脚本中运行一个 powershell 命令来替换文本文件内容

set file="C:\myfile.txt"

powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace "Latest", "FOO" } | Set-Content %file%"

我收到以下错误:

您必须在右侧提供一个值表达式 '-replace' 运算符。

我做错了什么?

谢谢

编辑(不确定是否与答案相关...)

文件内容是

\\10.10.10.10\Shared\Latest

【问题讨论】:

    标签: powershell cmd


    【解决方案1】:

    你没有正确嵌套字符串

    powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace "Latest", "FOO" } | Set-Content %file%"
                        ^----------------------------------------------------^
                   string start                                        string end
    

    使用单引号:

    powershell -command "(Get-Content %file%) | ForEach-Object { $_ -replace 'Latest', 'FOO' } | Set-Content %file%"
    

    【讨论】:

    • @AnsgarWiechers 它似乎像 %file% 一样工作 - 我猜命令提示符会在调用 powershell.exe 之前进行替换。
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2017-03-06
    • 2014-09-16
    • 2018-05-10
    • 2021-10-05
    相关资源
    最近更新 更多