所以有一個我正在嘗試解決的問題,我不知道這是否是解決問題的方法。
基本上我有一個檔案夾結構,看起來像:
\---folder
\---subfolder1
---subsub1
| ---subsubsub1
\---subsub2
\---subsubsub2
我希望它在 excel 中看起來像這樣: link to excel screenshot
我知道treePowershell 或命令提示符中的命令給出了上面的文本輸出,這就是我得到它的方式。我現在正在嘗試格式化命令的輸出,以便它包含空格和制表符,而不是它具有的 、'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= />'}
到目前為止我遇到的一些事情:
- 無法通過 PowerShell 在文本檔案中使用加號“ ”編輯/替換字串值
- https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference
uj5u.com熱心網友回復:
正如在我的評論中一樣,列在使用Export-Csv或時由物件屬性定義Export-Excel。如果您要用表格替換前導空格、斜杠、管道等,匯出到 CSV 或 Excel 后的最終結果將與您添加到問題中的電子表格不同,匯出將是一個單列檔案和每個單元格會有不同的填充(取決于檔案的嵌套)。
在我看來,即使需要更多的代碼,也是為此使用遞回而不是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-Csv和兼容Export-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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/381815.html
