Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, December 31, 2012

Thank you for another great year

2012 has now come to an end.  I want to thank all of my clients for allowing me to represent you to your clients.  Below is my report card for the year. The blue line is my average score while the orange line represents the average of all instructors.  I think this says it all.  Please contact me early to reserve your 2013 dates.
Happy New Year!
image

Friday, December 21, 2012

PowerShell.com Moderator

I am pleased to announce that I am working with Jakub Jareš as the moderator for the Active Directory forums on PowerShell.com.  Please feel free to stop by and ask us your Active Directory, PowerShell related questions.

Jakub JarešJakub Jareš

Follow Jakup on Twitter 

Jason Yoder

Jason Yoder

Follow Jason on Twitter.

Wednesday, December 19, 2012

What to do if your CSV file has a blank line at the end?

On PowerShell.com, I answered a question from a forum member who was receiving a CSV with the list of user names to be added to a group.  If the CSV file had a blank line at the end of it, it would cause problems.  Below is my code to read in a CSV file and filter out any blank lines before handing the object to PowerShell for processing.
Import-Csv -Path "F:\Temp\Users.csv" |
 ForEach-Object {If($_.Name -ne "") {Add-ADGroupMember -Identity "Test Group" `
 -Members $_.Name}}
We first import the CSV file into the PowerShell pipeline.  Next we pass the object to a ForEach-Object statement.  Each object is tested to see if the name property is empty.  If it is, then nothing is done.  If it contains data, then the user is added to the group.  I could not use Where-Object {$_.Name –ne “”} as my filter because Add-ADGroupMember does not accept input from the PowerShell pipeline for its Member parameter.

Monday, December 17, 2012

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of.

This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago.

In the Group Policy module for PowerShell V3, there is a New-GPO and a Get-GPO cmdlet, but there is not a Set-GPO cmdlet.  Fortunately, the Get-GPO cmdlet has some "put" capabilities to it.  Below I I used Get-GPO to grab one of my GPOs and I sent it to Format-List *

image

Notice the Description field.  I did the same thing, but this time I piped it to Get-Member.

image

The Description field has a "set" flag on it.  Next I went ahead, grabbed the object and set the description field.

image

When I look at the comment field in the GPO, there it is!

image

Wednesday, December 12, 2012

Discover what Accounts Services are Used in Your Network

This week in My Windows Server 2012 class, I had an interesting question pop up while we were discussing managed service accounts. The client knew they needed to switch off of their current service accounts because to many people knew the passwords. They knew managed service accounts were the way to go, but did not know how to address the issue of how to discover all the services that they were using the same accounts on across all of their servers. The client asked me if they could do it with PowerShell….absolutely!
The cmdlet below will allow you to pipe in a comma separated list of your server names and the cmdlet will return all the accounts being used by the services running on the servers in your environment.  I am using the Test-Connection cmdlet in this  code so make sure your servers are able to return pings.

Function Find-ServiceAccounts
{
[cmdletbinding(HelpUri = 'http://get-help-jason-yoder.blogspot.com/2012/11/fins-serviceaccounts.html')]Param (
    [Switch]$AllAccounts,
    [Switch]$Quiet
)   

    # Create a dynamic array to hold all the objects.
    $InitialData = @()

    # Holds a list of all services found.
    $AllServices = @()

    # Final output
    $Output = @()


    # Cycle through each server.
    ForEach($Server in $Input)
    {

        # Display progress data
        If (!$Quiet)
        {
            Write-Host "Check Server $Server : " -NoNewline
        }
        # Add the computer name to the object
        $Obj = New-Object -TypeName PSObject
        $Obj | Add-Member `
            -MemberType NoteProperty `
            -Name "ComputerName" `
            -Value $Server

        # Test to see if it is online.
        If (Test-Connection -Quiet -ComputerName $Server -Count 1)
        {
            # Add the online flag to the object.
            $Obj | Add-Member `
                -MemberType NoteProperty `
                -Name "Online" `
                -Value $True

            # If the $ALLAccounts flag is set, get all services and their
            # logon accounts.  If it is not set, then only retrieve services
            # whose logon accounts ar not "LocalSystem" or "NT AUTHORITY"
            If ($AllAccounts)
            {
                $Services = Invoke-Command -ScriptBlock {
                    Get-WmiObject Win32_Service |
                    Select-Object -Property Name, StartName, __Server} `
                    -ComputerName $Server
            }
            Else
            {
                $Services = Invoke-Command -ScriptBlock {
                    Get-WmiObject Win32_Service |
                    Where-Object {($_.StartName -notlike "*LocalSystem*") `
                    -and ($_.StartName -notlike "*NT AUTHORITY*")}|
                    Select-Object -Property Name, StartName, __Server} `
                    -ComputerName $Server
            }
           
            # Add the Services names to the list of services.
            ForEach ($Service in $Services)
            {
                $AllServices += $Service
            } # End: Add the Services to the object.

            If (!$Quiet)
            {
                Write-Host "Online" `
                    -ForegroundColor Green `
                    -BackgroundColor DarkGreen
            }
        
        } # End: If (Test-Connection -Quiet -ComputerName $Server -Count 1)
        Else
        {
            # Add the offline flag to the object.
            $Obj | Add-Member `
                -MemberType NoteProperty `
                -Name "Online" `
                -Value $False
            
            If (!$Quiet)
            {
                Write-Host "OffLine" `
                    -ForegroundColor Red `
                    -BackgroundColor DarkRed
            }
        }

        $InitialData += $Obj
    } # End: ForEach($Server in $Input)


    # Get a list of all the services names
    $ServiceNames = $AllServices | 
        Select-Object -Property Name -Unique
    


    ForEach ($Server in $InitialData)
    {

        # Build the output objects
        $Obj = New-Object -TypeName PSObject

        # Add the server name and online value.
        $Obj | Add-Member `
            -MemberType NoteProperty `
            -Name "ComputerName" `
            -Value $Server.ComputerName
        $Obj | Add-Member `
            -MemberType NoteProperty `
            -Name "Online" `
            -Value $Server.Online

        ForEach ($Service in $ServiceNames)
        {
            

            # Add a property for each service.
            $Name = $Service.Name
            $Obj | Add-Member `
                -MemberType NoteProperty `
                -Name $Name `
                -Value "N/A"
            
            #Write-Host $Service.Name -ForegroundColor Red
            ForEach ($Item in $AllServices)
            {
                
                   
                If (($Service.Name -eq $Item.name) `
                    -and ($Server.Computername -eq $Item.__Server))
                {
                    $Obj.$Name = $Item.StartName 

                }
                Else
                {
                    
                }
            
            } # End: ForEach ($Item in $InitialData)
            $Output += $Obj
        } # End: ForEach ($Service in $ServiceNames)
        

        $Obj
    }<#
.SYNOPSIS
Discovers all the logon accounts used on service accounts

.DESCRIPTION
Discovers all the services running on a list of servers piped into the
cmdlet and the logon accounts for those services.

The list of servers must be piped in to this cmdlet.


.PARAMETER AllAccounts
Returns services that have logon accounts of LocalServer or NT AUTHORITY.
Without this switch, only services that do not utilize LocalService or
NT AUTHORITY will be returned.

.PARAMETER Quiet
Suppresses the online status display on the monitor.

.EXAMPLE
"Indy1", "Indy2", "Indy3" | Find-ServiceAccounts

Returns the online status of each server, the services running on all servers,
and the service account used for the services logon account ina list format.  
Any service listed as N/A does not exists on that particular server.  Only 
services with a logon account that is not a LocalSystem or NT AUTHORITY
account will be listed.

.EXAMPLE
"Indy1", "Indy2", "Indy3" | Find-ServiceAccounts | FT

Check Server LON-DC1 : Online
Check Server NotOnline : OffLine
Check Server LON-SVR3 : Online

ComputerName  Online BITS           hkmsvc         NcaSvc         Appinfo               
------------  ------ ----           ------         ------         -------              
Indy1         True   .\Webservice$  ADATUM\Acco... ADATUM\Acco... N/A                     
Indy2         False  N/A            N/A            N/A            N/A                     
Indy3         True   N/A            N/A            N/A            ADATUM\Acco... 

Returns the online status of each server, the services running on all servers,
and the service account used for the services logon account.  Any service
listed as N/A does not exists on that particular server.  Only services
with a logon account that is not a LocalSystem or NT AUTHORITY account
will be listed.


.EXAMPLE
"Indy1", "Indy2", "Indy3" | Find-ServiceAccounts -Quiet | FT


ComputerName  Online BITS           hkmsvc         NcaSvc         Appinfo               
------------  ------ ----           ------         ------         -------              
Indy1         True   .\Webservice$  ADATUM\Acco... ADATUM\Acco... N/A                     
Indy2         False  N/A            N/A            N/A            N/A                     
Indy3         True   N/A            N/A            N/A            ADATUM\Acco... 

Returns the online status of each server, the services running on all servers,
and the service account used for the services logon account.  Any service
listed as N/A does not exists on that particular server.  Only services
with a logon account that is not a LocalSystem or NT AUTHORITY account
will be listed.  This example will not display its progress in contacted 
each server.

.EXAMPLE
"Indy1", "Indy2", "Indy3" | Find-ServiceAccounts -AllAccounts | FT

Returns the online status of each server, the services running on all servers,
and the service account used for the services logon account.  Any service
listed as N/A does not exists on that particular server.  

.EXAMPLE
"Indy1", "Indy2", "Indy3" | Find-ServiceAccounts  | Where-Object {$_.Online -eq $True} | Format-table

Check Server LON-DC1 : Online
Check Server NotOnline : OffLine
Check Server LON-SVR3 : Online

ComputerName  Online BITS           hkmsvc         NcaSvc         Appinfo               
------------  ------ ----           ------         ------         -------              
Indy1         True   .\Webservice$  ADATUM\Acco... ADATUM\Acco... N/A                     
Indy2         False  N/A            N/A            N/A            N/A                     
Indy3         True   N/A            N/A            N/A            ADATUM\Acco... 

Returns the services running on all servers that are currently online
and the service account used for the services logon account.  Any service
listed as N/A does not exists on that particular server.  Only services
with a logon account that is not a LocalSystem or NT AUTHORITY account
will be listed.

.NOTES
All servers must be able to return a ping. If the Windows Firewall is
turned on, you must enable inbound firewall rule:
File and Printer Sharing (Echo Request - ICMPv4 -In)

===============================================================================
Copyright 2012 MCTExpert, Inc.
Licensed for use by participants from classes delivered by Jason Yoder.

This script is provided without support, warranty, or guarantee.
User assumes all liability for cmdlet results.
===============================================================================
This code has been tested in a Windows Server 2012 domain.#>
}

Monday, December 10, 2012

Can you import your previous PowerShell history into the F7 feature of the PowerShell window.


The short answer is no.  We do have the ability to import our PowerShell history from one session to another if we save that history to an XML file.  We can then import that history into another session.  The F7 and up arrow functionality in the PowerShell window is a feature of the window, not PowerShell.  Here is an example.
1. Open PowerShell and execute a couple of simple cmdlets.
2. Type Get-History and press Enter.
image
You can save this information to an xml file for import into another session
Get-History | Export-Clixml History.xml
Either open another PowerShell session or type Clear-History to clear your current session’s history.
Now import your history back in by:
image

If you press F7, you will not get these items in the history window.  You can still use them.  Let’s execute the item in ID 312.
image

Wednesday, December 5, 2012

How to find if a property in a custom object has a NULL NoteProperty

This was a bit of a different problem.  How to find if a property in a custom object has a NULL value.  The client had a collection of objects that they gathered from their environment with PowerShell.  They needed a way to find out if any of the NoteProperties had a NULL value.  I created the function below.  You send it the collection of objects you are interested in probing for a NULL property value and it will return the index number of the object in the collection that has one.

 

Function Find-NullProperty

{

    [cmdletbinding(HelpUri="http://get-help-jason-yoder.blogspot.com/2012/10/find-nullproperty.html")]

    Param (

        [Parameter(Mandatory=$True)]$Object

    )

    # Check to see if an object has any NULL values in

    # its properties.

 

    # Create an object to output to the calling statement.

    $Output = @()

 

    # Index number to return for to denote the instance of an object

    # (should multiple instances be sent) that the Null value if found

    # in.

    $Index = -1

 

    # Extract the names of the properties of the object.

    $PropNames = (($Object | GM) |

      Where {$_.MemberType -eq "NoteProperty"} |

      Select-Object -Property Name).Name

 

    #Cycle through each object

    ForEach ($Obj in $Object)

    {

        # Increment the Index.

        $Index++

 

        # Set to $True is a $Null value

        #is found in a property.

        $NullFound = $False

 

        ForEach ($Prop in $PropNames)

        {     

            If ($Obj.$Prop -contains $Null)

            {

                $NullFound = $True

            }    

        }

        If ($NullFound)

        {

            # Create the object to be returned.

            $Obj = New-Object -TypeName PSObject

           

            # Add object members

            $Obj | Add-Member `

                    -MemberType NoteProperty `

                    -Name "Index" `

                    -Value $Index

           

            # Send the object to the output array.

            $Output += $Obj 

        }

    }

    Write-Output $Output

<#

.SYNOPSIS

Indicates if an object has a property that is $NULL

 

.DESCRIPTION

Search through a collection of custom objects and returns the index

number of any instance that has a $NULL value in a NoteProperty

 

.PARAMETER Object

The Object, or collection of objects that may contain a NULL value

in a note property.

 

.EXAMPLE

Find-NullProperty $Object

 

 Index

 -----

     1

     2

 

Returns the index number of instance of a collection of object in which

a NoteProperty has a NULL value.

 

.NOTES

Provided without warranty or support.

Author: Jason Yoder.

#>

}

 

Monday, December 3, 2012

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple.

# Create a collection with duplicate values

$Set1 = 1, 1, 2, 2, 3, 4, 5, 6, 7, 1, 2

 

# Remove the duplicate values.

$Set1 | Select-Object -Unique

1

2

3

4

5

6

7

What if you want only the duplicate values and nothing else?

# Create a collection with duplicate values

$Set1 = 1, 1, 2, 2, 3, 4, 5, 6, 7, 1, 2

 

#Create a second collection with duplicate values removed.

$Set2 = $Set1 | Select-Object -Unique

 

# Return only the duplicate values.

(Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1).InputObject | Select-ObjectUnique

1

2

This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are different between the two sets.  By asking for the InputObject property, you will get those objects placed in the pipeline.  Finally using the –Unique parameter of Select-Object, you filter any repeat objects.  Without this final step, you will get 

1

2

1

2