I have a folder with files with similar names. For example, one of them is called "(15.02.22 11-55-45 - timeshift 145544 s) News (TVP Wilno HD).ts". In this case, on February 15, 2022, at 11:55:45, I ordered a program that started 145,544 seconds earlier to be saved. I want to change the date and time of the recording request to the broadcast date and time of the program I ordered to be saved, and do the same for each file in the folder, and I've tried to use this script to do so:
$folderPath = "D:\test"
$files = Get-ChildItem -Path $folderPath -Filter "*.ts"
foreach ($file in $files)
{
$fileName = $file.Name
$startTimeSeconds = $fileName.Substring($fileName.IndexOf("timeshift") 10, 6)
$startTime = [datetime]::ParseExact($fileName.Substring(1, 18), "dd.MM.yy HH-mm-ss", $null)
$startTime = $startTime.AddSeconds(-$startTimeSeconds)
$newFileName = "(" $startTime.ToString("dd.MM.yy HH-mm-ss") ") " $fileName.Substring($fileName.IndexOf(")") 2)
Rename-Item $file.FullName -NewName $newFilename
}
The following errors were displayed upon using it:
Exception calling "ParseExact" with "3" argument(s): "Ciąg nie został rozpoznany jako prawidłowy element DateTime."
At line:7 char:5
$startTime = [datetime]::ParseExact($fileName.Substring(1, 18), " ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : FormatException
Method invocation failed because [System.Object[]] does not contain a method named 'AddSeconds'.
At line:8 char:5
$startTime = $startTime.AddSeconds(-$startTimeSeconds)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "ToString" and the argument count: "1".
At line:9 char:5
$newFileName = "(" $startTime.ToString("dd.MM.yy HH-mm-ss") " ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodException
FullyQualifiedErrorId : MethodCountCouldNotFindBest
The filename was replaced to "() Wiadomosci (TVP Wilno HD).ts".
What script should I use to change the date and time of the recording request to the broadcast date and time of the program I ordered to be saved, and do the same for each file in the folder? The resulting name of the above file should be "(13.02.22 19-30-00) Wiadomosci (TVP Wilno HD).ts".
CodePudding user response:
Your substring operation is the problem. If the filename is "(15.02.22 11-55-45 - timeshift 145544 s) News (TVP Wilno HD).ts" you need substring(1,17), not 1,18. The first argument is the position of the most left character of your substring, starting with 0. The second is the length not the position of the most right character as you might have thought, and this case 17.