Advanced Windows PowerShell Scripting Video Training

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

Monday, January 30, 2012

Get the Access Control List entries on a resource using PowerShell

PowerShell comes with the Get-ACL cmdlet that allows you to see who has security rights to a resource  Below is the syntax:

(Get-ACL –Path path).Access

The path is a location (eg. C:\Logs) that you want to enumerate the ACL for. We first need to create the ACL object before we can view it.  To do that, we encase part of this command in parenthesis.  Once the command completes, we ask for the Access properties.  Below is sample output.

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited       : True
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : 268435456
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : InheritOnly

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited       : True
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : 268435456
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : InheritOnly

FileSystemRights  : Modify, Synchronize
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited       : True
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : -536805376
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : InheritOnly

FileSystemRights  : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited       : True
InheritanceFlags  : None
PropagationFlags  : None

FileSystemRights  : -1610612736
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited       : True
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : InheritOnly

Friday, January 27, 2012

How to get the members of a array, and not the members of the objects in the array in PowerShell

Let’s start off by explaining the situation by creating an array.

$myArray = 1, 2, 3, 4
If I execute $myArray | Get-Member
I get the member information for the integer objects in the array:

TypeName: System.Int32


 
































Name MemberType Definition
CompareTo Method int …
Equals Method bool …
GetHashCodeMethod int …
GetTypeMethod type GetType …
GetTypeCodeMethod System.TypeCode GetTypeCode() …
ToStringMethod string …


 


However, If I execute $MyArray.count, I get a value of 4.  Where did this count property come from?  By looking at the members above, the count property is not listed.  The Count property can from the object of the array, not the objects contained in the array.  To see the members of the object array, type:

Get-Member -InputObject $MyArray


This will give you the members of the object of $MyArray.  Below is a listing of what you will receive.


 



Name              MemberType
----              ----------
Count          AliasProperty
Address               Method
Clone                 Method
CopyTo                Method
Equals                Method
Get                   Method
GetEnumerator         Method
GetHashCode           Method
GetLength             Method
GetLongLength         Method
GetLowerBound         Method
GetType               Method
GetUpperBound         Method
GetValue              Method
Initialize            Method
Set                   Method
SetValue              Method
ToString              Method
IsFixedSize         Property
IsReadOnly          Property
IsSynchronized      Property
Length              Property
LongLength          Property
Rank                Property
SyncRoot            Property


 


You can see that there is an aliased property called Count.  It is a alias for the Length property.  Below is an excerpt from the Get-Member help file.


-InputObject <psobject>
    Specifies the object whose members are retrieved.


    Using the InputObject parameter is not the same as piping an object to Get-Member. The differences are as follows:


    -- When you pipe a collection of objects to Get-Member, Get-Member gets the members of the individual objects in the collection, such as the properties of the integers in an array of integers.


    -- When you use InputObject to submit a collection of objects, Get-Member gets the members of the collection, such as the properties of the array in an array of integers.


 


 




Wednesday, January 25, 2012

How to list the members of every Active Directory group with PowerShell

The code will allow you to see every member of every group in Active Directory.  The output is placed in in object so you can process it through the PowerShell pipeline.

# Import the Active Directory Module.

# You must have access to the Active Directory Module for # this code to work.

Import-Module ActiveDirectory -Cmdlet Get-ADGroup, Get-ADGroupMember

# Create an array to hold the objects as they are created.

$Objects = @()

 

# Store the objects of all groups in Active Directory.

$Groups = Get-ADGroup -filter *

 

# Loop through each group and enumerate the user objects # who are members of each group.

ForEach-Object ($G in $Groups)

{

    # Enumerate each member object of the group

    $Members = $G | Get-ADGroupMember

   

    # Loop through each user object and add data

#to the output object.

    ForEach-Object ($M in $Members)

    {

        # Create a new instance of an object.

        $ObjectData = New-Object PSObject

       

        # Add data to the object.

        # The property of "Group" will be the "Name" property of the

        # current group being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "Group" -Value $G.Name

       

        # The property of "User" will be the "Name" property of the

        # current user being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "User" -Value $M.Name

       

        # The property of "GroupType" will be the "GroupCategory" property

        # of the current group being interrogated.

        $ObjectData | Add-Member NoteProperty -Name "GroupType" -Value $G.GroupCategory

       

        # Add this instance to the object.

        $Objects += $ObjectData

    } # -- End: ForEach-Object ($M in $Members)

} # -- End: ForEach-Object ($G in $Groups)

 

# Send to object to the pipeline.

$Objects

Monday, January 23, 2012

How to list the group membership of a user with PowerShell

Here is a nice example of a one liner.

(Get-ADUser –filter “Name –like ‘Adm*’” –Properties MemberOf).MemberOf

This will return the FQDN of the groups the user is a member of.  The first portion need to execute first and that is why we placed it inside of parenthesis.  We then had to specifically tell PowerShell to give us the MemberOf property.  Once the first portion of the command completes, we have an object to work with.  Now we just simply ask PowerShell to provide us with the MemberOf property.

Wednesday, January 18, 2012

Search a hard drive for image files and copy them to another client with PowerShell

Here is another one of the student projects from Decembers PowerShell class.  In this case, the student needed to examine the hard drive of a computer and discover certain image files.  He then needed to copy those files to another computer and hold them in a folder who’s name contained the source clients name and a date stamp.  This code is still rough as we identified a lot of conflict scenarios that could pop up, but it still works.

 

Function Copy-ImageFile
{
param
(
[
switch]$ListFiles,
$Destination = "C:\Users\Jason\Documents\Roman\Roman2"
)

$Images = Get-ChildItem -Recurse | where{$_.Extension -match "gif|jpg|jpeg|png"}

If ($ListFiles-eq $True)
{
$Images
}
Else
{
# Get the computer name.
$ComputerName = gc env:ComputerName

# Create the name of the folder to copy data to.
[string]$FolderName = $ComputerName + ((Get-Date).Year).ToString() + `
((
Get-Date).month).ToString() + ((Get-Date).Day).ToString()

# Create new folder in Destingation.
New-Item -type Directory -Path $Destination -Name $FolderName

# Copy Image to the destination
$Images | Copy-Item -Destination "$Destination\$FolderName" -Force
}


}
# End: Function Copy-ImageFiles

Copy-ImageFile

Tuesday, January 17, 2012

How to check for processes utilizing to much processor time in PowerShell

 

I’m a bit behind in posting some of this code.  This was one of the projects a student brought to class.  He needed to know how to use PowerShell to monitor if any processes consumed more than 25% of the processor time.  If so, he had a set of services that needed to be restarted.  Below is the code to find out the current processor load with the process restarting code commented out.

 

The get-counter cmdlet gave us the ability to collect multiple samples so that a spike would not trigger the process restart.  In the code below, we took two samples with 1 second between them.  Yes, the variable $CurrentLoad is set with a very long one liner.

 

Function CheckProcess
{
Param
(
$Threshold = 25
)
$CurrentLoad = ((get-counter -counter "\processor(_total)\% Processor time" -SampleInterval 1 -MaxSamples 2) |
ForEach {$_.CounterSamples} |
Select-Object -Property CookedValue |
ForEach {$_.CookedValue} |
Measure-Object -Average).Average
If ($CurrentLoad -gt $Threshold)
{
# Kill Processes
# EX: "Proc1", "Proc2", "Proc3" | Stop-Process
# Pause script to allow processes to stop
Start-Sleep 1
# To Restart Service
# EX: "Service" | Restart-Server
}
}
CheckProcess