Saturday, March 17, 2018

Advanced Files and Folders techniques with PowerShell


In my previous article, I explained basic files and folder PowerShell cmdlets. In this article I’ll show some advanced features and techniques to work with Files and Folders using PowerShell.

Get-Member

When you execute Get-ChildItem cmdlets it will display only default columns not all. You can use below command to check how many columns you can display with Get-ChildItem or any other command.

Get-ChildItem | Get-Member |more



The Get-Member command will list all the Methods and Properties of given command or object. If you want to get Properties of given command or object use below command.

Get-ChildItem | Get-Member -MemberType Properties


If you want to get only Methods of given command or object use below command.

Get-ChildItem | Get-Member -MemberType Method


Get-ChildItem

As you know via Get-Member cmdlets you can find all the methods and properties of given command. So when you execute Get-ChildItem cmdlets it will display all the default columns but you can customize it via selecting specific columns to display. You can customize number of columns by specifying Select-Object or Select with pipe line.

Get-ChildItem -Path c:\Powershell | select Name, Length


You can also include other columns which are not displayed in default result. I included IsReadOnly, CreationTime, BaseName columns in below command.

Get-ChildItem | select Name, IsReadOnly, CreationTime, BaseName



You can also sort list of files and directories based on column names using Sort-Object or Sort cmdlets.

Get-ChildItem | select Name, IsReadOnly, CreationTime, Length | Sort Length, CreationTime -Descending 


You can use below command to count total files or folders recursively.

(Get-ChildItem -File -Recurse).count
(Get-ChildItem -Directory -Recurse).count



You can use Where cmdlets to search files or folders on specific conditions.

Get-ChildItem -file | where {$_.Name -eq "app.pdf" -or $_.Name -eq "Test.doc"} | select Name, Length, LastWriteTime | sort Length -Descending


You can use below command to get list of all the specified files and rename it via ForEach object.

Get-ChildItem -File -Filter *.PDF | foreach {Rename-Item $_.FullName -NewName ($_.BaseName + 1 + $_.Extension)}
Get-ChildItem -File -Filter *.PDF



The similar way you can use cmdlets like Move-Item, Copy-Item, Remove-Item, New-Item etc. along with Get-ChildItem to get list of files and folders and execute cmdlets on the fly.

I hope you have now some understanding on advanced techniques to list files and folders, selecting extra columns, sorting and counting total files and folders and loop through each files in foreach loop to perform some actions.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See Also –

No comments:

Post a Comment