gpt4 book ai didi

powershell - 结合两次调用Select-Object的结果

转载 作者:行者123 更新时间:2023-12-02 23:22:20 25 4
gpt4 key购买 nike

作为PowerShell脚本的一部分,我想生成两个不同文件夹的子文件夹列表。我通过两次调用Get-ChildItem,使用Select-Object转换路径并尝试合并结果来解决此问题。但是,这是我遇到的合并步骤。我已经试过了:

$cur = Get-Location
$mainDirs = Get-ChildItem -Directory -Name | Select-Object {"$cur\$_"}
$appDirs = Get-ChildItem -Directory -Name Applications\Programs |
Select-Object {"$cur\Applications\Programs\$_"}
$dirs = $mainDirs,$appDirs #Doesn't work!

但是 $dirs最终由 $mainDirs中的条目组成,后跟 $appDirs中的所有空项目。

如何在PowerShell中结合使用它们?

编辑: mainDirs[0]的输出:

“$ cur \ $ _”
---------
D:\ somefolder \ somesubfolder
appDirs[0]的输出:

“$ cur \ Applications \ Programs \ $ _”
-------------------------------
D:\ somefolder \ Applications \ Programs \ other子文件夹

最佳答案

Get-ChildItem接受字符串数组作为输入。只需将要列出其子文件夹的两个文件夹传递为数组即可。展开FullName属性以获取子文件夹的路径:

$folders = '.', '.\Applications\Programs'
$dirs = Get-ChildItem $folders -Directory | Select-Object -Expand FullName

如果要相对路径而不是绝对路径,请从路径字符串的开头删除当前目录:
$pattern = '^{0}\\' -f [regex]::Escape($PWD.Path)
$folders = '.', '.\Applications\Programs'
$dirs = Get-ChildItem $folders -Directory |
ForEach-Object { $_.FullName -replace $pattern }

关于powershell - 结合两次调用Select-Object的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47135845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com