question

mehta.parth09 avatar image
mehta.parth09 asked

Create log file in PowerShell for file movement

I would like below PowerShell script to create log file which should contain information about how many files have been moved in each folder and error exception/handling code in case of script get fails in between so that automatically perform rollback. Below code is used to move files according to last modified date and it creates folder in YYYYMM format in same path. For example, suppose file's last modified date is any date of Dec-2016 so it will move that file to 201612 folder after creating this folder and zip the folder and remove it. I need help that this code should generate log file with how many files moved and if code fails then it should rollback. Can someone please help me with this? Param( $FolderPath = "D:\newfolder\*.*", $ErrorActionPreference = "Stop" ) $ChildItems = Get-ChildItem $FolderPath -Include *.txt,*.xml $DestFolders = @() foreach ($item in $ChildItems) { if ((($item.LastWriteTime).Month -ne (Get-Date).Month) -or (($item.LastWriteTime).Year -ne (Get-Date).Year)) { $FolderName = $(Get-Date $item.LastWriteTime -f "yyyyMM").ToString() $DestFolder = ($item.Directory.ToString() + "\" + $Foldername) $DestFolders += $DestFolder if (-not (Test-Path $DestFolder)) { try { New-Item $DestFolder -ItemType Directory -ErrorAction Stop } catch { throw $Error[0] } } try { Move-Item $item -Destination $DestFolder -ErrorAction Stop } catch { throw $Error[0] } } } foreach ($item in ($DestFolders | Sort-Object | Get-Unique)) { try { Add-Type -Assembly System.IO.Compression.FileSystem $CompressLevel = [System.IO.Compression.CompressionLevel]::Optimal $SourceFolder = $item $DestFileName = ($item + ".zip") [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceFolder, $DestFileName, $CompressLevel, $false) Remove-Item $SourceFolder -Recurse -ErrorAction Stop } catch { throw $Error[0] } }
powershellautomationwindowsmove
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

0 Answers

·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.