复制后重命名 - Powershell

时间:2018-01-08 16:04:31

标签: powershell

我正在尝试使用powershell将一种类型的文件(.xlsx)从一个文件夹复制到另一个文件夹。

复制完成后,我希望更改原始文件的扩展名。 (.xlsx到.cmp)

我将副本部分放下(下方),但在重命名时我迷失了方向。你能帮忙吗?我是PS菜鸟!谢谢。

$src = "C:\Users\x\Documents\Test1"
$dst = "C:\Users\x\Documents\Test2"

Get-ChildItem $src -Filter "*.xlsx" | Move-Item -Destination $dst -Force

2 个答案:

答案 0 :(得分:0)

这应该这样做:

$src = "C:\Users\x\Documents\Test1"
$dst = "C:\Users\x\Documents\Test2"

Get-ChildItem $src -Filter "*.xlsx" | ForEach-Object {
    Copy-Item $_ -Destination $dst 
    Rename-Item $_ -NewName ($_.Name -Replace '.xlsx','.cmp')
}

使用ForEach-Object循环遍历$src文件夹中的每个项目。然后对于每个项目(在循环内表示为$_),我们使用Copy-Item将其复制到目标然后使用带有-Replace的Rename-Item来更改文件扩展名。

答案 1 :(得分:0)

据我所知,您必须遍历文件才能执行此重命名。

# Set-up variables
$sourcePath = "C:\temp"
$sourceExtension = "txt"
$destinationPath = "C:\temp2"
$destinationExtension = "cmp"

# Grab the list of files
$files = Get-ChildItem -Path $sourcePath -Filter "*.$sourceExtension"

# Loop over the files
foreach ($file in $files) {
    # Construct the new file name
    $newFileName = (Join-Path -Path $destinationPath -ChildPath $file.BaseName) + ".$destinationExtension"

    Write-Output "New File Name = $newFileName"

    # Move the file to the new destination with its new name!
    Move-Item -Path $file.FullName -Destination $newFileName
}

注意:BaseName =文件名没有扩展名

相关问题