Powershell-使用Get-ChildItem和读取主机搜索带有扩展名的文件

问题描述 投票:0回答:1

非常简单的代码,我正在尝试使用读取主机搜索某些具有特定扩展名的文件。然后,我尝试将其传递给get-childitem行,以便搜索所述扩展名,但它无法正常工作。

 $SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

 $TargetedLocation = Read-Host "Which location are the files located?"

 Get-ChildItem -Path $TargetedLocation -Include $SelectedFiles -Recurse
powershell powershell-2.0 powershell-3.0 powershell-4.0
1个回答
0
投票

我运行了此代码:

$SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

$TargetedLocation = Read-Host "Which location are the files located?"

Get-ChildItem -Path $TargetedLocation -Include $SelectedFiles -Recurse

对提示提供以下响应:

您希望删除哪种文件?:txt

文件位于哪个位置?:C:\ temp

此未返回任何输出。但是,如果我以*.txt重复,作为第一个响应,那么我确实会获得C:\temp内的所有txt文件。如果您希望最终用户指定扩展名而不将*.放在前面,则可以执行以下操作:

$SelectedFiles = Read-Host "Which type of file(s) do you wish to delete?"

$TargetedLocation = Read-Host "Which location are the files located?"

Get-ChildItem -Path $TargetedLocation -Include "*.$SelectedFiles" -Recurse

这将对问题1的回答开头添加*.

关于将Get-ChildItem-Include一起使用还有更多上下文:Difference between -include and -filter in get-childitem

© www.soinside.com 2019 - 2024. All rights reserved.