2013-03-01 121 views
4

我一直試圖找到一個腳本,遞歸打印這樣的目錄中的反斜槓用於指示目錄中的所有文件和文件夾:PowerShell腳本列出目錄中的所有文件和文件夾

Source code\ 
Source code\Base\ 
Source code\Base\main.c 
Source code\Base\print.c 
List.txt 

我使用的PowerShell 3.0和我發現的大多數其他腳本不起作用(雖然他們沒有像我問的東西)。

此外:我需要它是遞歸的。

回答

4

這可能是這樣的:

$path = "c:\Source code" 
DIR $path -Recurse | % { 
    $_.fullname -replace [regex]::escape($path), (split-path $path -leaf) 
} 

繼@Goyuix想法:

$path = "c:\source code" 
DIR $path -Recurse | % { 
    $d = "\" 
    $o = $_.fullname -replace [regex]::escape($path), (split-path $path -leaf) 
    if (-not $_.psiscontainer) { 
     $d = [string]::Empty 
    } 
    "$o$d" 
} 
+0

@Melab參數添加到您的腳本傳遞路徑,在所有的答案在這裏的路徑是硬代碼爲方便...閱讀有關如何創建與參數PowerShell腳本... – 2013-03-02 21:00:10

+0

我該怎麼做?我懷疑它會以正確的方式命令他們。看到我對Goyux的回答的評論。 – Melab 2013-03-03 15:45:22

+0

@Melab我認爲是時候嘗試自己做點什麼了...... – 2013-03-03 15:59:10

8

什麼你很可能在尋找的東西,以幫助區分從文件夾中的文件。幸運的是,有一個屬性叫PSIsContainer,對於文件夾是真實的,對於文件是虛假的。

dir -r | % { if ($_.PsIsContainer) { $_.FullName + "\" } else { $_.FullName } } 

C:\Source code\Base\ 
C:\Source code\List.txt 
C:\Source code\Base\main.c 
C:\Source code\Base\print.c 

如果前面的路徑信息是不可取的,你可以很輕鬆地使用-replace其刪除:

dir | % { $_.FullName -replace "C:\\","" } 

希望這可以讓你在正確的方向前進了。

+0

用於查看'\'作爲文件夾標記的+1;) – 2013-03-01 20:20:15

+1

@Guvante'''必須在正則表達式中逃脫! '-replace'的第一個參數是一個正則表達式! – 2013-03-01 20:28:28

+0

感嘆號使它更加直接。 http://knowyourmeme.com/memes/the-1-phenomenon – EBGreen 2013-03-01 20:43:08

3
dir | % { 
    $p= (split-path -noqualifier $_.fullname).substring(1) 
    if($_.psiscontainer) {$p+'\'} else {$p} 
} 
0
(ls $path -r).FullName | % {if((get-item "$_").psiscontainer){"$_\"}else{$_}} 

只有在PS 3.0使用

1

這一個顯示完整路徑,如一些其他的答案的事,但更短:

ls -r | % { $_.FullName + $(if($_.PsIsContainer){'\'}) } 

然而,OP相信詢問相對路徑(即相對於當前目錄),只有@ CB的回答解決了這一點。因此,只需添加一個substring我們有這個:

ls -r | % { $_.FullName.substring($pwd.Path.length+1) + $(if($_.PsIsContainer){'\'}) } 
0

不PowerShell的,但你可以使用命令提示符中的以下遞歸列出文件到一個文本文件:

dir *.* /s /b /a:-d > filelist.txt 
0

的PowerShell命令指南清單到TXT文件:

完全路徑目錄列表(文件夾&文件)以文本文件:

ls -r | % { $_.FullName + $(if($_.PsIsContainer){'\'}) } > filelist.txt 

相對路徑目錄列表(文件夾&文件)以文本文件:

ls -r | % { $_.FullName.substring($pwd.Path.length+1) + $(if($_.PsIsContainer){'\'}) } > filelist.txt 
相關問題