Get Files modified after a certain date

Hi,
I try to get all files of a folder which have been modified after a certain date. I know this question has already been asked before, and I found several solutions / proposals, but none worked. And concerning the particular behaviour I encountered, I found nothing, maybe someone can help?

To test, I have a folder with three files, two with lmd in 07/24, one with 09/24. I run the same program, once to find files modified after 01-07-24 (locale is Germany, so dd-mm-yy) and it works, as expected the three files are found. I run it again with the date of 01-08-24 and the output becomes completely weird.

Here the program:

$sourceFolder = "d:\test"
#sourceFolder contains 3 files, 2 with date 07/24, one with date 09/24

Function List-Files{
	
	$fn = Get-ChildItem $sourceFolder -File | ? LastWriteTime -gt $ld 
	$sourceFiles=$fn.FullName
	Write-Host $sourceFiles.Length
	Write-Host $fn.Length

	if($sourceFiles -eq $null){
		Write-Host "null"
		exit
	}

	for($k=0; $k -lt $sourceFiles.Length; $k++){
		Write-Host $sourceFiles[$k]
	}
	Write-Host "************************"
}

$ld = Get-Date("01-07-24")
List-Files
$ld = Get-Date("01-08-24")
List-Files


and here the output

3
3
D:\test\file_0107.txt
D:\test\file_1307.txt
D:\test\file_1509.txt
************************
21
657
D
:
\
t
e
s
t
\
f
i
l
e
_
1
5
0
9
.
t
x
t
************************

Any idea?
Thanks!

When you search for files with the date 01-08-24 you’re getting only one result. So the Length property is the number of characters in the string, rather than the number of elements in an array. So your for loop is printing each character in the string, one-by-one.

If you want to keep your code as it is, declare $sourceFiles to be of type array.

[array]$sourceFiles = $fn.FullName

You don’t need to loop over the files to print them to the console though. You can just return them with:

$sourceFiles

A couple of other pointers:

Avoid using aliases such as ? in scripts and code that you’re sharing with other people.

It’s considered a PowerShell best practice to place $null on the left as placing it on the right doesn’t always yield the expected result:

1 Like

@matt-bloomfield : Thank for the reply, explanations and hints! Works.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.