Xyz
Xyz

Reputation: 1

Powershell rename and zipping

Need to rename all the files wwithin same directory using powershell

Source files 1234_56789abc_t1_20201_0_4_0.pdf 1234_56788def_t2_20200_0._4_1.pdf

Renamed files 1000_56789abc_tar_2020.pdf 1000_56788def_tar_2020.pdf

Also, need to zip these renamed files into one zip file.. In this i want to extract 4 digits of the year and neglect all the underscores afterwards..

Please help??

Upvotes: 0

Views: 373

Answers (1)

f6a4
f6a4

Reputation: 1782

Try this:

$directory = Get-Item -Path 'D:\test\mypdf'

foreach( $file in $directory.GetFiles() ) {

    $newFileName = $file.Name -replace '^(.*_)t\d+(_.*)$', '$1tar$2'
    Move-Item -Path $file.FullName -Destination $newFileName -WhatIf | out-null
}

Compress-Archive -Path "$directory\*.*" -DestinationPath "$directory\archive.zip" -CompressionLevel Optimal -Force | out-null

Upvotes: 1

Related Questions