Functions

When you use a function like .count the value can be zero if it gets an improper value. Let's say you want to find out how many files or directories a path has and it has none how can you trap that?
Normally you would specify the following:

$list=(dir c:\)
$list.count

What if you specify a directory that does not excist:
$list=(dir *gamalaga)

If you count that with .count it will return nothing and would be better than to return a zero

So you would get around this problem by adding an @ symbol to it:

@(Dir *gamalaga).count

How about a function that colours all .doc files yellow in a directory: You should first run the first line and then you can copy and past all the rest in it and give an enter to come out of interactive mode
Filter ColorDOC 
{
  # Store the old color first
  $oldcolor = $host.ui.rawui.ForegroundColor
  # The current pipeline element is in $_
  # If the name ends in ".doc", change 
  # the foreground color to red:
  If ($_.name.toLower().endsWith(".doc")) {
    $host.ui.Rawui.ForegroundColor = "yellow"
  } Else {
    # Otherwise, use the normal foreground color:
    $host.ui.Rawui.ForegroundColor = $oldcolor
  }
  # Output element
  $_
  # Finally, restore the old foreground color:
  $host.ui.Rawui.ForegroundColor = $oldcolor
}

Now you can give DIR | ColorDOC
You will then see all the word documents in yellow

To see what this function is made of type:

$function:ColorDOC

Okay that worked but if you apply it on a directory that has a lot of files and folders it is rather slow and instead you should define a filter to see it realtime
Just change function with filter and see the difference between a filter and a function

Unlike most other script languages,
PowerShell functions that you define inside your script must be at the beginning of your script.

On Me

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License