【问题标题】:Powershell - Searching for files with extension using Get-ChildItem and Read-hostPowershell - 使用 Get-ChildItem 和 Read-host 搜索具有扩展名的文件
【发布时间】:2019-11-27 09:42:25
【问题描述】:

非常简单的代码,我正在尝试使用读取主机搜索一些具有特定扩展名的文件。然后我尝试将其传递给 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】:

我运行了这段代码:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2017-02-23
    • 2017-12-16
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多