powershell - Powershell-错误检查以查找和替换(ForEach对象)

标签 powershell error-handling pipeline error-checking

我需要在ForEach-Object部分上添加错误检查。

当前,此代码可替换文件中的值。但是,如果找不到该值,则似乎不会产生任何错误。我已经试过了,但是没用。我已经搜寻了几个小时,并尝试了各种东西...有什么帮助吗?

我可以通过两种不同的方式执行命令,不确定在哪种情况下添加错误检查更好或更容易...

(Get-Content $file) | ForEach-Object { $_ -replace $replace, $with } | Set-Content $file

-要么-
ForEach-Object { (Get-Content $file) -replace $replace, $with } | Set-Content $file

谢谢。

最佳答案

找不出要替换的东西不是错误,它只会返回原始内容。因此,请在if语句中进行检查,例如:

foreach { $rep=$_ -replace $replace,$width; if ($_ -eq $rep) {...} } 

关于powershell - Powershell-错误检查以查找和替换(ForEach对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19012682/

相关文章:

configuration - Powershell:如何使用不同的用户名/密码映射网络驱动器

json - Powershell 2.0格式列表输出到JSON吗?

rust - 匹配和解包之间的不同行为

shell - 管道是否保证在任何 POSIX shell 中创建子 shell?

python - TransformedTargetRegressor 保存和加载错误

python - "Piping"使用 Python 中缀语法从一个函数输出到另一个函数

powershell - 使用 PowerShell Write-Output 创建后损坏的 Cmd 脚本

powershell - 将 Powershell 脚本和文件包装在一起?

error-handling - selenium webdriver - 报告生成,截屏并保存到桌面上的文件夹

python - 忽略错误消息以继续 python 中的循环