遍历文件夹中具有不同文件扩展名的所有文件

Loop through all files in folder with different file extensions

我正在尝试遍历文件夹中的所有文件,无论类型如何,并将字符串更改为用户输入的字符串。

我现在可以用下面的代码做到这一点,但只能使用一种类型的文件扩展名..

这是我的代码:

$NewString = Read-Host -Prompt 'Input New Name Please'
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

$InputFiles = Get-Item "$scriptPath\*.md"

$OldString  = 'SolutionName'
$InputFiles | ForEach {
(Get-Content -Path $_.FullName).Replace($OldString,$NewString) | Set-Content -Path $_.FullName
}

echo 'Complete'

无论扩展名如何,我如何遍历文件? 所以无论是md、txt、cshtml还是其他什么的,它都会按照指示替换字符串。

要获取一个文件夹中的所有文件,您可以使用 Get-ChildItem。添加 -Recurse 开关以包含子文件夹中的文件。

例如你可以像这样重写你的脚本

$path = 'c:\tmp\test'
$NewString = Read-Host -Prompt 'Input New Name Please'
$OldString  = 'SolutionName'

Get-ChildItem -Path $path  | where {!$_.PsIsContainer} | foreach { (Get-Content $_).Replace($OldString,$NewString) | Set-Content -Path $_.FullName }

这将首先从 $path 中定义的文件夹中获取所有文件,然后将 $OldString 中给出的值替换为用户在提示时输入的值,最后保存文件。

注意:脚本对文件内容是否更改没有任何影响。这将导致所有文件的修改日期得到更新。如果此信息对您很重要,那么您需要在更改和保存文件之前添加检查以查看文件是否包含 $OldString