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:


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

Friday, February 15, 2013

A word on standardization for this blog

Greetings!  I feel it is time for me to set down a set of standards for my blog so that none get confused.  I have renamed and reformatted all of my blog entries for the sake of standardization. 

11.       All Powershell specific posts will be labeled as “Powershell Script DYI” for Search Engine Optimization.

22.       All variables and filenames will be some variation of “Foo.”  “Foo” is an industry standard catch all term describing a generic file.  I use this for the sake of standardization

33.       All IP addresses will be  This is so that if you do use my scripts, you do not accidentally get into a protected network.

44.       The folder we work out of will always be c:\Temp. 

55.       All usernames will be either John Reginald Doe or Jane Renee Doe

66.       All commands / code will be indented and Italicized and all variables/objects will be bolded.

Thank You & Have an excellent day!

Wednesday, February 13, 2013

Powershell Script DIY:Naming Conventions

Powershell Script DIY: Naming Conventions

Greetings and welcome to “Help! I’m stuck in my Powershell!”  Today we address an important issue that plagues all Powershell scripter’s: The dreaded “I have 44 different script files named some variation of "Foo.PS1!” A naming convention is a documented system of naming files, variables, folders,   ect.  Naming convention in a production environment is paramount as it helps reduce confusion when you have multiple scripts you are working on.  Here I will help you with a Simple naming convention for a file, a folder, and a script. But first, I will define what can, and cannot be used as an Object name in windows:

File / folder limitations & why they are in place:

/  and \
used for directory paths
? and *
Used as wildcards
< and  >
Used for system functions
Used to define a port when referencing a port location
Used to string commands together
Used to define a path or file that contains spaces
Any name over 255 characters long (Fat32) or 256 characters long (NTFS)
The maximum file name can only be 260 characters long, including extension.
Space at the end of a name
A space indicates a separation, while allowed inside a name it creates system conflicts at the end
Period at the end of a name
A period indicates a separation between the name and the extension
com1, com2, com3, com4, com5, com6, com7, com8, com9, lpt1, lpt2, lpt3, lpt4, lpt5, lpt6, lpt7, lpt8, lpt9, con, nul, and prn
Reserved by windows for system use
(Source: http://support.grouplogic.com/?p=1607)

Now that we have defined what you cannot do, let’s look at some of the things you can use in the naming convention:
Computer name
Server name
Physical location
Version number
Group Name
Data Source

FILE Naming Conventions:
When creating a file naming convention you must first define the intent of the file.  Our purpose is to house source data from our source “foo”:


I prefer to separate portions of my name with either – or _: 


The source of our data is Server1:


I like to include the date-time group:


And the important thing to add at the end is the extension.  An extension is not necessary for Powershell to pull data; rather it is useful for debugging.  I prefer to use the *.log for source data:


So we used “Intent_Source_Date_Time.extention” Remember, this is only an example, and you do not need to follow this example to the letter.

Folder Naming Conventions:
Folders are a slightly different case as their purpous and function are fundamentally different.  With that being said, instead of starting with “intent,” we will start with “contains.”  Defining what your folder contains is important, as it helps navigation to the files it contains.  This example will use “Foo source data files”:

Foo source data files

If this is a sub directory, you can append the group, or variable that differentiates those files contained within from the rest of the files:

Foo source data files_Server1

Additional items can be added at the end, but remember that the folder name should generally describe everything it contains.

Script Naming Conventions
As scripts are inherently files, they can be treated as such when naming them, with a few caveats:  The file name should start with its purpose and not what it contains, and you should always end it with a version number.  To start we will use fooscript to describe its purpose:


It is a good idea to follow this with the author’s initials if you are working in a multi-admin environment:


Instead of a date I prefer using a version number (I will explain more on this later on in the post):


If this is a work in progress you can append “Working” after this, while it is not required, it is a good idea if you work on a shared system, or the script resides on a network drive:


Finally, you should append the extention particular to your scripting language.  We use Powershell here, so the extension is “*.PS1”:


 The version number is an unofficial industry number that is delimited by periods used to identify the progress of the script.  Normally, there are 3 values:


The first number, “1” indicates major changes.  This should only change if there is an major revision to the code.  The second number, “2” refers to Incremental change.  This means an added minor feature, or changing out a block of code for a more effective block without fundamentally altering the function of the script.  The final number, “3” indicates a bug fix, i.e. if the script crashes under specific circumstances.

As always, I encourage commenting & sharing.  It does no one good if we keep knowledge and resources to our self! 

Sources: http://support.grouplogic.com/?p=1607

Powershell Script DIY: removing items based on date

Powershell Script DIY: removing items based on date
Warning: This DYI is potentially damaging, be absolutely sure you want to do this and you test it in a sandbox first.
With that being said, today we are going to remove items from a directory basted on their date.  The first thing we are going to do is define the directory.  We start with “dir”:


We need to define the location:

                Get-ChildItem 'C:\Temp\'

Now we use the –recurse operator.  Recurse is short for recursive which, plainly put means serch everything in subdirectories too.  So if you don’t want it to do this, skip this next step:

                Get-ChildItem 'C:\Temp\'-recurse 

Now that we have defined the scope of the commands, we need to use the pipe operator in order to tell it “now that you have gotten c:\Temp AND everything in every folder it contains do this”:

                Get-ChildItem 'C:\Temp\'-recurse  |

In order to diferenciate between files, we need to give Powershell a conditional statement.  We begin this with “where”:

                Get-ChildItem 'C:\Temp\'-recurse  | where

When you use a conditional statement, such as foreach-Item or Where, we need to encapsulate the statement itself in curley brackets {}:

                Get-ChildItem 'C:\Temp\'-recurse  | where {}

Because we want to remove old items we are going to use the get-date command:

                Get-ChildItem 'C:\Temp\'-recurse  | where {(get-date)}

We encapsulate this in parantheses as well in order to say that we are not getting the date from system time.  Next we define what date we want to get, which is the file creation time time:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime)

Remember the -$_. The – indicates what to get, the $_ indicates it is a list of items and the . belongs to .creationTime.  Moving along we encapsulated all of that within another set of parentheses to say that is a group that has a specific output, creation time. We need to then do something with it to indicate the length of time that has passed since it was created.  This is where we use .days:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime).days

Now here is where we accually select old items with the –ge operator.  Remember if the file was created today, then its age is 0.  For our purpouses we will say we want to select all files not created today:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime).days -ge 0

Now that we have selected the files that we want we need to add an additional command, which means an additional Pipe operator:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime).days -ge 0} |

Now because we want to remove we use the remove-item command, which was the same as del in DOS:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime).days -ge 0} | remove-item

Remove-Item has a couple of switches in it that you can use, for our purposes we are going to use the –force and the –recurse switches to tell it to delete EVERYTHING selected and to do it nondescrimitory:

                Get-ChildItem 'C:\Temp\'-recurse  | where { ((get-date)-$_.creationTime).days -ge 0} | remove-item -force –recurse

And there you have it!  As usual please add your comments below and I fully encourage you to share this with your colleagues.  Also that extra few clicks to +1, Like, Tweet, linkedin Goes a long way for me!

Sources: Microsoft Scripting guy http://preview.tinyurl.com/37ljrya, Myself

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:


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

Tuesday, February 12, 2013

Powershell Script DIY: Error establishing connection when pulling HTML

I noticed on an early blog post titled “Downloading HTML code from the internet using powershell” I failed to touch on HTTPS connections with untrusted certificates.  Occasionally you may run up on a website that has an untrusted certificate that gives you this when you try to navigate to it using internet explorer:

This is because of a problem with the certificate being unverifiable.   Should you attempt to run a script that refers to this address it will return this error:

Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
This can be alleviated by using the following line of code before you query the web page:

 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

As always, do not query web pages unless you know the contents and do not run security code unless you know its effect.  Please leave you comment below!

Source: Daniel Richnak http://stackoverflow.com/questions/6781433/how-to-ignore-ssl-certificate-is-signed-by-an-unknown-certificate-authority-prob

Monday, February 11, 2013

Powershell Best Practices: Commenting in Powershell. While optional, Its highly encouraged.

 This post is more of a “best Practice” then a “How To,” although, It does contain some how elements.  Commenting in any programming language is in important function, and even more so in Powershell due to the fluid nature of scripting.  While not officially defined, I like to think there are 4 types of comments:

Header: This includes the authors name, the creation / last modification date, and the purpose.  This is important as a script can be renamed a number of times, but you need to know what your published script does.  Some companies even mandate this set of comments as a way of tracking employs work.

# Author: John Doe
#Date Created: 1/1/2010
#Date Last Modified: 2/2/2012
#Purpous: Provide an example of commenting out a header

Explanation:  Code is confusing.  Very confusing.   When a large script is written, it is good to explain blocks of commands so that your successor can come in and make alterations if needed.

#this next line of code sets your working directory to “c:\temp”
Set-Location “c:\temp

Credit:  This is like citing your work on a paper.  It’s not only honest but necessary if the code needs to be manipulated. If no author is presented, verify the code and put down the web address where you found it. Remember, DO NOT USE CODE YOU CANNOT EXPLAIN.  Period.

#this next block of code was provided by Jane Doe via Janedoescripting.com.  Her email address is doe.jane@janedoescripting.com

Temporary editing:  When you’re working with code and are not sure if your modifications are right, comment out the original section and start from scratch.  This will keep you from getting lost in your purpose and provides you with the opportunity to revert to the original block of commands.

#remove-item “c:\temp\*.*
Remove-item “c:\temp\*.log

With that being said the two commands you need to know are # and <# #>.  # comments out 1 line in a script and is best used when you only have one line to comment.

#remove-item “c:\temp\*.*

This will make Powershell ignore your command so long as # precedes it.  Block commenting is used for most everything else.  Simply Precede the block of commands with <# and succeed it with #>:

Set-Location “c:\temp
$foo = “foo.txt

Do you have anything to add? Do you have corrections or Kudo’s?  Please leave a comment below! And remember, a share and a +1/like/tweet go a long way!

Powershell Script DIY: Adding a line at the begining of a file

Today we are going to add a header to our file, foo.txt.  This can be useful for adding a header to a CSV file, or just adding a title to your output for easy reference.  Whatever your reasons you always need to start by Setting your location and defining variables:

Set-Location “C:\Temp

$fooaltered = “fooaltered.txt
$H = "the title is foo"
$I = Get-Content “foo.txt”

Notice the Get-Content command in the definition for $I?  This is necessary to grab the contents of foo.txt and not the actual file itself.  Remember, you must encapsulate the actual object or value in quotations, but any command prior to that does not get the quotes.
Next we need to use the Set-content command


We tell powershell what variable we want to set the content to:

Set-Content $fooaltered

And we use the nifty –value switch to tell powershell that we are adding more than just one set of data:

Set-content $fooaltered –value

Now we use the variables $H and $I that we defined earlier to define the content of fooaltered.txt.  It is important to note that when using multiple values in this manner you need to separate them with a comma and a space:

Set-Content $fooaltered –value $H, $I

If you want to limit the size of your file to a certain number of lines, you can use the [x…y] definition where x and y are line numbers.  This is useful if you need to keep the file a certain size, or number of lines:

Set-Content $fooaltered -value $H, $I[0..5000]

Your end result should be:

Set-Location “C:\Temp

$foo = "foo.txt"
$fooaltered = “fooaltered.txt
$H = "the title is foo"
$I = Get-Content $foo
Set-Content $fooaltered -value $H, $I[0..5000]

As always if you have a correction or something to add, Please feel free to post below!

Powershell Script DIY: Creating Variables

     The most important thing you do in Powershell scripting is setting variables.  A variable is any value that you need to refer to later.  It can be a location, a file name, a specific number, or anything you could possibly imagine! When done incorrectly, you can end up with a messy script that no one but the most attentive can step through.  Variables are always lead by a $, and can be any combination of letter and number characters.  While you can name your variable anything you want: $bobwehadababyitsaboy, its best practice to have a naming convention in place.  A naming convention is a standardized system of assigning names such as: FirstnameLastnamebirthyear or MakeModelYear.  These two examples would look like


Once you decide on a naming convention it is time to define your variable “foo.” We start with the $


And add the variable name:


Now a variable on its own is useless unless we assign a value, so we tell powershell that foo is equivalent to foo.txt in the current directory.  The = sign is used to say “is” and the quotation is to say “this value.” It is important to remember that the type of quotation is important as double quotes tell Powershell to treat the string as text and single quotes tell it to literally treat it as text.  To clarify, placing a variable in double quotes will return the value of the variable and single quotes will return the variable name as you typed it.:

$foo = “foo.txt”

Until you say otherwise, or close the session, the value of $foo is forevermore “foo.txt

As always, If you have a correction, or something to add, please post a comment below!

Powershell Script DIY: The easy command: Set-Location

     Setting your location is easy, and when done correctly, can give you a proper entry into the world of scripting. For this exercise we use the Set-Location command.


As with every Set command you need to set the value.  The value must always be encapsulated in quotations of some kind. The type of quotes are important.  Double " quotes are for normal non-literal use.  that is, if you put a variable in there, then the variable value will appear.  Single quotes tell Powershell to take the string literal, that is the variable itself will appear in the string, not its value:

Set-Location “c:\temp

As always, If you have anything to add, Post it below!

Edit: I had been misinformed on the use of the two kinds of quotation, this has been corrected.

Friday, February 8, 2013

Powershell Script DIY: Remove Empty Lines From a Text File

Today we are going to learn to remove empty lines from a text file.   This can be useful if you need the input to be formatted a certain way for input into another script, or you just want your text file to look pretty.
First we start off with our location, and as with my other posts I set it at “C:\temp”:

Set-location “c:\temp”

Next we define our variables as:

$foo = "foo.txt"
$foolog = “foo.log

If you’re new to the field, Foo is a catchall for examples.  It can be literally anything.  Moving on we need to use the select-string command with the – pattern variable this tells Powershell that we are looking for a specific pattern in the file.

Select-String –Pattern

We are not even close to done as we need to define what we are looking for, which is anything.  This is done by using \w.  \w is used to find a word character, which is most anything (Except a line break):

Select-String -Pattern "\w"

So far we have said “Hey Powershell, Look for anything.” But as with everything in life, Powershell will respond with “Where?”.  This is where we tell it to look in our source file, or $foo:

Select-String -Pattern "\w" $foo

Now selecting the string its self is useless. It’s tantamount to saying “Hey You, Pick one!” and not following it up with anything.  So we use the pipe operator “|” to tell it that we want it to do something with it:

Select-String -Pattern "\w" $foo |

As there are multiple lines in our file, we need to use ForEach-Object to make Powershell recognize this:

Select-String -Pattern "\w" $foo | ForEach-Object

The next part is encapsulated in curly brackets “{}”.  You always have to encapsulate something when you are giving something a repeating command like “ForEach-Object”:

Select-String -Pattern "\w" $foo | ForEach-Object {}

Inside the Curley Brackets we need to tell it to go line by line through the file starting with the first line.  You can do this by saying start at the first line “$_” and do it for every subsequent line “.line”:

Select-String -Pattern "\w" $foo | ForEach-Object { $_.line}

Remember, This has to be in the brackets.  And finally, we dump the output into Foo.log, which is defined as $foolog. As this is an additional command we will use another | operator to add a “Set-Content” to the end:

Select-String -Pattern "\w" $foo | ForEach-Object { $_.line
} | Set-Content $foolog

In the end it should look something like this:

Set-Location “C:\temp”
$foo = "foo.txt"
$foolog = “foo.log
Select-String -Pattern "\w" $foo | ForEach-Object { $_.line
} | Set-Content $foolog

So to summarize, we:

1.       Set our location
2.       Defined our variables
3.       Selected any word character within foo.txt
4.       Told it to do this for every line
5.       Set the content to foo.log

Sounds like you should still have the lines unless you remember that we are selecting every “Word Character.”  Empty lines don’t count as characters so they are not extracted from the original file.
As always, please post your comments below.  I welcome the Critique and would love to hear if you have a different way of doing this!

Source: ScriptingGuy1 http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/27/deleting-extra-returns-and-line-feeds-from-a-text-file-using-windows-powershell.aspx

Thursday, February 7, 2013

Powershell Script DIY: Removing Special Characters

     Tired of those pesky special characters infiltrating up your data that you pulled from erroneous sources? I have a solution for you!  In this post we are going to use the regex function, and its replace operator with the escape command.  Confused? I aim for you not to be.  First we need to set our location, if you are not already there.  I always default to c:\temp:

                Set-location “C:\temp

Define your variable, let’s say foo, with:

$foo = “foo.txt

Remember to encapsulate the value in quotations and put a $ before foo. Now, we need to pull the data from $foo with:

                Get-Content $foo

This will pull it into memory under the $foo variable.  But we need to do something with the data, so we use the pipe operator |.  Remember to put a space between the variable and the pipe operator:

                Get-Content $foo |

The pipe operator tells powershell that this is only part of a sequence of commands; you can keep adding pipes as long as the command between them is doing something.  I will go into more detail in a future post.  For the mean time, we need to pipe it into ForEach-Object.  This command says just that “For Each Object, do this”.  So, you should look like this:

                Get-Content $foo | ForEach-Object

But of course you need to tell it what to do, and that is where we need the {} to encapsulate your next set of commands:

                Get-Content $foo | ForEach-Object {

We need the Special Pipeline Variable $_ in front of our first –replace command, only the first one as the rest are separated by `.  This denotes everything within the brackets as the current pipeline object:

                Get-Content $foo | ForEach-Object {
                                $_ -replace

Now we tell it to replace a regular expression with [regex] and to escape the special character ? with nothing:

                Get-Content $foo | ForEach-Object {
                                $_ -replace [regex]::Escape(‘?’), ‘’`

Note that the special character is encapsulated by parentheses and quoted within those parentheses.  After the character to be replaced is a , and two ‘ followed by a `.  This is essential as two ‘’ is not one ” and means empty space.  The ` denotes the next line.  You can follow this up with as many characters you want to replace such as the case with % :

Get-Content $foo | ForEach-Object {
                                $_ -replace [regex]::Escape(‘?’), ‘’`
                                     -replace [regex]::Escape(‘%’), ‘’`

In order to finish this off you need to finish the encapsulation with a }:

Get-Content $foo | ForEach-Object {
                                $_ -replace [regex]::Escape(‘?’), ‘’`
                                     -replace [regex]::Escape(‘%’), ‘’`
And use the pipe operator set the contents of your output file.  You can use either:

Set-Content $foolog
                Out-file foo.log

For the purpose of this exercise we will use out-file foo.log as you need to define a variable for set-Content.  The last line should look like this:

            } | out-file Foo.log 

The final result should be:

set-location "c:\temp"
$foo = "foo.txt"
Get-Content $foo | ForEach-Object {
                $_ -replace [regex]::Escape('?'), '' `
                     -replace [regex]::Escape('%'), '' `    
    } | out-file foo.log 

If you feed it a file containing:


You should get the result:


You can replace the individual characters “?” and “%” with any character, but there are simpler ways for non special characters. As usual, I always invite comments; I have learned in the past that there is always a better, or different way to do things!

Wednesday, February 6, 2013

Powershell Script DIY: Downloading HTML code from the internet using powershell

So you need to pull information from a webpage?  Just the raw HTML can be useful, especially if you are scouring for specific or variable strings on regularly accessed sights, like say a printers toner levels.  
First we start with Set-Location and the variable:


I prefer to name my variables something easy to remember, given the context of the script.  We then tell the variable what it is:

$web = New-Object Net.WebClient

This is telling the variable that the new object is a Net.WebClient, or in simpler terms, it’s out on the internet.  But we need to tell it what to do, so we pipe it through Get-Member:

$web | Get-Member

I usually like to name all of my variables at once, so we can go ahead and name the output file (See my blog post on Creating unique temp file names) :

$foo = "c:\Temp\foo-$(Get-Date -format 'yyyy-MM-dd hh-mm-ss').log"
New-Item "$foo" -itemType File

So far we should be about here:

$web = New-Object Net.WebClient
$web | Get-Member
$foo = "c:\Temp\foo-$(Get-Date -format 'yyyy-MM-dd hh-mm-ss').log"
New-Item "$foo" -itemType File

Don’t forget to create $foo as a file, otherwise you will not have anywhere to put the html code that you pulled.
Now we pull the actual data.  This is accomplished by attaching “DownloadString” to the $web variable, telling the variable what it is going to become:


We need to give it a source.  To do this we encapsulate the URL in quotes, and then in parentheses. The quotes are for the special characters and the parentheses are denoting the source as everything in between them.  The source data should look something like this:


Attach this to the $web.DownloadString and you get:


What about the output?  You can’t just leave the string just hanging! You need to Pipe it into your $foo variable.  We accomplish this with a set-content command:

| set-content $foo

To produce the complete command:

$web.DownloadString("") | set-content $foo

Run it all together and you get:

$web = New-Object Net.WebClient
$web | Get-Member
$foo = "c:\Temp\foo-$(Get-Date -format 'yyyy-MM-dd hh-mm-ss').log"
New-Item "$foo" -itemType File
$web.DownloadString("") | set-content $foo

As always, please feel free to give us a better way to do things with the comments below!

Sources: rob_campbell@centraltechnology.net posted online

Tuesday, February 5, 2013

Powershell Script DIY: Unique Temp File names

 Hello again!

Have you ever need a unique temp filename?  A name that you can easily call and manipulate?  First you start with the variable:


$foo can be anything.  it can be $Jamaca, or even $US_of_A.  All that really matters is that it’s easy to pick out in your script and it begins with a $.  All variables in Powershell begin with a $.

Next we move on to assigning a variable.

$foo = "foo"

Of course you probably don’t want your variable to have a value of "foo" but foo can be anything, even:

$foo = "c:\Temp\TEMP"

This is only telling $Foo what it is.  All that matters is that it has quotes.

After that we want to get it a unique string:

$foo = "c:\Temp\TEMP-$(Get-Date -format 'yyyy-MM-dd hh-mm-ss').log"

Here is the complicated part.  We are using the system Date Time Group to generate a unique identifier.

The TEMP portion is giving the string a beginning, and after that we begin with the variable portion (anything between will show up in the name.) The Get-Date function will pull the system time at that second.  But wait, everyone formats their date differently!  Not to worry, here is a quick reference guide:

dd - 2 digit day of the month
ddd - 3 character day of the week (i.e. tuesday)
dddd - full day name (i.e. Tuesday)
mm - 2 digit month
yyyy - 4 digit year
yy - 2 digit year
hh - hour (12 hour format)
HH - hour (24 hour format)
MM - Minuet
ss - Second

Now I perfer the format yyyy-MM-dd hh-mm-ss, and the dashes are only delimiters, they are not necessary.  you could even have:

$foo = "c:\Temp\TEMP-$(Get-Date -format 'dddd-dd-mm-yyyy HH-MM-ss').log"

This will get you a output of "TEMP-Tuesday-05-39-2013 14-02-25.log"

Make sure the format has single quotes around it.  Make sure everything from before Get-date to the end of your date format is in parentheses. 

Now you add the extension, while this is not necessary, I find it useful for debugging output.  My personal favorite is .log but you can name it anything.  Keep in mind that windows may not like it if you name something .dll or something of that nature.  

To complete your variable you need to encapsulate it in quotes:

$foo = "c:\Temp\TEMP-$(Get-Date -format 'yyyy-MM-dd hh-mm-ss').log"

Just the value, not the variable itself.

After that you need to create the file itself.  Start with New-Item.  Self explanatory but easily overlooked.  Append the variable name, in quotes after it so it looks like this:

New-Item "$foo"

This will prompt Powershell to ask you what type of item you want.  It can be a folder, a file, ECT.

To avoid this, you need to select an item type with, you guessed it, -itemType.  For the purpose of this exercise, I selected File for my item type.  don’t forget the - as it denotes it as a switch. The command should look like this:

New-Item "$foo" -ItemType File

Last but not least you need to roll it all together for script friendly formatting:

$foo = "c:\Temp\TEMP-$(Get-Date -format 'yyyy-MM-dd HH-mm-ss').log"
New-Item "$foo" -itemType File 

And that my friends, Is how it’s done.  Do you have another way to do it? Do you have comments? Leave them below!

Sources: Unknown Internet Source