I have a script where I need to retrieve a date string from a CSV column to compare it with a file date value (LastWriteTime).
When I run the script, I get the error outlined in the title of this post.
This the portion of the script where I create the CSV file and update the columns with the values and try to compare date value from the .CSV file with system date value.
I tried to convert the Import-Csv output stored in the variable to a date value but that throws an error, obviously because the variable is array object and not a string.
$lastexecutedRuntime.GetType()
[DateTime]::ParseExact($lastexecutedRuntime, 'MM/dd/yyyy HH:mm:ss' $null)
Output:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
I appreciate your help. This is the script generating the error:
Could not compare "05/02/2024 09:47:26" to "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData". Error: "Cannot convert
the "System.Object[]" value of type "System.Object[]" to type "System.DateTime"."
At line:124 char:8
+ If($_.LastWriteTime -le $lastexecutedRuntime){
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : ComparisonFailure
This is the script I tried:
#CREATE CSV FILE
$csvfilePath = DIR\Mcsvfile.csv
New-Item -Path $csvfilePath
#CREATE CSV FILE COLUMNS
Add-Content -Path $csvfilePath -Value "StartTime, EndTime, Message"
$startTime = Get-Date (Get-Date -Format "MM/dd/yyyy HH:mm:ss") -Format "MM/dd/yyyy HH:mm:ss"
#FOR TESTING PURPOSES
$endTime = Get-Date (Get-Date -Format "MM/dd/yyyy HH:mm:ss") -Format "MM/dd/yyyy HH:mm:ss"
#LOG TIMESTAMP IN THE CSV FILE
Add-Content -Path $csvfilePath -Value "$startTime, $endTime, Script completed"
#SORTING THE COLUMN BY DATE IN DESCENDING ORDER AND GETTING THE RECENT DATE VALUE
$lastexecutedRuntime = Import-Csv -Path $csvfilePath | Sort-Object -Property EndTime -Descending | where-Object { $_."EndTime" -as [DateTime]} | Format-Table -HideTableHeaders EndTime | Select-Object -First 3
Get-ChildItem $backupDir| ForEach-Object {
If($_.LastWriteTime -le $lastexecutedRuntime){
# CODE HERE
}else{
# CODE HERE
}
}