将文件名从一个文件夹复制到另一个文件夹,同时保留原始扩展名

Copy file names from one folder to another while keeping the original extensions

我需要帮助将文件 names(不是文件本身)从 C 驱动器复制到 D 驱动器。我能够在线找到以下 powershell 代码:

$names = @()
$getPath = "C:\MyFiles"
$setPath = "D:\MyFiles"
Get-ChildItem $getPath |
    Foreach-object{
    $names += $_
}
$i = 0
Get-ChildItem $setPath |
Foreach-object{
    Rename-Item -Path $_.FullName -NewName $names[$i]
    $i++
}

此代码成功renames/copies所有文件名从C:\MyFilesD:\MyFiles,严格按照相应的位置(枚举中的索引)。

但是,它也在更新 扩展 ,例如:

C:\MyFiles\myfile.txtD:\MyFiles\thisfile.docx 重命名为 D:\MyFiles\myfile.txt

有没有办法编辑 Powershell 代码,仅重命名文件名的 base(例如,myFile),同时保留目标文件的 [=33] =]扩展名(例如,.docx)?

以便 C:\MyFiles\myfile.txtD:\MyFiles\thisfile.docx 重命名为 D:\MyFiles\myfile.docx,使用

听起来您想根据源目录中的相应文件重命名目标目录中的文件位置-同时保留目标目录文件的扩展名:

$getPath = "C:\MyFiles"
$setPath = "D:\MyFiles"
$sourceFiles = Get-ChildItem -File $getPath

$iRef = [ref] 0
Get-ChildItem -File $setPath | 
  Rename-Item -NewName { $sourceFiles[$iRef.Value++].BaseName + $_.Extension }
  • 预览结果文件名,将-WhatIf附加到Rename-Item调用。

  • Get-ChildItem returns 输出的 [System.IO.FileInfo] 对象的 .BaseName 属性 不带扩展名的文件名部分。

  • $_.Extension 提取输入文件(即目标文件)的现有扩展名,包括前导 .

  • 请注意,传递给 Rename-Item 的脚本块 ({ ... }) 创建了一个 child 变量范围,因此您不能递增调用者范围内的变量直接(每次都会用原始值创建这样一个变量的新副本);因此,创建了一个 [ref] 实例来 间接 保存数字,然后子作用域可以通过 .Value 属性.


这是一个完整的例子

注意:虽然此示例使用相似的文件名和统一的扩展名,但代码在一般any下工作名称和扩展名。

# Determine the temporary paths.
$getPath = Join-Path ([System.IO.Path]::GetTempPath()) ('Get' + $PID)
$setPath = Join-Path ([System.IO.Path]::GetTempPath())  ('Set' + $PID)

# Create the temp. directories.
$null = New-Item -ItemType Directory -Force $getPath, $setPath

# Fill the directories with files.

# Source files: "s-file{n}.source-ext"
"--- Source files:"
1..3 | % { New-Item -ItemType File (Join-Path $getPath ('s-file{0}.source-ext' -f $_)) } | 
  Select -Expand Name

# Target files: "t-file{n}.target-ext"
"
---- Target files:"
1..3 | % { New-Item -ItemType File (Join-Path $setPath ('t-file{0}.target-ext' -f $_)) } | 
  Select -Expand Name

# Get all source names.
$sourceFiles = Get-ChildItem -File $getPath

# Perform the renaming, using the source file names, but keeping the
# target files' extensions.
$i = 0; $iVar = Get-Variable -Name i
Get-ChildItem -File $setPath | 
  Rename-Item -NewName { $sourceFiles[$iVar.Value++].BaseName + $_.Extension }

"
---- Target files AFTER RENAMING:"

Get-ChildItem -Name $setPath

# Clean up.
Remove-Item -Recurse $getPath, $setPath

以上结果:

--- Source files:
s-file1.source-ext
s-file2.source-ext
s-file3.source-ext

---- Target files:
t-file1.target-ext
t-file2.target-ext
t-file3.target-ext

---- Target files AFTER RENAMING:
s-file1.target-ext
s-file2.target-ext
s-file3.target-ext

请注意目标文件现在如何具有源文件的基本文件名 (s-file*),但目标文件的原始扩展名 (.target-ext)。