Home > Software design >  Powershell - Set the "LastWriteTime" Property so that it's different for each file in
Powershell - Set the "LastWriteTime" Property so that it's different for each file in

Time:05-28

I'm trying to change the "LastWriteTime" property on multiple files so that they are different using a random number. I have made a test folder with a few .txt files I'm trying to change the property on.

This is what I currently have:

$path = "D:\Test\Test"
$array = @(Get-ChildItem -Path $path)
for($i = 0; $i -le $array.Count; $i  )
{
    $randomNumber = Get-Random -Minimum 10 -Maximum 50
    $array[$i].LastWriteTime = (Get-Date).AddMinutes($randomNumber)
}

The error message states:

"The property 'LastWriteTime' cannot be found on this object."

But once I have run the script/selection in Powershell ISE and it stores the array in memory I can individually change members of the array without dramas using:

$randomNumber = Get-Random -Minimum 10 -Maximum 50
$array[1].LastWriteTime = (Get-Date).AddMinutes($randomNumber)

Can anyone give any pointers as to why I can't change array members using the for loop?

CodePudding user response:

I tested your script on Powershell7 and it's throwing an error for one file out of three. The interesting part is that dates are getting changed as expected for all. Could be a bug with this module.

Another point is that this error is not there if we use For each, instead of For.

$path = "C:\temp"
$array = @(Get-ChildItem -Path $path -Recurse)

Write-Host Before For each
$array | Select Name, LastWriteTime
$array |ForEach-Object {
 $_.LastWriteTime = Get-Date
}

Write-Host After For each
$array | Select Name, LastWriteTime
  • Related