搜索文件并将路径存储在变量中

时间:2017-05-02 14:20:59

标签: windows shell powershell

我正在尝试在目录树中搜索2个文件并删除它们。我想保持已删除文件的路径。

到目前为止,我所拥有的是:

#set the path to search for the file
$path = ".\"

#File name
$file = "GeneratedCode.cs"
$file2 = "TypedEnums.cs"

#Look for the file and delete every instance of it in all directories.
Get-Childitem $path -include $file -recurse | foreach ($_) {remove-item $_.fullname}



#Look for the file and delete every instance of it in all directories.

Get-Childitem $path -include $file2 -recurse | foreach ($_) {remove-item $_.fullname}

编辑: 我忘了提到我想要删除文件的每个实例。

1 个答案:

答案 0 :(得分:2)

我会将Get-ChildItem cmdlet的结果存储到变量中,让我们说$filesToDelete。然后,您可以简单地将对象传递到Remove-Item cmdlet(您不需要foreach):

$filesToDelete = Get-Childitem $path -include $file -recurse
$filesToDelete | Remove-Item