Powershell 替换所有txt文件中的字符

Powershell 替换所有txt文件中的字符,powershell,Powershell,我希望在目录“D:\Aither\Pca\Stat\”中的所有txt文件中将字符“a”替换为“o” 现在我使用这个,但是浪费时间,因为有很多文件 (Get-Content D:\Aither\Pca\Stat\StrEtb.dat).replace('a', 'o') | Set-Content D:\Aither\Pca\Stat\StrEtb.dat (Get-Content D:\Aither\Pca\Stat\StrEtb2.dat).replace('a', 'o') | Set-Co

我希望在目录“D:\Aither\Pca\Stat\”中的所有txt文件中将字符“a”替换为“o”

现在我使用这个,但是浪费时间,因为有很多文件

(Get-Content D:\Aither\Pca\Stat\StrEtb.dat).replace('a', 'o') | Set-Content D:\Aither\Pca\Stat\StrEtb.dat
(Get-Content D:\Aither\Pca\Stat\StrEtb2.dat).replace('a', 'o') | Set-Content D:\Aither\Pca\Stat\StrEtb2.dat
....
我想要这样的东西:

  (Get-Content D:\Aither\Pca\Stat\*).replace('a', 'o') | Set-Content D:\Aither\Pca\Stat\*
在PowerShell中是否可以执行此操作?

尝试以下操作:

$collection = Get-ChildItem -Path 'D:\Aither\Pca\Stat' -Recurse -Filter '*.dat'

foreach( $file in $collection ) {
   (Get-Content $file.FullName).replace('a', 'o') | Set-Content ($file.FullName) | Out-Null
}

使用
-Filter
-File
参数,可以更好地收集文件。此外,您还可以使用
ForEach对象
将这些文件通过管道传送到下一个cmdlet

因为您要覆盖文件,所以需要在
获取内容
周围使用括号,这样您就不会同时尝试读取和写入同一文件

Get-ChildItem -Path 'D:\Aither\Pca\Stat' -Filter '*.dat' -File -Recurse | ForEach-Object {
    ($_ | Get-Content).Replace('a', 'o') | Set-Content $_.FullName
}

Get ChildItem-Path'D:\Aither\Pca\Stat'-Recurse-Filter“*.dat”
。筛选器比其他参数更有效,因为提供程序在cmdlet获取对象时应用它们,而不是在检索对象后让PowerShell对其进行筛选。