Powershell tips, managing files

A tip, if you want to move all files from subdirectories up to a common hierarchy:

Get-ChildItem -Path source -Recurse -File | Move-Item -Destination dest

If you want to clear out the empty directories adterwards:

Get-ChildItem -Path source -Recurse -Directory | Remove-Item

Another simple one-liner to remove files older than a number of days:

Get-ChildItem -Path "C:\temp" -Recurse -File | Where CreationTime -lt (Get-Date).AddDays(-2) | Remove-Item -Force

If the file is recently copied, creationtime (“date modified” in Windows) and lastwritetime (“date created” in Windows) might differ.

Use the one suitable for the situation.

Another one, similar:

Get-ChildItem d:\tmp\* | Where {$_.PsIsContainer} | foreach-object { Get-ChildItem $_ -Recurse -ErrorAction SilentlyContinue | Where {!$_.PsIsContainer} | Select Name,DirectoryName, LastWriteTime, Mode | Sort LastWriteTime -descending | select -first 1}

Another one, if you need to do a search for files in different directories and want the full path in return

(get-childitem -path \\servername\share -force -filter "yourfile.ini" -recurse).fullname

More articles