I have a script where I need to retrieve a date string from csv column to compare it with a file date value (LastWriteTime). When I run the script, I get the error outlined in the subject line of this thread.
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 CSV FILE with system date value.
I tried to convert the Import-Csv output stored in the variable to a date value but that throw 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)
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:
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 = DIRMcsvfile.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 CULUMN 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
}
}
Mounir Farid is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.