Combine path, file strings and literals for path - powershell

Trying to combine a path, filename, and add some text along with a variable for Out-File log.
I've tried many alternatives unsuccessfully and need assistance;
FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$OldVersion = C:\Temp\TestFile.txt
$OldPath = (Get-Item $OldVersion).DirectoryName
$OldBaseName = (Get-Item $OldVersion).BaseName
ErrFile = Join-Path $OldPath OldBaseName
Out-File -FilePath "$ErrFile_$FormattedDate Error.txt"
Out-File -FilePath "$($OldPath)$($OldBaseName)_$($FormattedDate)_Error.txt"
...just two examples.
I've tried many other combinations and driving me crazy.
Basically I want it to be.
C:\Temp\TestFile_2017-08-24 16:51:36_Error.txt
Update:
I've tried both
$filename = '{0}_{1:s}_Error{2}' -f $basename, (Get-Date), $extension
I get _2017-08-25T13:02:17_Error.txt but no basename (TestFile).
$newpath = "${dirname}\${basename}_${date}_Error${extension}"
I get
A drive with the name '_2017-08-25 13' does not exists.
Can you also explain or provide a resource of what '{0}_{1:s}_Error{2}' and/or '{0}_{1:yyyy-MM-dd HH:mm:ss}_Error{2}' does?

Use the format operator (-f) for constructing the filename and Join-Path for building the path.
$oldpath = 'C:\Temp\TestFile.txt'
$basename = [IO.Path]::GetFileNameWithoutExtension($oldpath)
$extension = [IO.Path]::GetExtension($oldpath)
$filename = '{0}_{1:yyyy-MM-dd HH:mm:ss}_Error{2}' -f $basename, (Get-Date), $extension
$newpath = Join-Path ([IO.Path]::GetDirectoryName($oldpath)) $filename
Unless you must have the space in the date format you could simplify the format string by using the standard sortable format specifier (s) that will produce date strings like 2017-08-24T23:58:25 instead of 2017-08-24 23:58:25.
$filename = '{0}_{1:s}_Error{2}' -f $basename, (Get-Date), $extension
If you want to construct the path as a string with inline variables you need to make sure that the underscores in your file name are kept separate from the variable name. Because underscores are valid name components for variable names $var_ is the variable var_, not the variable var followed by a literal underscore. Use curly braces to ensure that variables and literal underscores don't get mixed up.
$oldpath = 'C:\Temp\TestFile.txt'
$date = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
$dirname = [IO.Path]::GetDirectoryName($oldpath)
$basename = [IO.Path]::GetFileNameWithoutExtension($oldpath)
$extension = [IO.Path]::GetExtension($oldpath)
$newpath = "${dirname}\${basename}_${date}_Error${extension}"
Addendum: Your file names should not contain colons. Colons in Windows paths either terminate a drive name or separate the file name from the name of an alternate data stream. Your date format string should rather be something like yyyy-MM-dd HH-mm-ss or yyyy-MM-dd_HH-mm-ss to avoid this pitfall.

Related

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]

PowerShell insert a string into a filename, just before the extension

A general thing that I need to do a lot with files is to create/reference a backup version of a file. e.g. I might want to have a date/time stamp version of a file so that I can reference both the original report and the backup version throughout a script:
$now = $(Get-Date -format "yyyy-MM-dd__HH-mm")
$ReportName = "MyReport-en.csv"
$Backups = "D:\Backups\Reports"
I found that using -join or + always inserted a space before the date/time stamp:
$ReportBackup = "$Backups\$($ReportName -split ".csv")" + "_$now.csv"
$ReportBackup = "$Backups\$($ReportName -split ".csv")" -join "_$now.csv"
I found a way to do this, but it looks feels inefficient with the triple $ and duplication of the .csv
$ReportBackup = "$Backups\$($($ReportName -split ".csv")[0])$_now.csv"
which results in:
$ReportBackup => D:\Backups\Reports\MyReport-en_2022-04-15__07-55.csv
Can you think of simpler/cleaner way to achieve the generic goal of inserting a piece of text before the extension, without the triple $ or duplication of the extension? ("Use a $name = "MyReport-en"" is not so useful because often I am reading a file object and get the name complete with extension.
$now = Get-Date -Format "yyyy-MM-dd__HH-mm"
$reportName = "MyReport-en.csv"
$backups = "D:\Backups\Reports"
$reportBackup = Join-Path $backups $reportName.Replace(".csv","_$now.csv")
$reportBackup
P.S.
There is no risk in using .Replace(), if you know how it works.
This method is case sensitive and replaces all occurrences. In this particular case, we know exactly the name in advance, so we can use this method safely.
The name "My.csvReport-en.csv" is an nonsense, but if the problem explicitly referred to the universal solution "any-name.ext":
$reportName = "My.aSd_Report-en.aSD"
$backups = "D:\Backups\Reports"
$reportBackup = Join-Path $backups ($reportName -replace "(?=\.[^.]+$)", (Get-Date -Format "_yyyy-MM-dd__HH-mm"))
$reportBackup
If you have obtained the report file as FileInfo object by perhaps using Get-Item or Get-ChildItem, you'll find that object has convenient properties you can use to create a new filename with the date included:
# assume $ReportName is a FileInfo object
$Backups = "D:\Backups\Reports"
# I'm creating a new filename using the '-f' Format operator
$NewName = '{0}_{1:yyyy-MM-dd__HH-mm}{2}' -f $ReportName.BaseName, (Get-Date), $ReportName.Extension
$ReportBackup = Join-Path -Path $Backups -ChildPath $NewName
If however $ReportName is just a string that only holds the filename, you can do:
$ReportName = "MyReport-en.csv"
$Backups = "D:\Backups\Reports"
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($ReportName)
$extension = [System.IO.Path]::GetExtension($ReportName)
$NewName = '{0}_{1:yyyy-MM-dd__HH-mm}{2}' -f $baseName, (Get-Date), $extension
$ReportBackup = Join-Path -Path $Backups -ChildPath $NewName
P.S. It is always risky to simply use .Replace() on a filename because that doesn't allow you to anchor the substring to replace, which is needed, because that substring may very well also be part of the name itself.
Also, the string .Replace() method works case-sensitive.
This means that
'My.csvReport-en.csv'.Replace(".csv", "_$(Get-Date -Format 'yyyy-MM-dd__HH-mm').csv")
would fail (returns My_2022-04-15__13-36.csvReport-en_2022-04-15__13-36.csv)
and
'MyReport-en.CSV'.Replace(".csv", "$(Get-Date -Format 'yyyy-MM-dd__HH-mm').csv")
would simply not replace anything because it cannot find the uppercase .CSV
..
If you really want to do this by replacing the extension into a date+extension, go for a more complex case-insensitive regex -replace like:
$ReportName -replace '^(.+)(\.[^.]+)$', "`$1_$(Get-Date -Format 'yyyy-MM-dd__HH-mm')`$2"
Regex details:
^ Assert position at the beginning of the string
( Match the regular expression below and capture its match into backreference number 1
. Match any single character that is not a line break character
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
( Match the regular expression below and capture its match into backreference number 2
\. Match the character “.” literally
[^.] Match any character that is NOT a “.”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
$ Assert position at the end of the string (or before the line break at the end of the string, if any)

How to reformat the date on files in bulk using powershell

I need to format the file name from ...
2639423_3_30_56 PM_9_4_2020.txt
... to ...
2639423-15-30-56-09-04-2020.txt
i.e. Need to change date in Military time format and replace '_' with '-', Also append with “0” for single digit months and single digit days
Please advise I need to perform this in powershell & need to perform this in bulk.
Start by splitting the file name into two parts - the prefix, which remains the same, and the timestamp, which you want to re-format:
$basename = '2639423_3_30_56 PM_9_4_2020'
$prefix,$timestamp = $basename -split '_',2
Next, parse the timestamp according to it's specific format:
$inputFormat = 'h_mm_ss tt_d_M_yyyy'
$parsedDateTime = [datetime]::ParseExact($timestamp,$inputFormat,$null)
Finally convert the parsed [datetime] object back to a string with the desired output format, and then join the prefix and (updated) timestamp together again:
$outputFormat = 'HH-mm-ss-dd-MM-yyyy'
$timestamp = $parsedDateTime.ToString($outputFormat)
# or
$timestamp = Get-Date $parsedDateTime -Format $outputFormat
$newFileName = $prefix,$timestamp -join '-'
# 2639423-15-30-56-09-04-2020
To rename the files in bulk, pipe the files to Rename-Item and use the parameter binder to generate the new name of each file based on the existing name:
Get-ChildItem -Path .\folder\with\files -Filter *.txt |Rename-Item -NewName {
$prefix,$timestamp = $_.BaseName -split '_',2
$parsedDateTime = [datetime]::ParseExact($timestamp, 'h_mm_ss tt_d_M_yyyy', $null)
$timestamp = $parsedDateTime.ToString('HH-mm-ss-dd-MM-yyyy')
$newBaseName = $prefix,$timestamp -join '-'
$newBaseName + $_.Extension
}

Multiple variables in path

I am planning on using the following script by looping through a text file to set variables for the location of the source PDF, and designate the path to create a new folder (with week number) to move the source PDF to.
$pdfSource = 'C:\path\in\text\file'
$newFolder = 'C:\path\to\newfolder\in\text\file'
Get-ChildItem $pdfSource '*.pdf' -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -UFormat %V
$des_path = "C:\path\to\newfolder\$new_folder_name"
if (Test-Path $des_path) {
Move-Item $_.FullName $des_path
} else {
New-Item -ItemType Directory -Path $des_path
Move-Item $_.FullName $des_path
}
}
I can't seem to figure out the syntax for the line below to include the $newFolder path variable along with the existing $new_folder_name I'm creating.
$des_path = "C:\path\to\newfolder\$new_folder_name"
Option-1:
$des_path = "${newFolder}\${new_folder_name}"
Option-2:
$des_path = "${0}\${1}" -f $newFolder, $new_folder_name
Option-3:
$des_path = $newFolder + $new_folder_name
Option-4:
$des_path = Join-Path -Path $newFolder -ChildPath $new_folder_name
There's nothing wrong with your approach to string expansion (interpolation):
$new_folder_name = 'foo' # sample value
$des_path = "C:\path\to\newfolder\$new_folder_name" # use string expansion
yields string literal C:\path\to\newfolder\foo, as expected.
Adam's answer shows you alternatives to constructing file paths, with Join-Path being the most robust and PowerShell-idiomatic, albeit slow.
Another option is to use [IO.Path]::Combine():
[IO.Path]::Combine('C:\path\to\newfolder', $new_folder_name)
The way you calculate the value for $new_folder_name should be problematic if your current culture is not en-US (US-English), but due to a bug actually isn't[1]; either way, it should be simplified:
Instead of:
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -uformat %V
use:
$new_folder_name = Get-Date $_.LastWriteTime -uformat %V
That is, pass $_.LastWriteTime directly to Get-Date, as a [datetime] instance - no detour via a string representation needed.
[1] .ToShortDateString() returns a culture-sensitive string representation, whereas PowerShell typically uses the invariant culture to ensure cross-culture consistency; therefore, if you pass a string to a parameter that accepts a [datetime] instance, it is the invariant culture's formats that should (only) be recognized, not the current culture's. While that is true for functions written in PowerShell, in compiled cmdlets (typically C#-based), the current culture is unexpectedly applied; while this is a bug, a decision was made not to fix it for the sake of backward compatibility - see this GitHub issue

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}_*")