PowerShell bits and pieces - Search for a file

I am taking some notes while discovering how to do simple things in PowerShell. What better place to store these than this blog?

Searching for a file:

Assume, We are searching for Remote Desktop Client File. I know that it's called mstsc.exe (and in fact I have a pretty good idea where it is) but assuming we don't have a clue about it's location. We would want to go to root of the drive and start searching from there. In DOS, I would run the following from the root of the drive

dir /s mstsc.exe

In PowerShell:

gci -recurse -filter mstsc.exe -EA SilentlyContinue|ft directory,name -auto

If you are not at root, add c:\

gci c:\ -recurse -filter mstsc.exe -EA SilentlyContinue|ft directory,name -auto

gci is short for Get-ChildItem (or ls or dir)

-recurse is like /s in DOS; goes recursively into subdirectories

-filter is very efficient because provider filters the results before they are passed to powershell

-EA is short for ErrorAction, which tells PowerShell what to do when there is an error. You are likely to hit access denied errors when searching. Options include

  • SilentlyContinue. Suppresses the error message and continues executing the command.
  • Continue. Displays the error message and continues executing the command. "Continue" is the default value.
  • Inquire. Displays the error message and prompts you for confirmation before continuing execution. This value is rarely used.
  • Stop. Displays the error message and stops executing the command.

Then we are piping results to FormatTable using column names and telling it to Auto Size

A couple of notes on this...

1) If the file we are searching for may be hidden, then we would want to add -force parameter when searching.

2) ErrorAction is a common parameter to PowerShell commands; not specific to Get-ChildItem. If you would like to get the explanation for a parameter of Get-ChildItem; you could type

get-help gci -parameter force

If you wanted to find out which other commands have "force" parameter; you would omit the command name like this:

get-help * -parameter force

None of these would work for ErrorAction as it's a common parameter. So, you would simply type

get-help ErrorAction

and you will notice that one of the help files is about_CommonParameters

get-help about_CommonParameters -detailed

That prints the information about ErrorAction I copied above.
Post a Comment