我正在尝试查找所有 .aspx
目录及其所有子文件夹中的文件,以便我可以在 <head>
下添加标签标签。父目录可能包含 .aspx
其中的文件以及子文件夹。
换句话说,我希望选择全部 .aspx
该目录中的文件以及所有 .aspx
其子文件夹中的文件,全部 .aspx
这些子项的子项中的文件等。我使用以下 PowerShell 代码片段来执行此操作:
$files = Get-ChildItem -Path C:\Users\apgdy\Downloads\test_proj -recurse -filter "*.aspx"
当我在 PowerShell 控制台中运行它并显示 $files
的内容时,我得到了我期望在屏幕缓冲区中显示的所有文件。但是,当我尝试使用以下代码向文件添加文本时,出现错误:
代码:
$textIsAddedAfter = "<head>"
$textToAdd = " <sometag>"
ForEach ($file in $files) {
(Get-Content $file) |
Foreach-Object {
$_
if($_ -match $textIsAddedAfter) {
$textToAdd
}
} |
Set-Content $file
}
错误:
Get-Content : cannot find path 'C:\users\apgdy\test.aspx' because it does not exist.
At line:2 char:17
+ <Get-Content <<<< $file> |
+ CategoryInfo : ObjectNotFound: <C:\Users\apgdy\test2.aspx:String
> [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetCo
ntentCommand
对于在 $files
中找到的每个文件,我都会得到其中一个
奇怪的是,在代码中,我告诉控制台这些文件存在于 "C:\users\apgdy\Downloads\test_proj"
中。及其子项,而不是 "C:\users\apgdy"
。为什么省略了"\Downloads\test_proj"
从我告诉它的目录中查找文件?
提前致谢!
最佳答案
当您调用Get-Content
时,它没有使用完整的文件路径。更改自:
Get-Content $file
致:
Get-Content $file.FullName
或者:
$file | Get-Content
关于PowerShell - 使用 -Recurse 和 -Filter 附加到目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511378/