Powershell Simplified Part 8: Accessing the File System

With Powershell you can manipulate the file system easily,

$path = "c:\program files\internet explorer"

# get all the files in a folder and subfolders
$dlls = get-childitem $path -recurse

# filter based on file extension
$dlls = get-childitem $path -filter *.dll -recurse

# count the total number of files
$count = (get-childitem $path -filter *.dll -recurse).count

# for multiple filders use 'include' and 'exclude'
$dlls = get-childitem $path -include *.dll, *.exe -recurse

# filder based on other criteria
$dlls = get-childitem $path -filter *.dll -recurse | where-object { $_.length -gt 150KB }

foreach ($dll in $dlls) { write-host $dll }

Use the PSIsContainer to determine if a directory item is a file or a subdirectory.

# find subdirs only
$dirs = get-childitem $path -recurse | where-object { $_.PSIsContainer }

# find files only
$files = get-childitem $path -recurse | where-object { $_.PSIsContainer -eq $false}

We can get detailed information about a file,

get-item $env:windir\explorer.exe | select-object *   # view individual file properties
$file = get-item $env:windir\explorer.exe             # get individual file properties
write-host $file.versioninfo.productversion

Now let’s do some basic file/folder operations,

$path = "c:\program files\internet explorer\signup\test"

# check if a directory exists 
if (-not (test-path $path)) { write-host "Invalid path" }

# create a directory
new-item $path -itemtype directory

# create a file
$filepath = [System.IO.Path]::Combine($path, "test.txt")
new-item $filepath -itemtype file

# write to the file
add-content $filepath "<root>"
add-content $filepath "</root>"

# read the file contents
$content = get-content $filepath
write-host $content

# rename the file
rename-item $filepath "test.xml"

# change a file property
$filepath = [System.IO.Path]::Combine($path, "test.xml")
$file = get-item $filepath
$file.isreadonly = $true         # change to read-only

# delete a file
remove-item $filepath –force     # use 'force' for write-protected files 

# delete a directory
remove-item $path\* –recurse     # delete all files and subdirectories
remove-item $path -recurse       # delete the directory and all files and subdirectories

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Powershell Simplified Part 8: Accessing the File System

  1. Pingback: Powershell Simplified Series « I.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: