簡體   English   中英

powershell,在文件名中搜索第二個后的 5 個字符。 如果唯一則創建一個新目錄,然后移動,如果不唯一則移動

[英]powershell, search a filename for 5 characters after the second. create a new directory if it is unique, and move, if not, just move

我對 powershell 非常陌生,並且已經設法運行了一些基本命令。 但是,我堅持這一點。

我有一個包含數百個.txt 文件的文件夾。 每個.txt 文件都有特定的命名格式。 220401.tailnm.22JUN21.CALLSIGN.txt 我需要能夠按月和年分解這些文件。

那么我該如何寫:查看所有文本文件,在每個文件名中搜索第二個“.”之后的前 5 個字符。 如果該目錄不存在,則創建一個具有該名稱的新目錄並將文件移入其中。 如果該目錄已經存在,只需將文件移動到其中即可。 ??

我在網上找到了一些類似的帖子,但我並不完全理解他們在做什么,因此為什么我想出的可能沒有多大意義?

$files = get-childitem {$_.name -like "011529.tailnm.*"} $files %{$date = $_.name.Split('.')[2] | if (-not(test-path $date)) {md $date} $_.fullname | move -destination $date}

我一直收到紅色錯誤:Get-ChildItem:無法將“System.Object[]”轉換為參數“Filter”所需的類型“System.String”。

非常感謝對此的任何幫助。

非常感謝, 親切的問候

好的,這應該做你想做的。 我在每一步都添加了內聯注釋以幫助理解代碼。

# specify the rootfolder for the subdirectories and files
$destination = 'X:\The folder where the subfolders should be and the files to be moved to'
# find the files that fit the naming format
Get-ChildItem -Path 'C:\users\xxxxxxx' -Filter "*.tailnm.*.txt" -File | ForEach-Object {
    $date = $_.Name.Split('.')[2]
    if ($date.Length -gt 5) { $date = $date.Substring(0,5) }
    # combine the target destination folder path
    $targetDirectory = Join-Path -Path $destination -ChildPath $date
    if (-not(Test-Path -Path $targetDirectory -PathType Container)) {
        # create the subfolder if it did not yet exist
        $null = New-Item -Path $targetDirectory -ItemType Directory
    }
    # finaly move the file (represented by $_)
    $_ | Move-Item -Destination $targetDirectory
}

暫無
暫無

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

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