【问题标题】:Replace Output of Tree Command with Spaces and Tabs用空格和制表符替换树命令的输出
【发布时间】:2021-12-14 04:39:12
【问题描述】:

所以我正在尝试解决一个问题,但我不知道这是否是解决问题的方法。

基本上我的文件夹结构如下:

\---folder
    \---subfolder1
        +---subsub1
        |   +---subsubsub1
        \---subsub2
            \---subsubsub2

我希望它在 excel 中看起来像这样: link to excel screenshot

我知道 Powershell 或命令提示符中的 tree 命令会提供上述文本输出,这就是我得到它的方式。我现在正在尝试格式化命令的输出,使其包含空格和制表符,而不是它所具有的 +、's、|'s 和 -'s。然后我可以将其导入到 excel 中以获取我在该屏幕截图中寻找的输出

在我的 PS 脚本中,我目前可以将 - 替换为空格,但 +、\ 和 |符号变成了不容易被替换的特殊字符。

我想要完成的事情可能可以通过更简单的方式来完成,如果是这样,我愿意接受想法,但这是我一直在尝试解决的方法。

这是我目前所拥有的 Powershell 代码:

$filename = "test.txt"
tree /a > $filename
get-content $filename | %{$_ -replace "-"," "} 
get-content $filename | %{$_ -replace [RegEx]::Escape('< SharedPassKey=123456789abcdefghi/JKLM+nopqrst= />'),'< SharedPassKey=123456789abcdefghi/JKLM.nopqrst= />'}

到目前为止我遇到的一些事情:

【问题讨论】:

  • 在 Excel 中,用空格和制表符替换不会得到不同单元格上的元素。
  • 你可以试试tree /a | % {$_ -ireplace '[\\+| ][ -]{3}', "``t"} | out-file $env:USERPROFILE\desktop\test.csv (替换部分应该只有1个`,但是markdown给我带来了问题)

标签: windows powershell replace special-characters


【解决方案1】:

在我的评论中,当使用Export-CsvExport-Excel 时,列由对象属性定义。如果您用 tabulations 替换前导 空格、斜杠、管道等,则导出到 CSV 或 Excel 后的最终结果看起来不像您添加到的电子表格您的问题,导出将是一个 one 列文件,每个单元格都有不同的填充(取决于文件的嵌套)。

在我看来,即使需要更多代码,也应该使用递归而不是 regex 替换。我将在此示例中使用我的 /etc/ 文件夹。

  • 所以,一步一步,定义一个递归函数首先扫描目录:
function Get-FolderRecursive {
[cmdletbinding()]
param(
    [string]$Path,
    [int]$Nesting = 0,
    [switch]$Force
)
    
    $outObject = {
        param($Nesting, $folder)
        
        [pscustomobject]@{
            Nesting   = $Nesting
            Hierarchy = $folder.Name
        }
    }
    
    if(-not $Nesting)
    {
        $parent = Get-Item -LiteralPath $Path
        & $outObject -Nesting $Nesting -Folder $parent
    }

    $Nesting++

    $folders = if($Force.IsPresent)
    {
        Get-ChildItem -LiteralPath $Path -Directory -Force
    }
    else
    {
        Get-ChildItem -LiteralPath $Path -Directory
    }

    foreach($folder in $folders)
    {
        & $outObject -Nesting $Nesting -Folder $folder
        
        $PSBoundParameters.Path = $folder.FullName
        $PSBoundParameters.Nesting = $Nesting
        Get-FolderRecursive @PSBoundParameters
    }
}
  • 定义函数后,我们可以将结果存储在变量中:
PS /etc> $result = Get-FolderRecursive . -ErrorAction SilentlyContinue

这些是生成的object[] 的外观的几行代码:

PS /etc> $result | Select-Object -First 10

Nesting Hierarchy
------- ---------
      0 etc
      1 acpi
      2 events
      1 alternatives
      1 apache2
      2 conf-available
      2 mods-available
      1 apm
      2 event.d
      2 resume.d
  • 现在我们将文件夹层次结构存储在一个变量中,我们可以操纵这个object[] 以获得所需的输出,它与Export-CsvExport-Excel 兼容:
$maxNesting = ($result.Nesting | Measure-Object -Maximum).Maximum

$output = foreach($item in $result)
{
    $out = [ordered]@{}
    foreach($z in 0..$maxNesting)
    {
        $out["Column $z"] = ''
    }
    $out["Column $($item.Nesting)"] = $item.Hierarchy
    [pscustomobject]$out
}
  • 如果我们检查$output 的前几行,它是这样的:
PS /etc> $output | Format-Table -AutoSize
                          
Column 0 Column 1                   Column 2               Column 3                      Column 4
-------- --------                   --------               --------                      --------
etc                                                                                      
         acpi                                                                            
                                    events                                               
         alternatives                                                                    
         apache2                                                                         
                                    conf-available                                       
                                    mods-available                                       
         apm                                                                             
                                    event.d                                              
                                    resume.d                                             
                                    scripts.d                                            
                                    suspend.d                                            
         apparmor                                                                        
                                    init                                                 
                                                           network-interface-security    
         apparmor.d                                                                     

如果您有兴趣,我创建了一个使用此功能的修改版本的模块。除了文件夹大小之外,它还产生与tree 相同的输出:PSTree

【讨论】:

  • 这太棒了!!非常感谢圣地亚哥。是否可以在最后一个输出中创建固定宽度的列?
  • @bsquared 没问题,是的,有可能,请参阅this answer,但请注意,此代码并非要显示在控制台上(列越多,您看到的越少)。它主要用于导出到 CSV。如果答案有帮助,请考虑接受。
  • 是的,它奏效了。非常感谢!将标记为已解决:为之前从未将函数加载到 powershell 的任何人放置此:[link[(stackoverflow.com/questions/18764312/…)
猜你喜欢
  • 2019-05-05
  • 2020-03-11
  • 2020-11-24
  • 1970-01-01
  • 2013-08-10
  • 2014-05-02
  • 1970-01-01
  • 2021-05-23
相关资源
最近更新 更多