Tuesday, February 26, 2013

Powershell Script DIY: Creating Objects



An essential part of working with Powershell is the end result.  While it is all well and good to read the output on the screen with the write-output command, it’s easier to just dump it into a log or a text file for later analysis.   As usual we start with Set-Location:

Set-Location “c:\Temp

I like to start by defining a variable that will act as a placeholder for this file name.  This has two advantages, it shortens the amount of text that is gunking up your script, and you will only need to change one string to effect the entire script should you choose to change the file name:

$foo = "foo.txt

With the filename defined by a variable it is now time to actually create the file itself.  This is done with the New-Item command:

New-Item

The new Item’s name needs to be clearly defined directly after the command, and you must encapsulate it in quotations.  If you so choose, you can opt to just name the actual file name if you wish, Just replace the variable  “$foo” with “foo.txt.”:

                New-Item "$foo"

After you Define the file name the –itemType operator must be used to tell Powershell what exactly it is you want to create:

New-Item "$foo" –ItemType

As we are creating “foo.txt” It lends to reason that we would use the File object type:

New-Item "$foo" -itemType File

This is what your script should look like so far:

Set-Location “c:\Temp
$foo = "foo.txt
New-Item "$foo" -itemType File

With a few variations New-Item can also be used to create directories.  As with creating a file, we first define our variable:

                $FooFolder = “FooFiles”

And we use the  New-Item command to create the object:

                New-Item “$FooFolder”

Instead of using the File object type we use Directory:

                New-Item “$FooFolder” –ItemType Directory

Giving us this:

Set-Location “c:\Temp
$FooFolder = “FooFiles”
New-Item “$FooFolder” –ItemType Directory

Amazing! The fundamentals are there to create your folder, and then create the file within the folder:

Set-Location “c:\Temp
$FooFolder = “FooFiles”
New-Item “$FooFolder” –ItemType Directory
Set-Location $FooFolder
$foo = "foo.txt
New-Item "$foo" -itemType File

As usual, Please provide me with feedback; we only learn by working together! Also a +1/Like/Tweet/LinkIn always helps


Sources: Myself

No comments:

Post a Comment