Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping to ForEach-Object in PowerShell [closed]

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.

like image 897
N3cRiL Avatar asked Dec 26 '22 10:12

N3cRiL


2 Answers

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  **
like image 142
CB. Avatar answered Jan 05 '23 16:01

CB.


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
    }
like image 27
MrKWatkins Avatar answered Jan 05 '23 16:01

MrKWatkins