簡體   English   中英

如何僅在具有Powershell的txt文件的目錄中列出具有特定擴展名的文件?

[英]How can I list files with a certain extension only in a directory to a txt file with powershell?

我有一個包含約100個文件的目錄。 有沒有一種方法可以使用Powershell將目錄的內容列出到txt文件中?

My directory is C:\logs\weekly

我想要的是僅列出.log擴展名的文件,如下所示:

weekly\file1.log
weekly\file2.log
weekly\file3.log

這很簡單。

使用Get-ChildItem獲取子項,然后使用父路徑的Length確定在何處剪切FullName (路徑)屬性上的Substring()

function Get-ChildItemWithoutParent {
    param(
        [string]$Path,
        [string]$Filter,
        [switch]$Recurse
    )

    $ParentPathLength = (Split-Path $Path -Parent).Length + 1

    Get-ChildItem @PSBoundParameters |ForEach-Object {
        $_.FullName.Substring($ParentPathLength)
    }
}

使用$PSBoundParameters自動變量 ,我們可以對內部cmdlet調用重新使用 (或代理 )參數,而無需進行各種自定義處理,非常簡潔

現在,您只需要將輸出通過管道傳輸到文件:

Get-ChildItemWithoutParent -Path 'C:\logs\weekly' -Filter *.log | Out-File -Path .\textfile.txt

像這樣:

Get-ChildItem -Filter *.log | Select FullName -ExpandProperty FullName | Set-Content YourFileName.txt

如果您不希望使用完整路徑,則可以使用正則表達式替換,如下所示:

Get-ChildItem -Filter *.log | % {
    % {$_.FullName  -replace '^.*\\([^\\]+\\.*)$', '$1'}
} | Set-Content YourFileName.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM