首页 > 解决方案 > Powershell - 如何将文件名前缀到包含该文件类型的任何路径的文件夹中

问题描述

Powershell 脚本需要从目录上带有时间和日期戳的文件夹中的文件类型中提取文件基名,并使用该基名附加这些文件夹。

下面的脚本可以替换下面的路径名,但我需要为文件夹添加前缀。是否可以通过这种方式加入路径?

以下脚本的原始链接

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:\没有它的情况下运行我的整个驱动器。

标签: powershellprefixbasename

解决方案


它不漂亮,但我认为这会起作用:

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
}

更新了代码。


推荐阅读