Wednesday, August 28, 2013

All,

Summer has been busy! I have written 3 additional articles for Hey! Scripting guy!.   Here is a list of the articles published on Technet:


Weekend Scripter: Use PowerShell for Conditional User Profile Removal





With one more to be released on Monday, 16 Sep 2013!


Unfortunately I have not had an opportunity to write for my own blog, but fear not!  I will be explaining Arrays and functions soon.

-Bob Stevens

Friday, May 3, 2013

Powershell DIY: Absolute Value


Absolute value.  This is the best possible simple example of an “if” “ElseIf” statement.  An absolute value is the distance a number is from 0.  For 22 it is just that, 22.  For -22, the absolute value is 22.  In order to do this we are going to use the read-host command to gather the requisite value:

$a = Read-Host “Number?”

With this statement we are defining $a by asking the user with “Read-Host”.  The “Number?” is purely optional, but I always suggest using it to define the input.  Next we need to use the “If” statement.

If

If must always be followed by a statement in parentheses:

If ()

For our conditional statement we are going to use the -le condition.  We start with using the literal value of $a, ‘$a’ and the condition Less Than (-le) and define what exactly it is supposed to be less than, 0:

If ('$a' -le 0)

So What if $a is less than 0? We subtract it from 0 of course! Any negative number subtracted from 0 gives us the positive corresponding value.  Encapsulated in Braces ({}) we spell out the math equation:

{$a = 0 - ($a)}

In order to address a negative value we must further encapsulate it in parentheses, as we have done here.  Our completed “If” statement is:

If ('$a' -le 0) {$a = 0 - ($a) }

Now we must address positive values to balance the script.  We use the “ElseIf” statement for this:

ElseIf

And much like the “If” statement the condition is encapsulated in Parentheses () and the action is encapsulated in braces ({}):

ElseIf(){}

The conditional statement here is similar to the previous if statement, with one exception, the Less Than ( -le) has been replaced with a Greater Than (-ge) condition:

ElseIf ($a -ge 0){}

Since this statement is for a positive number, we don’t want it to actually do anything, so we balance both sides of the equation by making an obvious statement $a = $a

ElseIf ($a -ge 0){$a = $a}

With this we have stated this: “If $a is greater than 0, make $a equal $a.” In other words, Do nothing.  Last but not least, we tell the user the absolute value by using the variable alone:

$a

Here is the Finished product:

$a = Read-Host "Number?"
If ('$a' -le 0) {$a = 0 - ($a) }
ElseIf ($a -ge 0) {$a = $a}
$a

I am sure there is a command that does all this out there, but the purpose of this was to demonstrate math, addressing negative numbers, and If “ElseIf” statements.  As usual if you have a better way to do this, let me know!  The fastest way to learning is through collaboration!



Stats

The best thing about Blogger is the stats.  I love stats and as such I felt it prudent to share them with you!

from January till now:

United States
516
Germany
64
Russia
36
United Kingdom
24
France
15
Sweden
11
Canada
9
Australia
6
India
6
Netherlands
6


Firefox
273 (35%)
Internet Explorer
254 (32%)
Chrome
151 (19%)
Safari
34 (4%)
Mobile
16 (2%)
Opera
14 (1%)
Mobile Safari
12 (1%)
UniversalFeedParser
12 (1%)
CriOS
5 (<1%)
OS;FBSV
4 (<1%)


Windows
611 (79%)
Macintosh
58 (7%)
Android
51 (6%)
iPhone
16 (2%)
iPad
13 (1%)
Linux
10 (1%)
iPod
4 (<1%)
Windows NT 6.1
3 (<1%)
BlackBerry
2 (<1%)
Other Unix
1 (<1%)


I have had a total of 782 views, While I don't know how many of you are hitting my blog on a regular basis, all I can say is thank you.

Tuesday, April 30, 2013

Powershell DIY: Reading every other line in a file


     Recently I have come upon a situation that required that I read every other line in a file.  While this may sound unusual, believe me, it is more common than you may think.  As such I had to come up with a Do – While loop.  This loop simply put says “do ‘A’ while ‘B’ is true” 

     First, as usual we need to create a source file.  This file can contain anything, for our purposes we are going to use this:



Now we are going to define our first variable:

          $source =

This variable is going to have to be an array by using the ampersand (@) followed by parentheses ():

          $source = @()

     Inside the parentheses we need to tell Powershell what exactly is going to be in our array.  Since we are using the contents of the source.txt file, we need to use the Get-Content commandlet to tell it to look in the file, and grab everything in there:

          $source = @(Get-content source.txt)

     Now that we have our array defined, we can define its length.  This is needed as an escape for our loop.  For this we are going to use another variable:

          $length

     And define it with a property of the $source array.  Specifically, we want its length.  To get the property of a variable, simply append a period (.) followed by the attribute:

          $length = $source.length

     Now we need the counter.  A counter is a common piece of code that increments every time an action is taken.  It has two parts, the first is the initial definition, and the second is the incrementing commandlet.  General practice is to use “I” for an initial counter, “j” for a nested counter, and so on and so forth.  Four our purposes we are only using I, and we are setting it with the initial value of “0”:

          $i = 0

So far we have defined our variables with this block of code:

          $source = @(get-content source.txt)
          $length = $source.length
          $i = 0

     Now we are going to initiate the do-while loop with the “do” commandlet.  “Do” must always be followed by braces {} to encapsulate what we intend for it to do.  This tells Powershell what it is exactly you want done while the “While” condition is true:

         Do{}

     Because we want to count every other line we need to set some conditional statements.  For this exercise I am going to use the “If” condition.  If must always be followed by two things, a condition, and an action.  The condition is encapsulated in Parentheses (), and the action is encapsulated in braces {}

          Do{
          If(){}

          }

     We want to tell Powershell “If the line is even, then tell me it is even.” For this we need to define what is odd.  In basic arithmetic an even number is divisible by two with no remainder.  An odd number is divisible by two with a remainder of one.  The key here is the remainder.  It is always either a 1 or a 0.  This is convenient as it gives us a clearly defined variable that is always either true or false.  Four this we use the Percentile operator (%) followed by a 2.  The % returns the remainder rather than the product of a division, and as such is only a 1 or a 0 if we divide by 2.  This needs to be encapsulated in yet another nested set of parentheses ()


     Between the last two closing parentheses we need to give power shell the condition: “ if the result of the aforementioned formula is equal to “0”.  In order to indicate this we need to use the –eq (Equals) operator followed by the value of 0:

          If(($i%2) –eq 0){}


     So we have told Powershell that If the reminder of the counter $i divided by 2 is 0, then do this.  “This” is what we need to define now.  We enter in our action inside the braces that follow the condition statement.  For us, we are only going to have Powershell display the line, and tell us if the line is even or odd.  So we use the Write-Host Commandlet to tell it to display the output:

          {
          Write-Host
          }

     Now we need to tell it what to write.  Start with the source array variable, and in brackets tell it which item to select with the counter variable $i.  this tells Powershell that we are selecting the $i item in the array:

          {
         Write-Host $source[$i]
          }

     And to prove our output is correct, we are going to append “is odd” in quotations after this, remember to have the space between them or else Powershell will think it’s part of the $source[$i] variable:

          {
         Write-Host $source[$i] "is odd"
          }

Roll that together with the condition and you should come up with:

          If(($i%2) -eq 0){
         Write-Host $source[$i] "is odd"
          }

     Now that we have gotten this far we need to rinse and repeat with the even numbers, for this all we change is the –eq value from a 0 to a 1 and change the odd to an even:

          if(($i%2) -eq 1){
         Write-Host $source[$i] "is even"
          }

Combine them to get a solution for both possible vaues:

          if(($i%2) -eq 0){
          Write-Host $source[$i] "is odd"
          }
          if(($i%2) -eq 1){
          Write-Host $source[$i] "is even"
          }

     And at the end we need to increment the counter.  This is the second part of a counter function.  All that is needed is the variable name, $i, and a “++” appended to it to tell Powershell to add 1 to the current value:

          $i++

     Once we have accomplished this we nest this inside the braces following the Do commandlet, and we have our do statement:

          do{
          if(($i%2) -eq 0){
         Write-Host $source[$i] "is odd"
          }
          if(($i%2) -eq 1){
         Write-Host $source[$i] "is even"
          }
          $i++
          }

     With any do statement we need to give it an ending condition as I stated earlier.  This tells Powershell to do “this” until “that” condition is met.  For this we use “While”.  While is always followed by parentheses that encapsulate the desired condition:

          While()

     For our script, we want it to end at the end of the file, which we defined by its length. So we say “so long as the counter $i is less than the length ($length)of the file”  this is accomplished with the –le (Less than) operator:

          While ($i -le $length)

When we append this to the end of the script, and ensure that the variables are before it, it should look like this:

$source = @(Get-Content source.txt)
$length = $source.length
$i = 0
Do{
If(($i%2) -eq 0){
    Write-Host $source[$i] "is odd"
}
if(($i%2) -eq 1){
    Write-Host $source[$i] "is even"
}
$i++
}
While ($i -le $length)

But Wait!  The math is all wrong! If the counter has a remainder of 0 it is even, yet I stated that it is even!  This is intentional.  Arrays start at 0 so they are offset by one.  So 0 is the first position, 1 is the second position, so on and so forth.

In plain English what we have done is this:

“Read this file, and tell me if every line is either even, or odd.  Do this until the end of the file. ”

And there you have it.  Should you have any questions, or even a better way to do this, do not hesitate to let me know.  If you are as fast as me with a mouse, it takes a second to +1, Like, Tweet, Share.



Sunday, April 14, 2013

Announcment! 2 Posts on Hey! Scripting Guy!

All,
On 12 March 2013 I attended a presentation by Ed Wilson, the author of Hey! Scripting Blog. To make a long story short, He asked me to write two articles for him to feature on his blog. These two articles where posted on the 13th and 14th of April 2013:
Weekend Scripter: Use PowerShell to Clean Out Temp Folders

http://blogs.technet.com/b/heyscriptingguy/archive/2013/04/14/weekend-scripter-use-powershell-to-clean-out-temp-folders.aspx

Weekend Scripter: Pick Comments from a PowerShell Script

http://blogs.technet.com/b/heyscriptingguy/archive/2013/04/13/weekend-scripter-pick-comments-from-a-powershell-script.aspx

I fully encourage you to check them out yourself and please, comment and share them to your heart’s content!

Thank You,
Bob Stevens

Friday, March 29, 2013

Powershell Script DIY: Permissions


One of the most frustrating things with computers is permissions.  Not being able to access a file can quite often put a full stop to your Powershell adventures.  Microsoft has made this easy by giving us the ACL commandlets for our purpose today we will use these two commandlets:

               Get-ACL
               Set-ACL

The object is to take the contents of the Foo directory, which has the owner of Greg Foo and replace the permissions with administrator.  We start by defining variable.  First we need to find an object that we defiantly have permissions to.  The desktop is an excellent choice as we can read, write, and it most definitely exists for 99% of users. So we start with our variable and the Get-ACL command:

                $ACL = Get-ACL

We need to define the location we are pulling our permissions from so we are going to use the $home environmental variable.  This variable will return the path of the current working profile.  For me it is “C:\Documents and Settings\Administrator”.  This is not good enough.  We need the desktop so we append the “\Desktop” child directory to it.  Because we have a variable in the quotations we need to use double quotes otherwise Powershell will return the variable name:

                $ACL = Get-ACL “$home\Desktop

Now that the desired permissions are defined, we need to define what we want to apply them to.  For this we need the mighty Get-Childitem commandlet, and define our object as "C:\Foo"

                Get-Childitem “C:\Foo”

Because we want ALL Items in this folder, we need to tell Powershell to look in all subsequent folders with the “-recurse” operator and to select all hidden folders with the “-force” operators:

                Get-Childitem “C:\Foo”-recurse -force

Now that the files are selected, which is tantamount to CTRL+A with display hidden files on, we are going to dump the results into the Set-ACL command with a pipe (|) operator:

                Get-Childitem “C:\Foo”-recurse -force | Set-ACL

Because we already defined the object we are applying the permissions to we can move right along to the-aclobject operator.  This operator says apply the following permissions to the previous object.  The following being the $acl that we defined earlier in the article:

                Get-Childitem “C:\Foo”-recurse-hidden | Set-ACL-aclobject $acl

And there you have it.  We have successfully applied your permissions to this folder full of goodies that you need to accomplish your mission.  As usual, should you have any suggestions, or even a better way to do it, let me know!  And please don’t forget to share, +1, like, and tweet this post to all of your Powershell using compatriots below!



Tuesday, March 19, 2013

Powershell DIY: Install Powershell!


Below is the requirements and links to Powershell installations!  Please remember to meet all of the requirements before attempting to install Powershell.

Workstation Operating Systems:

Version
Operating systems supported
Requirements
- Windows XP
- Windows Vista
or
- Windows XP SP3
- Windows Vista SP1
- Windows 7*
-.NET Framework 3.0 for Powershell 2.0
-.NET Framework 3.5 for Powershell 2.0 ISE
Powershell 3.0***
- Windows 7 SP1
- Windows 8**
  Or

*Windows 7 has Powershell 2.0 and Powershell 2.0 ISE natively installed
**Windows 8 has Powershell 3.0 and Powershell 3.0 ISE natively installed
Server Operating Systems
*** Powershell comes in the Management Framework 3.0 package

Version
Operating systems supported
Requirements
- Windows Server 2003
- Windows Server 2008****

- Windows Server 2003 SP2
- Windows Server 2008 R2
-.NET Framework 3.0 for Powershell 2.0
-.NET Framework 3.5 for Powershell 2.0 ISE
Powershell 3.0***
- Windows Server 2008 SP1
- Windows Server 2008 R2 SP1
- Windows Server 2012

  Or

*** Powershell comes in the Management Framework 3.0 package
****Optional Feature

Monday, March 18, 2013

HISIMP! Announcement

As many of my readers may know I strive to learn more about the functionality of Powershell.  Recently after attending a presentation given by Ed Wilson on Powershell 3.0 best practices I was asked to write an article for his blog, Hey! Scripting Guy!  So on 4/13/2013 you will see my article on his blog!  I invite you all to view and leave your comments.

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

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 192.168.1.1 255.255.255.0.  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:
Purpose
Computer name
Date
Server name
Time
Physical location
Version number
Group Name
Author
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”:

Foosourcedata

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

Foosourcedata_

The source of our data is Server1:

Foosourcedata_Server1_

I like to include the date-time group:

Foosourcedata_Server1_01JAN2013_1200

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:

Foosourcedata_Server1_01JAN2013_1200.log

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:

Fooscript

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

Fooscript_JRD

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

Fooscript_JRD_1.0.1

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:

Fooscript_JRD_1.0.1_Working

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

Fooscript_JRD_1.0.1_Working.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:

1.2.3

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