Wednesday, February 13, 2013

Powershell Script DIY: Use a Variable to Refer to a User System Folder


     One of the problems I run into when writing scripts is the confusion when addressing dynamic and system specific folders.  By dynamic folders, I mean the ones that are specific to each user such as the desktop, my documents, app data, ect.  As you may well know, I like to work with variables as they tend to simplify things when used properly.  We start by defining our variable with the "$":

$desktop =
Next we are going to tack on the [Environment] definition this is going to state that the value is indeed an environmental variable.

$desktop = [Environment]::

You may notice the :: after [Environment].  This is necessary to signify that we are going to specify a part of the environment, particularly, the path of the desktop directory.  We are going to do this with GetFolderPath.

$desktop = [Environment]::GetFolderPath

We now specify what variable, for our purposes we are of course gong to use the desktop.  This needs to be encapsulated in parentheses, and in double quotations to treat it like text.

$desktop = [Environment]::GetFolderPath("Desktop")

Now that you have the complete command, what exactly does it do? It starts by saying The Variable ($) Desktop is equal to (=) the Desktop Path ("Desktop") which you can get the path from (::GetFolderPath)
the working environment ([Envirment]).

This operation can be done using the following folders, and remember they must be typed exactly as you see here:

Desktop
Programs
Personal
MyDocuments
Favorites
Startup
Recent
SendTo
StartMenu
MyMusic
DesktopDirectory
MyComputer
Templates
ApplicationData
LocalApplicationData
InternetCache
Cookies
History
CommonApplicationData
System
ProgramFiles
MyPictures
CommonProgramFiles

As always I fully encourage comments.  There is always a better way to do something

No comments:

Post a Comment