I have a path in a string,
C:\temp\mybackup.zip
I would like insert a timestamp in that script, for example,
C:\temp\mybackup 2009-12-23.zip
Is there an easy way to do this in PowerShell?
You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:
"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"
And if you are getting the path from somewhere else - already as a string:
$dirName = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext = [io.path]::GetExtension($path)
$newPath = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"
And if the path happens to be coming from the output of Get-ChildItem:
Get-ChildItem *.zip | Foreach {
"$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.
[string]$filePath = "C:\tempFile.zip";
[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
Move-Item -LiteralPath $filePath -Destination $newFilePath;
I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:
wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx
The magic code is just this part:
$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
Thanks for the above script. One little modification to add in the file ending correctly. Try this ...
$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**
Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
If you have the path on a variable ($pathfile) use this concrete line to get the TimeStamped Path:
(extracted from here: https://powershellexamples.com/home/Article/10/file-management-add-timestamp-to-file-name)
$pathFile = "C:\ProgramData\MyApp\file.txt"
$pathFileTimestamp = [System.IO.Path]::GetDirectoryName($pathFile) + "\" + `
[System.IO.Path]::GetFileNameWithoutExtension($pathFile) + "_" + `
(get-date -format yyyyMMdd_HHmmss) + ([System.IO.Path]::GetExtension($pathFile))
Write-Host "Path+File: $pathFile"
Write-Host "Path+File with Timestamp: $pathFileTimestamp"
Above will return:
PS C:\> Path+File: C:\ProgramData\MyApp\file.txt
Path+File with Timestamp: C:\ProgramData\MyApp\file_20210328_022045.txt
Use:
$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
Another approach for renaming.
Set-Location C:\Folder_containing_zipfiles
Get-ChildItem -File | ForEach-Object { Rename-Item -Path $_.FullName -NewName
$_.Name.Replace('.zip',"_$(get-date -Format yyyy_MM_dd_hh_mm_ss).zip") }
use variable to rename existing file
Get-Content -Path '${{vars.LOG_PATH}}\eventMapper.log'
$filenameFormat = 'eventMapper-' + (Get-Date -Format 'yyyy-mm-dd-hh-mm') + '.log'
Rename-Item -Path '${{vars.LOG_PATH}}\eventMapper.log' -NewName $filenameFormat
file created --> eventMapper-2023-23-21-10-23.log
Date + Filename - NOT (Filename + Date) - otherwise it messes up file extension.
$filenameFormat = (Get-Date -Format "yyyy-MM-dd") + " " + "mybackup.zip"
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
Related
I am trying to rename a filename by moving string from the back of the filename to the front:
PM - Prebills_10Aug20_Project _ 3359122596 H to:
3359122596 H PM - Prebills_10Aug20_
I'm trying to use this script and then strip out 'Project' afterward but can't get it to work:
Get-ChildItem *.pdf | Rename-Item -NewName {
$_.Name -replace '(Project\d{*}) - (.*?)\.pdf$', '$1 -
$2.pdf' } -WhatIf
This works. I don't know how general the pattern has to be. Check out https://regex101.com for trying out regex's.
Get-ChildItem *.pdf |
Rename-Item -NewName { $_.Name -replace '(.*)Project _ (\d{10} H)', '$2 $1' } -WhatIf
What if: Performing the operation "Rename File" on target
"Item: C:\users\admin\PM - Prebills_10Aug20_Project _ 3359122596 H.pdf
Destination: C:\users\admin\3359122596 H PM - Prebills_10Aug20_.pdf".
Adapt this into your code:
Clear-Host
$FName = "PM - Prebills_10Aug20_Project_3359122596 H"
#-------- Start Here -------
$Parts = $FName.Split("_")
$FName = $Parts[3] + " " + $Parts[0] + "_" + $Parts[1]
#-------- End Here -----
$FName
Results: 3359122596 H PM - Prebills_10Aug20
It suppresses the trailing underline, you can add it back in if you want it. You could also easily remove the underline between Prebills and date and replace it with a space.
HTH
I would do it like:
foreach($file in (Get-ChildItem *.pdf )){
$temp = $file -split '_'
$newname= $temp[3] + " " + $temp[1] + "_" + $temp[2] + "_"
Rename-item "$file" -NewName "$newname"
}
I need help with rearranging and renaming a bunch of files in PowerShell.
I want to change from:
YYYY_Project name_City_Category.jpg
to
YYYY_Category_Project name_City.jpg
The years, categories, project names and cities are of course all different.
Please be gentle, I'm new to PowerShell and regex.
Assuming we have an item like this:
get-item '.\YYYY_Project name_City_Category.jpg'
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 6/8/2020 10:12 AM 8 YYYY_Project name_City_Category.jpg
This is a FileInfo object which has a number of properties, one of which is BaseName which gives us the filename without extension.
PS> $file = get-item '.\YYYY_Project name_City_Category.jpg'
PS> $File.BaseName
YYYY_Project name_City_Category
We can call the .Split() method on the BaseName property to split on every instance of the _ underscore character, like so:
PS> $File.BaseName.Split('_')
YYYY
Project name
City
Category
We can then assign those to variables like this:
$FileSegments = $File.BaseName.Split('_')
$YearPart = $FileSegments[0]
$ProjPart = $FileSegments[1]
$CityPart = $FileSegments[2]
$CatgPart = $FileSegments[3]
We can then reassemble them in our desired order like this:
$newName = $YearPart + "_" + $CatgPart + "_" + $ProjPart + "_" + $CityPart + $file.Extension
write-host $newName
YYYY_Category_Project name_City.jpg
So, you'd put it all together like this. If you like the results, remove -WhatIf
$files = Get-ChildItem C:\PathTo\Your\Directory\*.jpg
ForEach ($file in $files){
$FileSegments = $File.BaseName.Split('_')
$YearPart = $FileSegments[0]
$ProjPart = $FileSegments[1]
$CityPart = $FileSegments[2]
$CatgPart = $FileSegments[3]
$newName = $YearPart + "_" + $CatgPart + "_" + $ProjPart + "_" + $CityPart + $file.Extension
write-host $newName
Rename-Item -Path $file.FullName -NewName $newName -WhatIf
}
You don't need a complex Regex for this, just some understanding of how to get the files in a folder using Get-ChildItem and how Rename-Item works.
Something like this should do it
$sourcePath = 'Folder\To\Where\The\Files\Are'
Get-ChildItem -Path $sourcePath -Filter '*.jpg' -File | Rename-Item -NewName {
# split the file's BaseName into 4 pieces at the underscore
$year, $project, $city, $category = $_.BaseName -split '_', 4
# use the -f Format operator to stitch the parts together in a new order
# see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-5.1#format-operator--f
'{0}_{1}_{2}_{3}{4}' -f $year, $category, $project, $city, $_.Extension
}
One liner version of the split and join idea:
dir *_*_*_*.jpg | ren -new {((($_.basename -split '_')[0,3,1,2]) -join '_') +'.jpg'} -whatif
What if: Performing the operation "Rename File" on target
"Item: C:\Users\admin\foo\YYYY_Project name_City_Category.jpg
Destination: C:\Users\admin\foo\YYYY_Category_Project name_City.jpg".
I am trying to write a script that will move hundreds of account PDFs into their respective folders. I am very new to powershell and my basic script for now I was able to move one file to the other folder and match its name and date format of 052020 using this script:
cd \\Sageshare\share
copy-item -path "\\Sageshare\share\Reconciliation\PDF Recon Center\DEA RECON 05292020.pdf" -destination "\\Sageshare\share\Reconciliation\Account Rec. Sheets\Separate Accounts\DEA" | Where-Object {$_.Name -like '*DEA RECON 052020*'}
Since that is only one file going into its named folder in another directory, how would I do this with 400 files going each into a respective folder? If I can get this then I am going to run into the issue to where the 05 date is going to need to change to 06 and so on until the end of the year where it will also have to change the month and year. But I would really like to just figure out the first part for now.
I have make you an code example which shows you how to work in Powershell. You cant break anything when you run my code until you uncomment the two lines at the end
$sourceFolder = '\\Sageshare\share\Reconciliation\PDF Recon Center'
$targetFolder = '\\Sageshare\share\Reconciliation\Account Rec. Sheets\Separate Accounts\DEA'
$files = Get-ChildItem $sourcefolder -Filter *.pdf
$files | ForEach-Object {
echo ('Processing file ' + $_.Name)
$regex = [regex]::Match($_.Name, '\s([0-9]{2})([0-9]{2})([0-9]{4})[.]pdf')
echo ('Month ' + $regex.Groups[1].Value)
echo ('Date ' + $regex.Groups[2].Value)
echo ('Year ' + $regex.Groups[3].Value)
$targetFolderTmp = (Join-Path $targetFolder -childpath ($regex.Groups[3].Value + '\' + $regex.Groups[1].Value + '\' + $regex.Groups[2].Value))
Write-Host ('Copy to: ' + $targetFolderTmp)
#if(-not $targetFolderTmp) {mkdir $targetFolderTmp} uncomment if code is good
#copy-item -path $_.FullName -destination targetFolderTmp uncomment if code is good
}
I am attempting to write a small PowerShell script to clean up files names from some log dumps, but I seem to be stuck... I have logs dumped from various sources, and the file names seem to be getting garbled up.
I am looking to for name the names of files like so... " Source - Service.log "
Get-ChildItem *.* -Path ~/Desktop/New | ForEach-Object {
while ([string]($_.Name) -notmatch "^[a-z].*" -or [string]($_.Name) -notmatch "^[A-Z].*") {
Rename-Item -NewName { [string]($_.Name).Substring(1) }
}
Write-Host $_.Name
}
The output seems to be erroring out.
Rename-Item : Cannot evaluate parameter 'NewName' because its argument is
specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:8 char:30
+ Rename-Item -NewName { $File.Substring(1) }
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand
The Idea is to check the filename to to see if it is a character, and if not remove it, to remove ". - / and whitespace"
The orginal files I am running against are like this:
1. source - data (1).log
100. - source - Data.log
(1) Source - data.log
source - data.log
<space><space> source - data.log
and the result I am looking for from the above is: I am not concerned about the duplicates file names as source and data change day to day and the folder is cleared regularly...
source - data (1).log
source - Data.log
Source - data.log
source - data.log
source - data.log
Can someone tell me how to get past this error?
If your goal is to delete leading non-alpha characters, you can simplify what you're doing:
$files = Get-ChildItem -Path ~\Desktop\New -File
foreach ($file in $files)
{
if ($file.BaseName -notmatch '\S+\s-')
{
$newName = $file.Name -replace '^.+?(?=[a-z])'
$newName = Join-Path $file.DirectoryName $newName
if (Test-Path -Path $newName)
{
Remove-Item -Path $newName
}
$file | Rename-Item -NewName $newName
Write-Verbose $newName
}
}
This will iterate your list and look for your pattern, renaming where necessary. Assumption: the source doesn't have spaces.
This might be helpful: Remove-NonAlphanumericCharFromString.
Knowing how to remove non-alphanumeric, take the base name of the file (name without Path and extension).
Replace unwanted Chars with empty string.
$pattern = '[^a-zA-Z]'
Set-Location <YourDir>
Get-Childitem | Foreach-Object {
Rename-Item -Path ".\$($_.Name)" -NewName "$($_.BaseName -replace $pattern,'')$($_.extension)"
}
Note that above will fail upon a need to overwrite existing file.
I have this Powershell code:
Function CheckFileList()
{
$limit = (Get-Date).AddDays(-270)
$input_path = gci '//network/sourceDir' | sort -property LastWriteTime
$output_file = 'c:\PowershellScripts\prune_results.txt'
#Clear-Content $output_file
$countf = 0
$outputstr = ""
$outputstr = $(Get-Date -format 'F') + " - Folders to be purged:`r`n"
$input_path | Foreach-Object{
if ( (Get-Item $_.FullName) -is [System.IO.DirectoryInfo] ) {
if ( $_.LastWriteTime -le $limit ) {
$source='//network/sourceDir' + $_.Name
$dest="\\computer\c$\targetDir" + $_.Name
$what=#("/MOVE")
$options=#("/COPY:DAT /DCOPY:T")
$cmdArgs = #("$source","$dest",$what,$options)
#"robocopy " + $cmdArgs >> $output_file
robocopy #cmdArgs
$outputstr = $outputstr + " (" + $_.LastWriteTime + ") `t" + $_.Name + "`r`n"
$countf++
$outputstr = $outputstr + "Folders [to be] purged: " + $countf + "`r`n`r`n"
$outputstr >> $output_file
Exit
}
}
}
$outputstr = $outputstr + "Folders [to be] purged: " + $countf + "`r`n`r`n"
$outputstr >> $output_file
}
CheckFilelist
This is intended to move many folders (and the files in them) while preserving the folder timestamps.
When I run it, I get this error:
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : Mon Apr 27 13:20:35 2015
Source - \\network\sourceDir\someFolder12345\
Dest - \\computer\c$\someFolder12345\
Files :
Options : /COPY:DAT /MOVE /R:1000000 /W:30
------------------------------------------------------------------------------
ERROR : Invalid Parameter #4 : "/COPY:DAT /DCOPY:T"
Simple Usage :: ROBOCOPY source destination /MIR
source :: Source Directory (drive:\path or \\server\share\path).
destination :: Destination Dir (drive:\path or \\server\share\path).
/MIR :: Mirror a complete directory tree.
For more usage information run ROBOCOPY /?
**** /MIR can DELETE files as well as copy them !
Is there something wrong with my what/options array? The parameters look valid to me.
[EDIT] I'm also finding this script is not preserving folder timestamps. someFolder12345 ends up on the targetDir with the date/time of "now". The files within the folder are preserving timestamps, but not the folder?
It looks like your string "/COPY:DAT /DCOPY:T" is being passed to robocopy as one argument, not as 2 separate arguments. If you check the $options variable, it has a single item in the array. Try changing that line to $options=#("/COPY:DAT","/DCOPY:T") so that each argument is passed in separately.