Copy and rename file following a pattern with Powershell - powershell

I have a file with name like this:
KE1_F00177_077_00_50
When I show the Property of the file, 2018.02.21.10.30 is the modified Date of the File which is copied like the picture below. I want to copy this file to another Location and rename it with Powershell. The new name should be:
_F00177_2018_02_2018.02.21.10.30_KE1_F00177_077_00_50

This will generate the format you mention including hour in 12 hour format (AM/PM).
$source = 'c:\temp\KE1_F00177_077_00_50'
$destinationFolder = 'c:\temp\new'
$file = Get-ChildItem $source
$date = '{0:yyyy_MM_yyyy.MM.dd.HH.mm}' -f $file.LastWriteTime
$head = $file.Name.Split('_')[1]
Copy-Item $source "$($destinationFolder)/_$($head)_$($date)_$($file.Name)"
However you should consider either using 24 hour format or including AM/PM in the name, otherwise it won't be easy to know when it is AM or PM.
For 24 hour format, replace hh for HH:
$date = '{0:yyyy_MM_yyyy.MM.dd.HH.mm}' -f $modified

Related

How to build path and file name for excel sheet from SMB share

I have below share and folders. For every month there will be a folder and there will be year folder prior to that as shown
Last Friday of every month there is excel sheet generated as shown below
End piece in file name "-14-26-48" remain same but prior pieces changes as per year and date. I would like to get this excel sheet path and name build in PowerShell. So how can i code so i get following path without manually entering complete path and filename. whenever i run new code i should get path and file name for last sheet which was generated last Friday of last month.
$oldbk = Import-Excel -Path '\\hcohesity05\cohesity_reports\2022\7\07-29\Cohesity_FETB_Report-2022-07-29-14-26-48.xlsx'
If you just want the file from the last Friday of the previous month the easiest way to find it is not to build the path, but just search a month's folders and filter for files created on a Friday, sort by time created, and get the first one (once sorted the last folder created will be the first item).
$LastMonth = [datetime]::Now.AddMonths(-1).ToString('yyyy\\M')
$TargetFolder = Get-ChildItem (Join-Path '\\hcohesity05\cohesity_reports' $LastMonth) |Where{$_.CreationTime.DayOfWeek -eq 'Friday'}|Sort CreationTime|Select -first 1
$FilePath = (Resolve-Path (Join-Path $TargetFolder.FullName 'Cohesity_FETB_Report-*-14-26-48.xlsx')).Path
$oldbk = Import-Excel -Path $FilePath
You can use the [DateTime] type to help you out here.
# To do this, we create a new datetime,
# (using the current month and year, but the first day).
$endOfMonth = [datetime]::new(
[DateTime]::Now.Year,
[DateTime]::Now.Month,
1
).AddMonths(1).AddDays(-1)
# Then we add a month to it and subtract a day
# (thus giving us the last day of the month)
# Now we create a variable for the last Friday
$lastFriday = $endOfMonth
# and we keep moving backward thru the calendar until it's right.
while ($lastFriday.DayOfWeek -ne 'Friday') {
$lastFriday = $lastFriday.AddDays(-1)
}
# At this point, we can make the ReportPath, piece by piece
# ($BasePath would be the path until this point)
$ReportPrefix = "Cohesity_FETB_Report"
$ReportSuffix = "14-26-48.xlsx"
$ReportPath = Join-Path $BasePath $lastFriday.Year |
Join-Path -ChildPath $lastFriday.Month |
# A Custom format string will be needed for the month/day
Join-Path -ChildPath $lastFriday.ToString("MM-dd") |
Join-Path -ChildPath "$reportPrefix-$($lastFriday.ToString('YYYY-MM-dd'))-$reportSuffix"
$reportPath

How to set Get-Date format as variable but get up to date time in function

I'm trying to store a get-date format as a variable so it's at the top of the file but be able to have it get an up to date get-date in functions using the variable name. Example:
$LogDir = "c:\somefolders"
$LogSubDir = $(Get-Date -f MM-yyyy)
function MakeLogSubDirs{
$Path = "$LogDir\$LogSubDir" # rather than "$LogDir\$(Get-Date -f MM-yyyy)"
If(!(test-path $path)) {
New-Item -ItemType Directory -Path $path
}
But I don't want it to set the time in the variable, I want the variable in the variable, to get gotten in the function. I tried single quotes $LogSubDir = '$(Get-Date -f MM-yyyy)', but that didn't work. "$LogDir\$(Get-Date -f MM-yyyy)" works to make the folder. Any suggestions?
here is a demo of the save the pattern into a $Var & use that later idea ... [grin]
$EU_Backwards = 'dd-MM-yyyy'
$US_InsideOut = 'MM-dd-yyyy'
$SaneSortable = 'yyyy-MM-dd'
Get-Date -Format $EU_Backwards
output = 15-05-2022
as an aside, try to use the sane, sortable largest 1st layout whenever you can. [grin]

How to modify the date-created attribute for multiple files using .csv data?

I am unsure on how to word my problem as it's not something I am familiar with,
but Powershell is probably what I'm need to use.
I saw this: need to change file created date based on csv (4 years ago)
and would like to know how I can apply this to my problem.
I have many .mp4 files in the folder videos that have incorrect date-created attributes.
I also have a .csv file that lists the all the files in videos in chronological order (using the respective filenames).
The first file starts at 15 Nov 2019, and each successive video is created 1 day after the prior.
How can powershell help me modify the date-created attribute of every file using the rows of the files in the .csv file.
CSV FILE: contains the filenames IN CHRONOLOGICAL ORDER
video1
video2
video3
...
videos Folder:
name date created
video1 dd/mm/yyyy
video2 dd/mm/yyyy
video3 dd/mm/yyyy
... ... <---- dates are incorrect
What I would like:
name date created
video1 15/11/2019
video2 16/11/2019
video3 17/11/2019
... ... <---- dates are in chronological order according to .csv file
Thanks for your help!
Assuming that:
A) all your files are in the same folder
OR B) you have the full paths in your CSV
AND C) your csv files header is called filename
$csvfile = 'Path\to\csvfile.csv'
$startdate = Get-Date 11/15/2019
Set-Location Path\to\videofiles
Import-Csv $csvfile | ForEach-Object {
#set creationtime
(Get-Item $_.filename).CreationTime = $startdate
#increase date by one day
$startdate = $startdate.AddDays(1)
}
#Doug Maurer provided an incomplete answer (did not work) so here is the working solution:
$csvfile = 'path/to/csvfile.csv'
$startdate = [datetime]::ParseExact('15/11/2019','dd/MM/yyyy',$null)
Set-Location 'path/to/folder'
Import-Csv $csvfile | ForEach-Object {
#set creationtime
(Get-Item $_.filename).CreationTime = $startdate
#increase date by one day
$startdate = $startdate.AddDays(1)
}

Rename and copy select files in nested directory Powershell

I cannot seem to rename let alone copy any text files using this code, I am trying to go through a nested directory which should be taken care of with Get-ChildItem -Recurse.
It seems like I am only going through the selected source folder's files instead of fully recursing through all of the subfolders.
A sample text file in the directory would be 02-01-2016 Test.txt
$InputDate = Read-Host -Param 'Please select a starting date (In the following format: mmddyyyy)'
$Date = [datetime]::ParseExact($InputDate, "MMddyyyy", [Globalization.CultureInfo]::CreateSpecificCulture('en-US'), $null)
$Dst = Select-FolderDialog #This function is working for me, assume you can select a folder
$Src = 'C:\Users\Bart Zhang\Downloads\Test Folder (1)\Test Folder' # #source
$FileType = '*.txt'
Get-ChildItem -Path $Src -Recurse -Force | Where-Object {$_.Name -notcontains "Archive"} | ForEach-Object {
$DateStr = $_.BaseName.Substring(0, 2) + $_.BaseName.Substring(3, 2) + $_.BaseName.Substring(6, 4)
$FileDate = [datetime]::ParseExact($DateStr, "MMddyyyy", [Globalization.CultureInfo]::CreateSpecificCulture('en-US'), $null)
If ( $FileDate -ge $Date ) {
Rename-Item -NewName { $_.Directory.Name + ' ' + $_.Name} -Filter $FileType -Recurse -Force
Copy-Item -Path (Join-Path -Path $Src -ChildPath '\*' ) -Destination $Dst -Filter $FileType -Recurse -Force
}
}
I started with a sample folder with files with this naming standard, matching what you described.
Then I ran through your date conversion logic and found that it didn't seem to work as described (lots of errors trying to conver '04082011' to date, for instance) , so I made a change on line 10, changing the line to this:
$DateStr = $_.BaseName.Substring(0,2)+'/'+$_.BaseName.Substring(3,2)+'/'+$_.BaseName.Substring(6,4)
I simply added slashes to the date, so we would end up with '04/08/2011' which seemed to be all I needed for $DateStr to populate, which then allowed the line of file date comparison to work. I also changed the conversion on line 11 to this
$FileDate = get-date $DateStr
Adding some Write-Host lines for visibility and I get this.
03/02/2017 03-02-2017 Test has date of 03/02/2017 00:00:00
03-02-2017 Test has a file date of 03/02/2017 00:00:00 which is newer than 02/04/2014 10:13:14, time to move it
03/22/2010 03-22-2010 Test has date of 03/22/2010 00:00:00
03-22-2010 Test has a file date of 03/22/2010 00:00:00 which is older than 02/04/2014 10:13:14, ignoring...
04/08/2011 04-08-2011 Test has date of 04/08/2011 00:00:00
04-08-2011 Test has a file date of 04/08/2011 00:00:00 which is older than 02/04/2014 10:13:14, ignoring...
05/08/2016 05-08-2016 Test has date of 05/08/2016 00:00:00
05-08-2016 Test has a file date of 05/08/2016 00:00:00 which is newer than 02/04/2014 10:13:14, time to move it
I haven't checked the rest of your code, but this should get you back on track.
Conclusion
Good work for parsing out the file date from a file name like that, which is tricky. However the Conversion technique you were trying was making things harder than it needed to be, so by changing the way we parse the filename (adding slashes so that PowerShell would recognize the string with the much easier Get-Date cmdlet), we could use a different technique which is easier to understand.

Powershell file name check

I need verify a file copied to a destination exists, the file format is like:
SuperFile_yyyyMMdd_randomstring.txt
What I have tried to do is the below:
$FileDate = Get-Date -format yyyyMMdd
$FileExists = (Test-Path "\\UNC\TestShare\SuperFile_$FileDate_*")
However all files that match the first part SuperFile_ are copied and not just the ones matching the date. This file is created daily and I want to ignore any other file that do not contain the today's date. I had tried to do a Get-ChildItem query and pipe this into my check but it never returned any files.
So my problem is both copying and also verifying the file I just copied exists in the destination.
Thanks for any help.
_ is a valid character for variable names, so the expression evaluated $FileDate_, which is not defined. This can be prevented by using a subexpression:
$FileDate = Get-Date -format yyyyMMdd
$FileExists = (Test-Path "\\UNC\TestShare\SuperFile_$($FileDate)_*")
or by putting the variable name in curly braces:
$FileDate = Get-Date -format yyyyMMdd
$FileExists = (Test-Path "\\UNC\TestShare\SuperFile_${FileDate}_*")