首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Powershell使用备份移动文件(如mv -- backup =numbered)

Powershell使用备份移动文件(如mv -- backup =numbered)
EN

Stack Overflow用户
提问于 2018-09-05 15:38:34
回答 1查看 199关注 0票数 1

我正在查找是否有一个等于mv --backup=numbered的PS命令,但是找不到任何东西。

本质上,将'file‘移动到'file.old',但是如果'file.old’存在,'file‘应该移动到'file.old.2’。

目前,我找到的最接近的链接是:https://www.pdq.com/blog/copy-individual-files-and-rename-duplicates/

代码语言:javascript
运行
复制
$SourceFile = "C:\Temp\File.txt"
$DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"

If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i += 1
        $DestinationFile = "C:\Temp\NonexistentDirectory\File$i.txt"
    }
} Else {
    New-Item -ItemType File -Path $DestinationFile -Force
}

Copy-Item -Path $SourceFile -Destination $DestinationFile -Force 

拥有如此多的代码似乎相当可怕。有没有更简单的方法?

EN

回答 1

Stack Overflow用户

发布于 2018-09-05 18:17:25

事实上,没有内置的函数可以做到这一点。但是,使用您自己的函数来实现此目的应该不成问题。

这样如何:

代码语言:javascript
运行
复制
function Copy-FileNumbered {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
        [string]$SourceFile,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]$DestinationFile
    )
    # get the directory of the destination file and create if it does not exist
    $directory = Split-Path -Path $DestinationFile -Parent
    if (!(Test-Path -Path $directory -PathType Container)) {
        New-Item -Path $directory -ItemType 'Directory' -Force
    }

    $baseName  = [System.IO.Path]::GetFileNameWithoutExtension($DestinationFile)
    $extension = [System.IO.Path]::GetExtension($DestinationFile)    # this includes the dot
    $allFiles  = Get-ChildItem $directory | Where-Object {$_.PSIsContainer -eq $false} | Foreach-Object {$_.Name}
    $newFile = $baseName + $extension
    $count = 1
    while ($allFiles -contains $newFile) {
        $newFile = "{0}({1}){2}" -f $baseName, $count, $extension
        $count++
    }

    Copy-Item -Path $SourceFile -Destination (Join-Path $directory $newFile) -Force 
}

这将在目标位置创建一个新文件,例如File(1).txt当然,如果您希望使用类似File.2.txt的名称,只需将格式模板"{0}({1}){2}"更改为"{0}.{1}{2}"

使用如下函数

代码语言:javascript
运行
复制
$SourceFile = "C:\Temp\File.txt"
$DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"
Copy-FileNumbered -SourceFile $SourceFile -DestinationFile $DestinationFile
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52179616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档