question

ChristopherJack-1763 avatar image
0 Votes"
ChristopherJack-1763 asked IanXue-MSFT edited

Loop using Where-Object

Hi I am using the following code to build a date array

 ##CHECK FOR DATES
 if($dayofweek -eq "Monday")
 {
     for($i=0;$i -le 3; $i++)
     {
         $Temp = (Get-date).AddDays(-$i)
         $Datearray += Get-Date $Temp -Format yyyy-MM-dd
     }
 }
 else 
 {
     $Datearray += Get-Date $Temp -Format yyyy-MM-dd
 }

I then have

 $OrderInfo = $file | Where-Object {$_."Issue Date" -eq $td } |Select-Object "Order Number"

Can I add a loop into the Where-Object clause? I only want to pull the order numbers based on the datearray

Thanks for help?

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
1 Vote"
IanXue-MSFT answered IanXue-MSFT edited

Hi,

If $file is imported from a csv file you can do it like this

 $dayofweek = (Get-Date).DayOfWeek
 $Datearray = @()
 if($dayofweek -eq "Monday")
 {
     for($i=0;$i -le 3; $i++)
     {
         $Datearray += (Get-date).AddDays(-$i).ToString('yyyy-MM-dd')
     }
 }
 else 
 {
     $Datearray += Get-Date -Format yyyy-MM-dd
 }
 $OrderInfo = $file | Where-Object { $_."Issue Date" -in $Datearray } | Select-Object "Order Number"

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
1 Vote"
RichMatheisen-8856 answered

No, you can't. But it isn't necessary, either.

First, your 1st code example needs a bit of modification (declaring DateArray so line 12 creates an array, removing $Temp from line 12 because it isn't in scope). The 2nd code example uses $td which isn't present -- is it safe to assume that should be "$DateArray"?

Try this (it uses a PSCustomObject in place of your file, just for testing purposes):

 $dayofweek = 'Friday'
 [array]$Datearray = @()
 if($dayofweek -eq "Monday")
  {
      for($i=0;$i -le 3; $i++)
      {
          $Temp = (Get-date).AddDays(-$i)
          $Datearray += Get-Date $Temp -Format yyyy-MM-dd
      }
  }
  else 
  {
      $Datearray += Get-Date -Format yyyy-MM-dd
  }
 $file = [PSCustomObject]@{
     "Issue Date" = "2021-03-29"
     "Order Number" = 1
 }
 $OrderInfo = $file | 
     Where-Object {$dateArray -contains $_."Issue Date"} |
         Select-Object "Order Number"
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.