簡體   English   中英

Powershell - 如何在包含該文件類型的任何路徑的文件夾中添加文件名前綴

[英]Powershell - How to prefix filename into folder for any path containing that file type

Powershell 腳本需要從目錄上帶有時間和日期標記的文件夾中的文件類型中提取文件基名,並且 append 那些具有該基名的文件夾。

下面的腳本可以替換下面的路徑名,但我需要為文件夾添加前綴。 是否可以通過這種方式加入路徑?

以下腳本的原始鏈接

cd C:\Directory
Get-ChildItem *.lsa -File -Recurse | ForEach-Object {
  Rename-Item (Split-Path $_ -Parent) ($_.BaseName)  -WhatIf 
}

結果:

What if: Performing the operation "Rename Directory" on target "Item: C:\Directory\originalpath 
Destination: C:\Directory\basename".

我想要的是"C:\Directory\basename_originalpath"
或者更好的是"C:\Directory\basename\originalpath"

我認為Join-path是解決方案,但我是第一次編寫腳本,無法鏈接這兩個命令。 我還必須指定起始目錄,因為第一次嘗試在沒有它的情況下運行我的整個c:\驅動器。

它不漂亮,但我認為這會起作用:

Get-ChildItem *.lsa -File -Recurse | ForEach-Object {
    if(-Not (Test-Path -Path "$outputDirectory\$($_.BaseName)")){
        New-Item -WhatIf -ItemType Directory -Path "$outputDirectory\$($_.BaseName)"
    }

    Move-Item (Split-Path $_ -Parent) "$outputDirectory\$($_.BaseName)\$($_.Directory.BaseName)" -WhatIf
}

更新了代碼。

暫無
暫無

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

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