Piping to ForEach-Object in PowerShell [closed] Piping to ForEach-Object in PowerShell [closed] powershell powershell

Piping to ForEach-Object in PowerShell [closed]


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    }