gpt4 book ai didi

powershell - 基本 PowerShell 脚本问题 : "Expressions are only allowed as the first element of a pipeline"

转载 作者:行者123 更新时间:2023-12-02 11:26:29 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的脚本,该脚本读取文件,找到字符串,用另一个字符串替换该字符串,并将所有新文件内容(带有替换的字符串)存储在新文件中。这是我正在使用的:

(Get-Content C:\file1.txt) | {$_ -replace "this:text", "withthis:text"} | Set-Content C:\file2.txt

我收到的错误是:“表达式仅允许作为管道的第一个元素”

我很确定这是因为冒号“:”字符同时出现在我正在查找和替换的字符串中。我尝试使用“\”和“`”字符转义冒号字符,但收到了相同的错误。有谁知道这是怎么回事吗?

感谢您的帮助。

最佳答案

问题出在管道中的第二个元素。

{$_ -replace "this:text", "withthis:text"}

这是一个脚本 block (即一段代码)。如果要将脚本 block 应用于管道上的所有传入项目,您可以使用 foreach-object cmdlet,如下所示:

(Get-Content C:\file1.txt) | foreach-object {$_ -replace "this:text", "withthis:text"} | Set-Content C:\file2.txt

@shagun 使用 foreach-object cmdlet 的 % 别名,因此代码看起来也正确。

关于powershell - 基本 PowerShell 脚本问题 : "Expressions are only allowed as the first element of a pipeline",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25078049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com