Powershell - 根据最新文件重命名文件夹中的特定文件

时间:2016-10-09 09:32:34

标签: powershell

在Powershell中,我想自动更改特定文件的文件名。

该目录包含以下文件: 2.0.zip

从第三方程序创建一个新文件,并将其命名为" archive.zip"。

我需要将archive.zip更改为2.n.n.zip

例如:2.0.1等等(增量),我该如何实现呢?

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$YourDirectory = "C:\Test"

$LastFileName = $NULL
$NewName = $NULL
try {$LastFileName = (Get-ChildItem $YourDirectory -exclude "archive.zip" | Sort-Object LastWriteTime | Select-Object -last 1).name.split('.')}
catch{Write-Error "last file name does not";Exit 2}

If ($LastFileName[2] -eq "zip")
{
    $NewName = $LastFileName[0] + "." + $LastFileName[1] + ".1.zip"
}
ElseIf ($LastFileName[2] -lt 9)
{
    $NewName = $LastFileName[0] + "." + $LastFileName[1] + "." + $([int]$LastFileName[2] + 1) + ".zip"
}
ElseIf ($LastFileName[2] -eq 9)
{
    If ($LastFileName[1] -lt 9)
    {
        $NewName = $LastFileName[0] + "." + $([int]$LastFileName[1] + 1) + ".0.zip"
    }
    ElseIf ($LastFileName[1] -eq 9)
    {
        Write-Warning "last possible file name reached";Exit 1
    }
}
Else
{
    Write-Error "new file name could not be calculated";Exit 3
}

If ($NewName -ne $NULL){Get-ChildItem $YourDirectory -Filter "archive.zip" | %{Rename-Item $_.Fullname -NewName $NewName}}
Else {Write-Error "new file name could not be calculated";Exit 4}

答案 1 :(得分:0)

此解决方案观看您的目录,如果您将文件zip复制到您的目录中,我将自动重命名

    $folder = 'C:\temp\2.0.zip'
    $filter = '*.zip'                             # <-- set this according to your requirements

    $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
     IncludeSubdirectories = $false              # <-- set this according to your requirements
     NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
    }
    $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
     $path = $Event.SourceEventArgs.FullPath
     $name = $Event.SourceEventArgs.Name
     $changeType = $Event.SourceEventArgs.ChangeType
     $timeStamp = $Event.TimeGenerated

    $pathonly=[io.path]::GetDirectoryName($path)
    $versiondir=[io.path]::GetFileNameWithoutExtension($pathonly)

    $filter= "$versiondir" + ".\d*.zip"
    $lastfile=gci -Path $folder  -File | where {$_.Name -ne $name -and $_.Name -match $filter}  | sort @{Expression={[int]((($_.Name).Split("."))[-2])};Descending=$true} | select -First 1 


    Write-Host "last file is " + $lastfile.Name

    if ($lastfile -eq $null)
    {
        $newfilename="$versiondir.1"
        Write-Host "new file ...."
    }
    else
    {

        [string[]] $splitname=($lastfile.Name).Split(".")

        $newfilename="$versiondir." + (([int]$splitname[-2])+1).ToString() 

    }


    Rename-Item $path "$pathonly\$newfilename.zip"
     
    }

如果你想停止观看:

    Unregister-Event -SourceIdentifier FileCreated
相关问题