使用 Get-ChildItem 过滤文件夹名称。

huangapple go评论60阅读模式
英文:

Filtering folder names with Get-ChildItem

问题

以下是您要翻译的部分:

我已经编写了一个非常简单的脚本来获取如下所示的文件夹列表。我的问题是:我想导出一个像我期望的输出那样的输出。

这里有没有人有任何可以帮助我的信息?

我的脚本:

Get-ChildItem -Path "D:\GENERAL" -Recurse -Directory -Depth 5 |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

我的输出:

"FullName"
"D:\GENERAL\IT"
"D:\GENERAL\SOFTWARE"

我期望的输出:

"FullName"
"D:\GENERAL"
"D:\GENERAL\IT"
"D:\GENERAL\SOFTWARE"
英文:

I have written a very simple script to grab a list of folders like below. My question is : I want to export an output like my desired output.

Does anyone here have any information that would help me out?

My script :

Get-ChildItem -Path "D:\GENERAL" -Recurse -Directory -Depth 5 |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

My output :

"FullName"
"D:\GENERAL\IT"
"D:\GENERAL\SOFTWARE"

My desired output :

"FullName"
"D:\GENERAL"
"D:\GENERAL\IT"
"D:\GENERAL\SOFTWARE"

答案1

得分: 1

要在输出中包括根文件夹,请在 Get-Item 后添加一个 (非递归) 调用。将这两个命令都包裹在一个脚本块 {…} 中,这样你就能够统一处理它们的输出。脚本块是使用调用运算符 & 来调用的。它可以被视为一个单一的命令,这使我们能够将其输出管道传递到其他命令。

$path = "D:\GENERAL"
& {
    Get-Item -Path $path
    Get-ChildItem -Path $path -Recurse -Directory -Depth 5
} |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

另一种避免使用 $path 变量的方式:

"D:\GENERAL" | ForEach-Object {
    Get-Item -Path $_
    Get-ChildItem -Path $_ -Recurse -Directory -Depth 5
} |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

在这里,我们将路径作为输入传递给 ForEach-Object,它在 ForEach-Objectprocess 脚本块中作为 $_,即当前管道对象,可用。

英文:

To include the root folder in the output, add a (non-recursive) call to Get-Item. Wrap both commands in a scriptblock {…}, so you are able to process their output uniformly. The scriptblock is called using the call operator &. It can be treated like a single command, which enables us to pipe its output to other commands.

$path = "D:\GENERAL"
& {
    Get-Item -Path $path
    Get-ChildItem -Path $path -Recurse -Directory -Depth 5
} |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

An alternative way that avoids the $path variable:

"D:\GENERAL" | ForEach-Object {
    Get-Item -Path $_
    Get-ChildItem -Path $_ -Recurse -Directory -Depth 5
} |
    Select-Object FullName |
    Export-Csv c:\tmp\out.csv -NoTypeInformation -Encoding UTF8

Here we are piping the path as input to ForEach-Object which becomes available as $_, the current pipeline object, within ForEach-Object's process script block.

huangapple
  • 本文由 发表于 2023年6月8日 14:55:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429301.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定