更新时间:2022-11-02 23:01:35
Get-Content "C:\Dir\*"
会给你 C:\Dir 中所有内容的内容
一次性完成,因此您将无法单独修改每个文件.C:\Dir
中的任何目录也会出错.
Get-Content "C:\Dir\*"
will give you the content of everything in C:\Dir
in one go, so you won't be able to modify each file individually. You'll also get errors for any directory in C:\Dir
.
您需要遍历目录中的每个文件并单独处理它们:
You need to iterate over each file in the directory and process them individually:
Get-ChildItem 'C:\Dir' -File | ForEach-Object {
$file = $_.FullName
(Get-Content $file) -replace '1','2' | Set-Content $file
}
Get-Content
周围的括号确保在进一步处理之前读取并再次关闭文件,否则写入(仍然打开)文件将失败.
The parentheses around Get-Content
ensure that the file is read and closed again before further processing, otherwise writing to the (still open) file would fail.
请注意,参数 -File
仅在 PowerShell v3 或更高版本中受支持.在旧版本中,您需要将 Get-ChildItem -File
替换为以下内容:
Note that the parameter -File
is only supported in PowerShell v3 or newer. On older versions you need to replace Get-ChildItem -File
with something like this:
Get-ChildItem 'C:\Dir' | Where-Object { -not $_.PSIsContainer } | ...