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

\$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

# 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```