I'm looking to fix a PowerShell script that I have and add some more features to it. Currently, it's working as intended: when a file is saved to a directory, it moves the item to a new one.
What I'm looking to add to it is instead of just overwriting the existing file, it renames it to yyyyMMdd
. The files are all the same and are always the same name/extension, so adding this would be a great way for some semi version control.
$folder = 'C:\scripts\test'
$filter = '*.*' # <-- set this according to your requirements
$destination = 'H:\Office Documents\text_move'
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{
IncludeSubdirectories = $true # <-- 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
Write-Host "The file '$name' was $changeType at $timeStamp"
$dirname = [io.path]::GetDirectoryName($folder)
$filename=[io.path]::GetFileNameWithoutExtension($file)
$ext = [io.path]::GetExtension($file)
$newpath = "$destination\$filename\$(get-date -f yyyyMMdd)$ext"
Move-Item $path -Destination $destination -verbose
}
I get that I need to add to string the get-date
, but I can't seem for the life of me figure out how or where to add that in to make it work the way I think it should.