Given below are some tips from my scratchpad on working with files and directories in PowerShell. These are just basic tips and by no means exhaustive. Check out the book “Windows PowerShell in Action” by Bruce Payette, an excellent book on PowerShell authored by the lead developer of the language.
# Directory Listing
PS C:\POWERSHELL> dir
Directory: C:\POWERSHELL
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 12/29/2010 12:01 PM 1929 PowerShellTips.ps1
-a--- 12/29/2010 10:40 AM 50 test1.txt
# Number of files in a directory
PS C:\POWERSHELL> (dir).count
3
PS C:\POWERSHELL> (dir).length
3
# Number of files matching a pattern
PS C:\POWERSHELL> (dir *.ps1).count
1
# Number of lines in a file
PS C:\POWERSHELL> ${C:PowerShellTips.ps1}.length
141
PS C:\POWERSHELL> (Get-Content .\PowerShellTips.ps1).length
141
PS C:\POWERSHELL> (Get-Content .\PowerShellTips.ps1).count
141
# Largest file in a directory
PS C:\POWERSHELL> dir | Sort-Object -property length -Descending | Select-Object -first 1 | foreach-object {$_.length}
7157724
# Files created in the last 31 days
PS C:\POWERSHELL> dir | ?{$_.lastwritetime -ge ([datetime]::Now).AddDays(-31)} | %{"I am " + $_.Name}
I am PowerShellTips.ps1
I am test1.txt
PS C:\POWERSHELL> dir | %{if ($_.lastwritetime -ge ([datetime]::Now).AddDays(-31)) {"I am " + $_.Name}}
I am PowerShellTips.ps1
I am test1.txt
(Visited 40 times, 1 visits today)