Not able to Insert DateTime Values in DateTime Declared Empty Array!!!

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Martin Nielsen Martin Nielsen 1 year, 4 months ago.

  • Author
  • #26478
    Profile photo of Devesh Srivastava.
    Devesh Srivastava.

    If ($BCODE -LIKE "16")
    $TS1= [datetime]::ParseExact($tcode,"yyyyMMddhhmmss", $null)

    [datetime[]]$a = @()

    $a[$i]+= ,$TS1
    Write-host $a[$i]
    While($i -le $TS3)
    $tcode contains the string value in yyyyMMddhhmmss format. So, I am converting that value in to datetime and then would store all the values in an array and then would sort the array to get the latest timestamp.

    I am trying to save every DateTime value that is coming through $TS1 in an Array every time the loop runs. Its giving the error below:

    Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.DateTime".
    At C:\Users\c0srivastavad\Desktop\Untitled2.ps1:47 char:2
    + $a[$i]+= ,$TS1

    Please let me know where I am making the mistake. I am learning Powershell along the way so dont have much knowledge.


  • #26480
    Profile photo of Peter Jurgens
    Peter Jurgens

    The error is because you have a comma just in front of the $TS1 in the line where you're trying to add the value to your array. since you've put a comma in front, powershell sees this as a collection rather than a single datetime object. Also, you should choose to specify array indexes by iterating through values of $i, OR use the += operator when adding values to an array, otherwise you could end up combining specific values. Simple example of the differences:

    $a = @()
    For($b in $(1..5)){


    For($i=0;$i -lt $a.count;$i++){

    What you're trying to achieve can be done like this (assuming you have an array of strings matching your specific datetime format):

    ForEach($itm in $TS1){
    $array | Sort-Object
  • #26488
    Profile photo of Martin Nielsen
    Martin Nielsen

    Adding to an array is a quite expensive operation as PowerShell arrays are read-only, which means it has to recreate an array with a new object on every operation. It's simpler to just catch the output.

    $array = ForEach($itm in $TS1){

    Try it yourself.

    Measure-Command {
        $array = @()
        foreach($i in 1..10000) {
            $array += $i
    } | Select-Object TotalMilliseconds
    Measure-Command { 
        $array = foreach($i in 1..10000) {
    } | Select-Object TotalMilliseconds

You must be logged in to reply to this topic.