Advanced Windows PowerShell Scripting Video Training

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

Friday, August 31, 2012

Where did a User’s Account Get Locked Out?

Updated: May 15, 2015
When this article was originally published, two extra carriage returns were add causing the code to malfunction.  The code below is correct.  

My client for this week’s PowerShell class had a really interesting question. They needed to know where an account is being locked out at. OK, interesting. Apparently users hop around clients and forget to log off, leading to eventual lock out of their accounts. The accounts can be unlocked, but are then relocked after Active Directory replication.
This problem is solved in two parts. The first one is to modify the event auditing on the network. The second part is resolved with PowerShell.
The first part involves creating a group policy that will encompass your Domain Controllers. In this GPO, make these changes.
  • Expand Computer Configuration \ Policies \ Windows Settings \ Security Settings \ Advanced Audit Policy Configuration \ Audit Policies \ Account Management
  • Double click User Account Management
  • Check Configure the following audit events.
  • Check Success
This will allow the domain controllers to audit event 4740 which tells use that an account with locked out. Your users will see something like the image below when their account is locked out.
clip_image001
Once the above GPO has been applied, you will now begin to record lock outs. All accounts currently locked out will not have entries in the Security log until they report another lock out.
The second part is to use PowerShell to parse through all the Security logs on the domain controllers and tell you which client a user’s account was locked out on. This script is designed to be dot sourced or turned into a module. It is heavily commented so it can be used for instruction as well as an actually script in production.
Function Extract-UserName
{
param (
   $StringData
)
   <#
    Extract the username from the log file.
     The following line of code performs several tasks.  It receives
     a multi line string that is the message data from the event.  This data
     is saved in the variable $StringData.  Since this is a [STRING] object
     we have access to the methods Split, Replace, and Trim.

    - The first operation splits the string into an array of single lines.
      This is accomplished with the "Split" method.  The `n tells the
      method to split on each new line.

    - The next operation take the contents in array index [10]

    - The "Replace" method is used to replace the part of the string that we
      do not want.  In this case, we are replacing "Account Name:" with $NULL.

    - The "Trim" method removes all leading and trailing spaces and leaves
      us with just the username.
   #>
   ((($StringData.Split("`n"))[10]).Replace("Account Name:",$Null)).Trim()
}

Function Extract-ComputerName
{
param (
   $StringData
)
   # Extract the computer name from the log file.
   Write-Output ((($StringData.Split("`n"))[13]).Replace("Caller Computer Name:",$Null)).Trim()
}

<#
.SYNOPSIS
Discovers the client that a user account was locked out on.

.DESCRIPTION
Returns the client machine which has locked out a user account.
See the NOTEs section for setup information.

.PARAMETER $User
The Name of the User Account that you want to discover the client
that locked this account out.

.PARAMETER $DaysToSearch
This is the number of days to look back in the security logs.
The default setting is 14 days.

.EXAMPLE
Find-LockingClients -user jyoder

UserName                      LockingClient                TimeLocked
--------                      -------------                ----------
jyoder                        LON-CL1                      8/27/2012
7:02:06 PM
jyoder                        LON-CL1                      8/28/2012
8:53:42 PM

Returns the clients where the user account -jyoder was locked out.

.EXAMPLE
Find-LockingClients -User jyoder -DaysToSearch 7

Returns the clients where the user account -jyoder was locked out.
This will search the security logs for the past 7 days. 
The default is 14 days.


.NOTES
For the cmdlet to work, advanced auditing needs to be configured
on the domain controllers. This can be configured locally or in
Group Policy.  It must be done for all Domain Controllers.

Category: Account Management
Subcategory: User Account Management
Audit for: Success

#>
Function Find-LockingClients
{
Param(
    [cmdletbinding()]
    [Parameter(Mandatory=$True)][String]$User = $(Read-Host "Provide a user name"),
    [int]$DaysToSearch = 14


)
   # Get a list of all of the Domain Controllers
   $DCs = Get-ADComputer -Filter * `
    -SearchBase "OU=Domain Controllers,$((Get-ADDomain).distinguishedName)"



   # Set up the number of days to search in the past.
   $StartTime = (Get-Date).AddDays(-($DaysToSearch))

   # Create the hash for the event logs.
   $LogHash = @{LogName = 'Security';StartTime = $StartTime; ID=4740}


   # Store each relevant event in the variable $Events.
    ForEach($Item in $DCs)
     {

      # Error handling just in case on the Domain Controllers
      # is offline.
      Try
       {
          Write-Host "Gathering events from"$Item.Name-ForegroundColor Green `
           -BackgroundColor DarkMagenta
          $Events = Get-WinEvent -FilterHashtable $LogHash `
          -ComputerName $Item.Name -ErrorAction Stop |
          Sort-Object -Property TimeCreated
       }
      Catch
       {

           Write-host "Domain Controller"$Item.Name" if offline" `
           -ForegroundColor Red `
           -BackgroundColor DarkRed
       }
      Finally
       {
            Write-Host $Item.Name"completed" -ForegroundColor Green `
            -BackgroundColor DarkMagenta
       }
     }



   # Set up the array to hold multiple sets of data from the event logs.
   $EventArray = @()

   ForEach ($Event in $Events)
    {
       # Send the event message data to the functions to extract
       # Username and Computer Name.
       $UserName = Extract-UserName $Event.Message
       $ComputerName = Extract-ComputerName $Event.Message

     
       # Write the data to the object.
       $Obj = New-Object -TypeName PSObject
       $Obj |Add-Member -MemberType NoteProperty -Name "UserName" -Value $UserName
       $Obj |Add-Member -MemberType NoteProperty -Name "LockingClient" -Value $ComputerName
       $Obj |Add-Member -MemberType NoteProperty -Name "TimeLocked" -Value $Event.TimeCreated
     
       # Add the individual object to the array of objects.
       $Obj | Where-Object {$_.Username -eq $User}

    }

   # Filter for the user specified in the parameter $User and
   # Send the output into the Pipeline.
  #$EventArray |Where-Object {$_.UserName -eq $User}


}










Wednesday, August 29, 2012

Install Data Deduplication via PowerShell

In a previous article, I showed you how to install data deduplication using the GUI. In this article, we will install data deduplication remotely via PowerShell.

On a your 2012 server, open Server Manager.

The following assumes that you have added the remote server to the Server Manager that you are working on.

In Server Manager, click All Servers.

Right click the server that you want to install data deduplication on and select Windows PowerShell

Type Add-WindowFeature –Name FS-Data-Deduplication and press Enter.

clip_image001

Wait for the process to complete. No reboot of the remote server is necessary.

clip_image002

Once installed, we use the Enable-DedupVolume –Volume E: cmdlet to enable data deduplication on the E: drive.

image

Using Get-DedupVolume will let you see all the volumes on this server that has data deduplication enabled on them.

image

Use the Get-DedupSchedule cmdlet to get the current deduplication.

clip_image003

The current deduplication optimization that is scheduled runs at low priority. If you want to create one that will run at a higher priority:

clip_image004

This will start a new regularly scheduled data deduplication job at normal priority every Saturday at 3:45 AM that will last for 4 hours.

Monday, August 27, 2012

Did Microsoft change the membership of the everyone group from Win2000 to Win2003?

This is one that I have been thinking about for a while. One of my students in a server 2008 class pointed me to an article that corrected my train of thought. The question is, why is the Everyone group granted access when a share is created? Remember, I’ve been an MCSE since Windows NT4. At that time, the Everyone group included all authenticated users, and those who were on the network anonymously. I found this to be a security vulnerability so I have been advising students to remove this and use the Authenticated Users group instead for general share access for your entire domain. (Caution, it you have a trust relationship set up with another organization, they are also a member of the Authenticated Users group.) This article from Microsoft explains that the anonymous users have been removed from the Everyone group. This change happened in Windows 2003/XP.

Friday, August 24, 2012

How many snapshots can Hyper-V support

Per Microsoft, Hyper-V in Windows Server 2008 R2 will support up to 50 snapshots.  Remember that the more snapshots you created, the slower the performance of the virtual machine.  Also, the physical drive capacity will be used.  When you create a snapshot, a differencing disk is create for every VHD file that VM uses.  The more snapshots you create, the more physical hard drive capacity will be used.

Wednesday, August 22, 2012

Manually start a data deduplication with PowerShell

In some cases you may want to manually start an deduplication process on your Windows Server 2012 storage devices that are configured for data deduplication.

Here we see the same set of files located in three different areas of our e: drive.

clip_image001

To do this, utilize PowerShell.

Type Get-DedupVolume

clip_image002

Since we have not performed any deduplication, we do not have any savings.

Type: Start-DedupJob –Full –Path e: -Type Optimization

You can get the results by typing Get-DedupJob

clip_image003

The Data Deduplication Service is set to manual because it is either activated via a scheduled task or by PowerShell

clip_image004

By executing Get-DedupStatus –Path e:

clip_image005

Since only files that are greater than 32KB can be optimized by data deduplication, only the files that start with Colors will be processed. The total size of these files are 1053KB per instance. The SavedSpace attribute reflects the removed duplicate data plus the reference pointers for the removed data to a full copy of that data.

Monday, August 20, 2012

Recovering an object from the Active Directory Recycle Bin on Server 2012

The Active Directory Recycle bin was a very welcomed addition to our arsenal of tools.  It allowed us to recover objects from the AD Recycle Bin without losing any of their properties.  This was don entirely inside of PowerShell.  Now on Server 2012, you can perform this functionality in the Active Directory Administrative Center.

You can learn how to enable to AD Recycle Bin here.

In the image below, you can see a user named John Doe

image

We can see that John has the Description property populate with “IT Manager”.  Without the AD Recycle Bin, a recovery of this object from a tombstone state would have caused us to lose this data.  More importantly, we would have lost the SID associated with this account.  Using PowerShell, Lets get the SID of this account for comparison purposes.

image

We can see the SID ends in 1122.  The next step is to delete this object.

Switch the AD Administrative Center to Tree View and then click Deleted Objects.

image

Right click the object that you want to restore and then click Restore.

image

The object is restored with all of its properties still intact.

image

Click here to see how to recover an object from the Active Directory Recycle Bin in Windows Server 2008 R2.

Friday, August 17, 2012

Installing Server 2012 Storage Pools

To utilize Storage Pools, we first need to create one.

On your server, open Server Manager.

Click File and Storage Services.

Click Storage Pools

clip_image001

Click Tasks in the upper right hand corner and select New Storage Pool.

In the Before you begin window, click Next.

In the Name field, type a name for your storage pool. For this example, I am using the name UserDataPool.

clip_image002

Click Next

clip_image003

In the Select physical disks for the storage pool window, click on the disks that you want to use. If you do not see the disk that you want to use, verify that the disk is unformatted. Also, the following disk types are supported:

· iSCSI

· SAS

· SATA

· SCSI

· USB

If you are going to use failover clustering with this storage pool, the only disk types that are supported are:

· iSCSI

· SAS

The number of disks that you select will determine the type of a storage pool you can create.

1 disk is the minimum.

2 disks is the minimum for redundancy through mirroring.

3 disks are required for redundancy through parity

5 disks are required for 3 way mirroring.

Once you select a disk, you have three options.

clip_image004

Data Store: This is the default setting. You can use this drives full capacity right now, or for Just In Time (JIT) storage.

Manual: This type of selection allows administrators to control what types of drives are used in different pools. It must be specifically selected at the time of the storage pool creation.

Hot Spare: These drives are not used when the storage pool is created. They come online when a drive fails and the other drives build the needed data on it from their redundant copies.

For this demo, 2 Data Store drives are selected.

Click Next.

Click Create.

clip_image005

Click Close when completed.

clip_image006

You can see the Storage Pool has been created.

Click the Storage Pool and then under Virtual Disks, click New Virtual Disk.

clip_image007

Click Next.

On the Select the server and storage pool window, click the storage pool that you are creating the virtual disk in.

Click Next.

Provide a name for the virtual disk and click Next.

On the Select the Storage Layout window, you have a couple of options. Remember, each option has a minimum number of disks to implement.

Simple: This is disk striping. It allows you to use multiple read/write heads to increase throughput. There is no redundancy in this configuration to protect your data.

Mirror: This configuration requires at least 2 disks and mirrors your data across all disks.

Parity: This configuration requires at least 3 disks. Each disk contains blocks of data, a compressed data. If one drive fails, its replacement is built by using the compressed data on all the other drives.

For this example, I am selecting Mirror since I am only using 2 drives.

Click Next.

On the Specify the provisioning type window, you have two choices:

Thin: This option allows you to provide JIT storage. In other words, capacity on the drives will not be consumed until data is actually place on the device. This comes at with a slight performance hit, but allows you to power down drives until they are needed.

Fixed: The entire capacity specified is reserved at the time of creation, even though there is not any data present. This type of configuration provides better performance.

For this demonstration, I am selecting Fixed.

Click Next.

On the Specify the size of the virtual disk window, type in the value that appears in Storage pool free space. In this case, 38GB.

Click Next.

Click Create.

clip_image008

You may see the above message. If you type a size that is too big, Windows will adjust to the maximum capacity and continue.

Click Close.

Since we left the Create a volume when this wizard closes check box checked in the previous step, the New Volume Wizard opens for us.

Click Next.

Click the virtual disk that you just created (UserDataVD for us) and click Next.

clip_image009

Since we selected for this storage space to be a mirror, we will not have the full capacity of both disks, but half. Click Next.

On the Assign to a drive letter or folder windows, select what is appropriate for your environment. I am selecting drive letter F:

Click Next.

On the Select file system settings window, provide a volume name, a file system type, and an allocation size. My name is UserData and I am taking the defaults on the rest.

You can now turn on data deduplication for this drive. This helps to conserve drive space in environments where users may store identical data in multiple places in your storage pool. Click Next

Click Create.

Click Close.

On the File and Storage Services in Server Manager, click Volumes. Notice that your storage pool is online and ready for use.

Wednesday, August 15, 2012

How much space will Disk Deduplication save me?

After you have installed the Disk Deduplication functionality into Windows Server 2012, you also get a new program called DDPEval.exe By running this utility, you can get an estimate of you disk capacity savings should you implement disk deduplication on a volume. In the example below, you can see how much space would be saved by implementing disk deduplication on this volume.

clip_image001

This volume would greatly benefit from disk deduplication. This command will only run on a volume that you have not enabled disk deduplication. If you run it after you have enabled it, you get the following error:

clip_image002

Monday, August 13, 2012

What is the Primordial Pool in Windows 2012

When working with Storage Spaces in Windows Server 2012, you may notice a Storage Space that you did not create called Primordial.

clip_image001

This is simply a holding pool for all unallocated disks that are connected to the server that you are currently managing. If you create a storage pool, you will be able to grab the disks from this pool to use in the new storage pool.

Friday, August 10, 2012

Format a new disk on Server 2012

With Sever 2012, you can still use the old Disk Management MMC to manage disks like you have since Windows 2000. In Server 2012, you have a new option. For Server 2012 you can use the File and Storage Services in Server Manager to accomplish the tasks that you use to perform in the Disk Manager.

Open Server Manager and click File and Storage Services.

Click on the Disks menu item. Take a look below.

clip_image001

You can see that Disk 0 is offline.

Right click disk 3 and select Bring Online.

clip_image002

Click Yes to confirm if prompted.

To format the disk, right click it again and select New Volume.

Click Next.

If you are managing the disks on a different server, make sure you select the correct server. Also, click the disk the create the volume on.

clip_image003

Click Next.

Select how much of the drive that you want to include in the volume and click Next. The default is the maximum drive capacity.

On the Assign to a drive letter or folder window, select what is appropriate for your environment.

Click Next.

The two available file systems are NTFS and ReFS.

Provide a volume label.

Take note of the option to force this drive to only use 8 character names. This is to help with backward compatibility with older 16 bit applications and is not recommended.

Click Next.

clip_image004

The Enable Data Deduplication window will be new to most users. Data deduplication helps to save considerably on areas where static data is stored. You can enable data deuplication on this volume now if you wish. Click Learn more about data deduplication before enabling this option.

Click Next.

clip_image005

Click Create.

clip_image006

Click Close.

Click on the disk ID in File and Storage Services window in Server Manager that you just worked on to see your new volume.

clip_image007

If you need to delete the volume, right click it and select Delete Volume.

Click Yes at the confirmation.

Click Close when the wizard completes.

clip_image008

Wednesday, August 8, 2012

Turn on Data Deduplication

Over many years as a Network Administrator, I constantly struggled with the data storage needs of my users. Not only did we need to allocate funds for greater amounts of storage, but also greater amounts of funds for backup and recovery operations that would meet the needs of the organization.

One of the big problems was duplicate information being stored by multiple users. Duplicate data adds to your cost in several ways.

· Increase in storage cost due to capacity depletion from duplicated data.

· Increased number of backup media, and the cost associated with storage, transportation, and replacement of the media.

· Increased recovery times.

· Purchasing and deployment of new disaster recovery hardware so backup and recovery operations can stay within established time frames.

Data Deduplication can help reduce the cost of the above bulleted points. Data deduplication will remove duplicated blocks of data and place references to a single copy stored on the volume. It works well for data stores that are not frequently changed and will not work on boot partitions or partitions containing the operating system. You can achieve reduced storage capacity for file shares, software deployment shares, and virtual hard disk libraries. Data deduplication is only support on the NTFS file system and not on the new Resilient File System (ReFS).

Here is how you turn it on.

First we need some duplicate files. (OK, not really, but I wanted to have some files on the drive.)

image

Here you can see that we have a couple of files that are store in different locations, but are duplicates of each other. They also reside on an NTFS formatted volume that does not contain the boot or OS partition.

Open Server Manager and click Manager –> Add Roles and Features.

Click Next three times.

Expand File and Storage Services –> File and iSCSI Services.

Check Data Deduplication and click Next.

clip_image002

Click Next and then Install.

Click Close.

You can monitor the installation in Server Manager.

clip_image003

No restart is necessary.

On the Server Manager click File and Storage Services.

clip_image004

Click Volumes

clip_image005

Right click the E: drive and select Configure Data Deduplication. (Note: it may take a few minutes before you can select Configure Data Deduplication.)

clip_image006

Check Enable data deduplication.

Click Set Deduplication Schedule

Check Enable throughput optimization. This will set the time when data deduplication will run with normal priority. This allows time for more processor capacity to be dedicated to the deduplication process.

Click OK twice.

Data Deduplication is now set up.

Monday, August 6, 2012

Add additional servers to Server Manage

In Windows Server 2008, we were able to manage different servers in the Server Manager. The problem with this implementation is that we could only manage one server at any one time. In windows Server 2012, we now have the ability to quickly switch between multiple servers, and to execute the same functionality against multiple servers at the same time. To do this, we need to add the servers that you want to manage to your server manager.

In Server Manager, right click All Servers and select Add Servers.

clip_image001

Type in the name, or part of the name of the server. Click Find Now.

clip_image002

Click the name (or names) of the servers that you want to manage from this server and click the right pointing arrow button.

Click OK.

clip_image003

You can now manage the new server from this physical server’s Server Manager.

Friday, August 3, 2012

Reset Trust Relationship Without Rebooting

On a domain joined Windows Client, you may get an image like this:

clip_image001

(From Windows 8)

This means that the client computer’s account with the domain had a password change but for some reason your client does not know the password. This can happen if you restore your client operating system from a backup. To fix this, we would normally rejoin the client to the domain. This would cost us a reboot. Here is an alternative.

· Log into the client as a local administrator.

· Open PowerShell

· Type Test-ComputerSecureChannel

clip_image002

Notice the response back is False That means the secure channel cannot be negotiated between the client and the domain controller. The secure channel allows for your client to verify that it is talking with the correct domain controller. If the secure channel does not work, then you cannot log in. Here is how to fix this.

· Type Test-COmputerSecureChannel –Credential <Domain/DomainUser> -Repair and press Enter.

clip_image003

· Provide the domain users password and press Enter.

clip_image004

Notice the response is now True.

· Log off as a local user and log in as a domain user.

You should now be able to log in without a reboot.

This will also work on Windows 7.