Saturday, August 9, 2014

Create a list of Computer Names with no spaces with PowerShell

A few months back a co-worker of mine shot an email my way asking what the best way to create a list of all of the servers in the domain so that he could run a script against them way.

If you haven't ever done this before it can be a little trickier than you might originally think. The best way I've found to do this is with a function. A function allows you to name a block of code. Once defined you can then call that function block anywhere in a script or just at the console. Personally functions are one of my favorite things about PowerShell, well at least its up their with PS-Remoting, Workflows, and Desired State Configuration. Functions have 6 main parts; The Functions Name, a help file, param block, and a begin, Process, and End Block [Shown Below].

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
function Get-ComputerList {              # The Funtions Name

<#...#>                                  #Help File

                      [CmdletBinding()]
              Param (                    #Param Block
              )

          Begin {                        #Begin Block
          }

     Process {                           #Process Block
     }

  End {                                  #End Block
  }                   
}

Now lets take a look at what I've chosen to place into the Param, Begin, Process, and End blocks.


Param

First off I always like to define the location of the text file in the parameter block but this comes down to personal preference.

001
002
003
004
005
Param ( [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   $OutputPath = "$env:USERPROFILE\Desktop\ComputerList.txt"
)

I made $OutputPath above equal "$env:USERPROFILE\Desktop\ComputerList.txt" which is where the newly created computer list will be Out-File'd' too.


Begin


The Begin Block -- This is where we I've chosen to gather the computer names and output them to the $OutputPath defined above in the Param block. If we were to run only the cmdlets in the Param block and the Begin block we would have a text file on our Desktop called ComputerList.txt.

001
002
003
004
Begin {
       # requires PSv3.0+ -- retrieves all computer and server OS names
       Get-ADComputer -Filter * -Properties * | Select-Object -ExpandProperty name | Out-File $OutputPath
}

Another commonly used parameter is the -Filter parameter which I've used to only retrieve computer names whose OperatingSystem field have *Server* in the name. From there the generated computer list is piped to Select-Object -ExpandProperty name. A key thing to note, the -ExpandProperty parameter will give us a list of computers ready to run commands against. If we didn't use the -ExpandProperty  parameter the output would contain header information as shown on the right. There is a way to make it work without using the -ExpandProperty parameter but I'll talk about that in the next section. After the list is generated and filtered everything is Out-File'd' to $OutputPath also known as $env:USERPROFILE\Desktop\ComputerList.txt.

001
002
003
004
Begin {
       # requires PSv3.0+ -- retrieves all server OS names
       Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' | Select-Object -ExpandProperty name | Out-File $OutputPath
}


Process

There are multiple different ways to extract or remove white spaces from a document.

My favorite being:

001
(Get-Content $OutputPath).replace(" ","")


Here is another way to remove the white spaces from a file.

001
(get-content $ComputerList-replace "\s+", ""


Okay so lets say we didn't use -ExpandProperty in the Begin block, If that were the case we could get around the problem of the output containing the header information by using the below line of code.  


001
(Get-Content $OutputPath  | Select-Object -Skip 3).replace(" ","")



The -Skip 3 will successfully -Skip the first three lines of the output which would need to be done before we could successfully run a script or function against it.


The process block in its entirety.

001
002
003
004
005
Process {
         # removes empty spaces from txt document
         # Alternate Way --> (get-content $ComputerList) -replace '\s+', ''
         $ComputerList = (Get-Content $OutputPath).replace(" ","")
}



End

The end block should be where you wrap up the function, this is where all Out-File's' will output their final products.This is where any formatting would be if you must place some in your script. However it is best practice not to do any formatting to the output as the next user who runs this script might want all the data to be displayed differently and this will allow he\she to simply format the data if they feel the need.

001
002
003
004
005
006
  End {
       $ComputerList | Out-File $OutputPath
       write-verbose "The Computer list has been saved to $OutputPath"
       write-verbose "Opening file $OutputPath at this time"
       Invoke-Item $OutputPath
  }

The full function called Get-ComputerList can be downloaded at the Microsoft Script Repository.