Friday, March 2, 2018

Working with Files and Folders using PowerShell

In this article I’ll explain various PowerShell commands to perform File/Directory operations.

Get-ChildItem

You can use ‘Get-ChildItem’ command to get list of all the files and folder of given path.

Get-ChildItem -Path C:\PowerShell 

You can use below commands to list either files or folders only of given path

Get-ChildItem -Path C:\PowerShell -File

Get-ChildItem -Path C:\PowerShell -Directory

You can use below command to filter files and folders as per your requirement.

Get-ChildItem -Path C:\PowerShell -Filter *.pdf



You can you below command to list all the files and folders of give path recursively.

Get-ChildItem -Path C:\PowerShell -Recurse




You can also use Include or Exclude parameters with Get-ChildItem command to filter files.

Get-ChildItem -Path C:\PowerShell -Include "*.pdf" -Exclude "s*.PDF" –Recurse


New-Item
You can use ‘New-Item’ command to create new file or directory.

New-Item -Type File "C:\PowerShell\First1.txt"

New-Item -Type Directory "C:\PowerShell\MyFolder"




Copy-Item

You can use Copy-Item command to copy files and directories.

Copy-Item First1.txt Mitesh\First2.txt
Get-ChildItem -Path C:\PowerShell\Mitesh


Remove-Item

You can use Remove-Item command to delete files and directories.

Remove-Item c:\PowerShell\Mitesh\First2.txt
Get-ChildItem -Path C:\PowerShell\Mitesh


Rename-Item

You can use ‘Rename-Item’ command to rename file and directories.

Rename-Item First1.txt First3.txt
Get-ChildItem -Path C:\PowerShell\Mitesh




Move-Item
You can use ‘Move-Item’ command to move files and directories.

Move-Item c:\PowerShell\First3.txt C:\PowerShell\Mitesh\First1.txt
Get-ChildItem C:\PowerShell\Mitesh



Summary

Alias
Cmdlet
Description
dir
Get-ChildItem
List files and folders
ni
New-Item
Create new files and folders
copy
Copy-Item
Copy files and folders
del/rmdir
Remove-Item
Delete files and folders
ren
Rename-Item
Rename files and folders
move
Move-Item
Move files and folders


I hope you now have some basic understanding about PowerShell file and folder cmdlets to play around it. 

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

Reference –

See Also –

No comments:

Post a Comment