Windows 搜索文件并将路径存储在变量中
我试图在目录树中搜索2个文件并删除它们。我想保留已删除文件的路径 到目前为止,这就是我所拥有的:Windows 搜索文件并将路径存储在变量中,windows,shell,powershell,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 $
#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}
编辑:
我忘了提到我要删除文件的每个实例。我会将
Get-ChildItem
cmdlet的结果存储到一个变量,比如$filesToDelete
。然后,您可以通过简单的管道将对象传递到Remove Item
cmdlet(您不需要foreach
):
我想删除文件的每个实例,这就是我使用foreach的原因。(编辑了问题)这也会删除文件的每个实例。好的,我明白了,所以我是否必须使用两个变量,例如$filesToDelete和$filesToDelete2和$file2来删除文件?因为这些文件在每个文件夹中都放在一起。
$filesToDelete
将包含与您的包含条件匹配的所有文件,而不考虑目录。所以如果你有两个文件e。G/tmp中的abc1.cs和/tmp2中的abc1.cs都将存储在变量中。如果通过管道将对象发送到Remove-Item cmdlet,则这两个对象都将被删除。这样,您就可以在某处获取内容。Get ChildItem仅返回项(而不是内容)。
$filesToDelete = Get-Childitem $path -include $file -recurse
$filesToDelete | Remove-Item