Files and Folders (PowerShell)

Here’s some examples of how you can work with Files and Folders in Windows PowerShell

Move Files – using Move-Item cmdlet.

Move-Item “C:Folder 1Read.txt” “C:Folder 1Folder 2a”

If the file already exists, you’ll get an error. So use the -force switch.

Move-Item -force “C:Folder 1Read.txt” “C:Folder 1Folder 2a”

Copy Files – using the Copy-Item cmdlet.

Copy-Item “C:Folder 1Read.txt” “C:Folder 1Folder 2a”

Copy all files in a folder to another folder (but not copy any folders):

$files = Get-ChildItem | ? {$_.PSIsContainer -eq $False}
Copy-Item $files “C:Folder 1Folder 2b”

If the files already exist in the folder you’ll get an access denied error. Overwrite those files by using the -force switch:

Copy-Item -force $files “C:Folder 1Folder 2b”

Delete Files – using the Remove-Item cmdlet.

Remove-Item ‘C:Folder 1Folder 2aRead.txt’

List all txt files in the current directory

dir -filter *.txt

List all txt files in the folder path

dir -filter *.txt -recurse

Check a folder to see if there are any files in that folder.

$a = Get-ChildItem “C:Test Folder”
if ($a.Count)
{“C:Scripts contains files”}
else
{“C:Scripts does not contain files”}

Show Hidden Files

Get-ChildItem -force | ? {$_.PSIsContainer -eq $False -and $_.Attributes -match “Hidden”}

Search for File (this example will look for a file called old.txt in the current folder path)

Get-ChildItem -filter old.txt –recurse

Last Modified Date

$files = gci -filter old.txt
$files.lastwritetime

Last Accessed Date

$files = gci -filter old.txt
$files.lastaccesstime

Check the Archive Bit (Has File Been Backed Up? This will check the “Attributes” property in $files to see if it contains “Archive”)

$files | Where-Object {$_.Attributes -contains “Archive”}

Perform a directory listing and check all files for the Archive Bit.

dir -recurse | Where-Object {$_.Attributes -contains “Archive”}
dir -recurse | Where-Object {$_.Mode -contains “-a—”}

How many Files in a Folder?

(dir | Where-Object {$_.PSiSContainer -eq $False}).count

Count the number of files in the current folder.

[int]([object[]](dir *.*)).length

Count the number of XML files in the current folder.

[int]([object[]](dir *.xml)).length

Count the number of XML files in the C:Management-Packs-XML folder.

[int]([object[]](dir C:Management-Packs-XML*.xml)).length

How many Files in all Folders?

(dir -recurse | Where-Object {$_.PSiSContainer -eq $False}).count

How many Sub-Folders in a the current path?

(dir -recurse | Where-Object {$_.PSiSContainer -eq $True}).count

 

 

 
Comments

No comments yet.

Leave a Reply