I'm trying to get it to recurse through a directory, and include only .pdf
files. Then return the 3 most recently modified .pdf
's, and stick each of their (full) filenames into their respective variables.
Here's my code so far -
$Directory="C:\PDFs"
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object
{
Write-Host -FilePath $_.fullname
}
However, when I run the script, it asks me to provide parameters for the ForEach portion of the script - Which leaves me to conclude that either the command isn't piping the way it should, or the command isn't being using the command properly.
Remove the enter
after the foreach-object
:
$Directory="C:\PDFs"
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object {
Write-Host -FilePath $_.fullname }
There's a typo in your code:
** Get-ChildItem =path **
It's probably because your script block for the ForEach-Object is on a new line. In PowerShell you need to use the backtick character (`) to tell PowerShell a command continues to the next line. Try this:
$Directory="C:\PDFs"
Get-ChildItem -path $Directory -recurse -include *.pdf | sort-object -Property LastWriteTime -Descending | select-object -First 3 | ForEach-Object `
{
Write-Host -FilePath $_.fullname
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With