Advanced Windows PowerShell Scripting Video Training

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

Thursday, March 31, 2011

What is the maximum capacity of a Pass Through disk?

Pass Through disks are ideal in situations in which you need to exceed the 2 TB capacity limitation of the .VHD format.  In using a Pass Through disk, you will not have the ability to use snapshots.  The maximum size for a Pass Thru disk is????  Unfortunately after a long Google and Bing session, I could not find this answer.  I did find an article about an organization that linked (6) 2 TB hard drives and created a 12 TB pass-through disk that was functional.  I also saw that during some maintenance, they had a problem getting the VM back online.


As always, test before putting a new configuration into production.


Please post your maximum Pass Through disks sizes here and tell us how successful your implementation has been.

Wednesday, March 30, 2011

Creating a Capture image with WDS

The Capture image in Windows Deployment Service allows you to capture an image without having to create a WindowsPE boot disk.  This process will automatically transfer the captured image to the image storage location that you created when you set up WDS.

First you need to have the WDS server setup correctly. Once you have installed your images from an installation DVD, click Boot Images.

Right click the boot image and click Create Capture Image.

image

Enter the Image name and a description for it.

Click Browse.

You now need to go to the Sources folder on your installation media and find the file called boot.wim.

image

Click Next

Once the image loads, check Add image to the Windows Deployment Server now and click Next.

Click Next three times.

Click Finish


Next you need to boot your client to LAN.  You may have to reconfigure your BIOS settings or press a function key to get to your boot menu.

Take note that depending on your configuration, you may have a couple of steps to perform. 
You may need to set the PXE boot policy.  To do this, open Windows Deployment Services

Right click your server name and then click Properties.

image

Click the Boot tab.

Depending on whether or not you pre-staged the client, you will have two options.  The first one for Known clients is for pre-staged clients.  The second set of options for Unknown clients controls clients that you have not pre-staged.  In the example below, I want my non pre-staged client to go ahead with a PXE boot.

image


If you client hangs, such as below, you must provide for administrator approval.

2010-12-30_16-47-27_363

To set this policy, go to your server properties again, but this time click the PXE Response tab.
The default setting of requiring Administrator approval for unknown clients is recommended.  This prevents rouge clients for obtaining a copy of your images.

image

To allow this process to continue, we need to approve the PXE boot of this client.  Click Cancel to close the WDS server properties.

Click Pending Devices.

image

The above image shows a client that is waiting for the administrator to approve its loading the organization PXE environment,

Right click the client in click Approve.

image

Click OK

The PXE environment will start to load in a few seconds.

2010-12-30_16-59-42_923

Once the GUI loads, select you language and click Next

You will now need to enter an account that is authorized to allow images to be deployed.  It is in the format of domain\user. Enter the credentials and click OK.

At the Welcome to the Windows Deployment Services Image Capture Wizard click Next.

2010-12-30_17-25-45_991

On the Directory to Capture Window, you will be able to choose the volume that you ran SYSPREP on.

Select the volume.  (Note: the volume label may have changed)

Provide both a descriptive name and description.  Click Next

2010-12-30_17-33-47_132

On the New Image Location, you can choose to store the image locally, or transfer it to a WDS server.
Browse to a location where you want to store this image locally and give it a name.  I had to right click in Windows Explorer and create a text file.  This is the one that I selected.  A little odd and I have not found a suitable explanation for this, but it worked.

In this scenario, we are uploading to a WDS server.

Check Upload image to a Windows Deployment Services Server (Optional)

In the Server Name: field, type the name of the server and click Connect

You will be prompted for administrative credentials.

In the Image Group Name: drop down box, select the image group that you want to store this image in.  The Image group is created in WDS.

Click Next.

The image will be captured. Do not be alarmed if it takes a few minutes before the progress bar starts moving.

The client will reboot once the capture is completed.  If all went well, you should now have this image listed in WDS under Images.

Tuesday, March 29, 2011

Application encountered an error when starting a VM in Hyper-V

If you recently made a change to the Boot Configuration Data store, you may see this error when starting a VM in Hyper-V

image

First, verify that virtualization support is turned on in your BIOS.  If it is and a power cycle of the server does not resolve the problem, you may not have the Hypervisor loading during the boot sequence.  To check for this problem, open a command prompt with administrative privileges.

Type bcdedit and press Enter

image

Tyhe output in red is the currently loaded boot configuration The output in blue is a boot configuration that will allow Hyper-V to run. Notice the data in green is missing from the current boot configuration.

Type bcdedit /set {current} hypervisorlaunchtype auto and press Enter.  You should get a response The operation completed successfully.

Type bcdedit to see the new results.

image

Now, restart the server and give it a try.

Monday, March 28, 2011

Enable PowerShell V2 Remote Management via Group Policy

One of PowerShell V2’s strongest assets is its remote management capability.  When you enable remote management, a few actions are taken.

 

  • Enables the WinRM service
  • Starts the WinRM service.
  • Set’s the WinRM Service to start automaticlly.
  • A modification is made to the Windows Firewall to permit incoming WinRM connections.  (Outgoing connections are allowed by default.)
  • Windows PowerShell is registered as a WinRM endpoint.  Both the 32 and 64 bit versions are registered.  This allows the WinRM service to be able to send and received back commands and information to applications on your remote clients.
  • You will be prompted (if manually doing this) to confirm your decision.  This is because this action has an impact level of “high".

 

You can manually enable PowerShell Remoting by opening a PowerShell session with local administrative rights and entering the cmdlet Enable-PSRemoting.  You will be prompted to confirm your choice and the cmdlet will execute the necessary actions.  You can see a screen shot below.

image

 

 

This requires you to visit each client that you want to run PowerShell remoting on.  The easier and more effective way of doing this in the enterprise with Group Policy.

 

Open up Group Policy Management.

Expand your Forest / Domains / DomainName

Right Click Group Policy Object and click New.

Provide a name for this GPO. For this demonstration, I named mine PSRemoteSetup.

Right click your GPO and click Edit.

Expand Computer Configuration / Policies / Administrative Templates / Windows Components / Windows Remote Management (WinRM) / WinRM Service.

Open Allow automatic configuration of listeners
- Set this policy to Enable
- Enter * in IPv4 filter:
- Enter * in IPv6 filter:
- Click OK

Expand Computer Configuration / Policies / Windows Settings / Security Settings / Windows Firewall with Advanced Security / Windows Firewall with Advanced Security
- Right click Inbound Rules and select New Rule.
- Select Predefined.
- In the drop down box, select Windows Remote Management
- Click Next
- Check only Windows Remote Management (HTTP-In)
- Click Next.
- Select Allow the connection.
- Click Finish

If this policy is going to be applied to only Windows Server 2008 servers, exit Group Policy Management Editor.  If this policy is going to be applied to Windows Vista or Windows 7 clients, we need to enable one more Group Policy.

Expand Computer Configuration / Policies / Windows Settings / Security Settings / System Services

Double click Windows Remote Management (WS-Management)

Check Define this policy setting

Select Automatic

Click OK

Exit Group Policy Management Editor.

 

Now link this GPO to the OUs that contain the computer objects that you want to remotely manage with PowerShell.

Friday, March 25, 2011

Optimize your VMM CPU utilization

For VMM implementations of over 150 hosts, Microsoft advises you to enable Server Optimized Garbage Collection (GC).  Workstation GC is the default and is only available on single processor systems.  Server GC is available for multiprocessor computers. This method, according to Microsoft, starts to provide benefits of computers with 4 or more processors.  Below are the instructions to implement Server Optimized GC from Microsoft.

To accomplish this, simply create a new filed named vmmservice.exe.config and place this file in the same location as vmmservice.exe (VMMservice.exe is located in the bin directory of the VMM server role installation)

This link: http://go.microsoft.com/fwlink/?LinkId=102219, will show you what the contents of this file need to be.

Reference:
http://blogs.technet.com/b/m2/archive/2009/02/04/how-to-enable-server-optimized-garbage-collector-for-vmm.aspx
http://msdn.microsoft.com/en-us/library/cc165011(office.11).aspx

Thursday, March 24, 2011

Implementing Failover Clustering for Hyper-V

Virtualizing your servers is a good way to reduce your expenses through hardware reduction.  You simply take several underutilized servers and move their activities to a single server.  This does create the obvious issue of single point of failure.

This set of instructions will help you set up a test lab for Hyper-V failover.  In a production failover environment, you would utilize at least 2 servers for the fail over cluster.  It is best to use two identical servers for this purpose. Also, you need to check to make sure all the hardware in the servers is supported by Windows Server 2008 R2.  It increases the chances of a successful failover.  You should also have 2 NICs in these servers.  One for the public network, and one for the storage network.  The final element will be a highly available storage system.  This storage system will hold the virtual machine.  A simple diagram of this setup looks like this:
image

In this test, we will use a third server acting as or storage device. Since the iSCSI Target Software requires either Windows Storage Server or the specific iSCSI Target software from your vendor, I am adding a virtual machine to our storage server.  This VM will serve as our iSCSI target.
image

Our Hyper-V machines will be called Lab1 and Lab2.  Our storage system will be hosted on a Windows 2008 R2 Hyper-V server.  The VM will be called SAN-VM.

Step 1: Set up virtual network.
In step 1, we will configure a virtual network that will allow our virtual machines to to communicate outside of their host server.

On both Lab1 and Lab2, open Hyper-V Manage.

In the Actions pane, click Virtual Network Manager

Select External and then click Add.

Provide a descriptive name for this network connection.  I am calling this one SAN.

Enter a description if you wish.

From the dropdown list, choose the network adapter that is connected to your SAN.

Click OK.

On the Apply Networking Changes window, click Yes.


Step 2: Install iSCSI target on the storage server.
Remember, you need Windows Server 2008 storage server or the iSCSI target software from your OEM to continue with this procedure.

On SAN-VM, click Start \ Administrative Tools \ Microsoft iSCSI Target Software.

Click YES or log in if the UAC prompt appears.

Right click iSCSI Targets and then click Create iSCSI Target.

On the Welcome to the Create iSCSI Target Wizard page, click Next

In the iSCSI target name field, type LUN-01 (You can use any name you want here.)  Click Next.

On the iSCSI Initiators Identifiers page, click the Advanced button.

In the Advanced Identifiers dialog box, click Add.

Change the Identifier type to IP Address.

Set the IP address of one of the two servers you will be using in the cluster. 

Repeat this above process to add the second servers IP address.  For my setup, I entered 192.168.1.50 and 192.168.1.114.

image

Click OK.

On the iSCSI Initiators Indentifiers page, the IGN Identifier field show display “Click Advanced button to view alternate identifiers”  Click Next

Click Finish


Step 3: Create and set up an iSCSI target for the witness disk of the Failover Cluster.

In the iSCSI Target – [Microsoft iSCSI Software Target] window, right click Devices and select Create a virtual disk.

Click Next

In the File field, type the full path of the virtual hard disk you want to create.  I entered C:\Disk01.vhd and click Next.

In the Size field, I entered 8000.  Enter what is appropriate for your witness disk.

Click Next.

Enter a description if necessary and click Next.

On the Access page, click Add.

Select the iSCSI target you created earlier.  In this case LUN-01 and click OK.

Click Next.

Click Finish.


Step 4: Create and setup a iSCSI target for the Virtual Machine that you will make highly available.

In the iSCSI Target – [Microsoft iSCSI Software Target] window, right click Devices and select Create a virtual disk.

Click Next

In the File field, type the full path of the virtual hard disk you want to create.  I entered C:\Disk02.vhd and click Next.

In the Size field, I entered 20000.  Enter what is appropriate for your witness disk.

Click Next.

Enter a description is necessary and click Next.

On the Access page, click Add.

Select the iSCSI target you created earlier.  In this case LUN-01 and click OK.

Click Next.

Click Finish.


Step 5: Connect the iSCSI target to Lab1

Perform the following proceeds on one of the Hyper-V servers that you will be clustering.  In this case, I am using the server named Lab1.

Click Start \ Administrative tools \ iSCSI Initiator.

Click Yes if prompted.

In the iSCSI Initiator Properties window, click the Targets tab.

In the Target field, enter the IP address of the iSCSI target.  In this case, it is the SAN-VM IP address of 192.168.1.115

image

Click Quick Connect.

The Status of the connection should be Done.

Click Done.

Click OK.


Step 6: Set up the volumes on the shared storage.
This procedure is being done on Lab1.

Open Server Manager.

Expand Storage and click Disk Management.

Located the 2 disks that are Unallocated. These are the two VHDs that you created on SAN-VM.  Notice the two different sizes.  The smaller one will be our witness disk and the larger one will be for the virtual machine.

image

Right click each disk and then click Online.

Right click one of the disks and select Initialize Disk

Make sure both disks are selected and click OK.

Right click the 7.81 GB disk and select New Simple Volume.

Click Next twice.

Provide the drive letter that you want to use for the witness disk.  For this demonstration, I am setting the drive to Q:.

Click Next.

Enter a volume label.  For this disk, I am entering Witness.  Click Next.

Click Finish.

In the Disk Management window, right click the 19.53GB disk and select New Simple Volume.

Click Next twice.

Provide the drive letter that you want to use for the witness disk.  For this demonstration, I am setting the drive to N:.

Click Next.

Enter a volume label.  For this disk, I am entering VM Storage.  Click Next.

Click Finish.


Step 7: Create an iSCSI target on Lab2

This procedure will be done on the second Hyper-V server to take part in the cluster.

Click Start \ Administrative Tools \ iSCSI initiator.

Click Yes if prompted.

In the Target: field type the IP address of SAN-VM (Your storage server ip address).  In this case, it is 192.168.1.115.

Click Quick Connect.

Click Done.

The status of the connection should be Connected.

Click the Volumes and Devices tab.

Click Auto Configure.  You should now see the two volumes.

image

Click OK to close the iSCSI Initiator Properties.


Step 8: Install Failover Clustering feature on both servers.
Perform this procedure on both servers that will be nodes in the cluster.  In this case, I will be performing it on LAB1 and LAB2.

Open Server Manager.

Click Features

Click Add Features

image

Check Failover Clustering and click Next.

Click Install.

Click Close when the installation completes.

Close Server Manager.

Remember, you must perform Step 8 on both servers that will be nodes in the cluster.


Step 9: Validate the cluster

The Failover Cluster Manager of Server 2008 has a feature to validate the cluster before you build it.  This feature will help to point out potential issues with the cluster before you commit to it.

On LAB1, click Start \ Administrative Tools \ Failover Cluster Manager.

In the Actions pane, click Validate a Configuration.

Click Next.

Click Browse.

Enter the names of the two servers, separated by a semicolon.

image

Click Check Names.

image

If all looks good, click OK.

Click Next

Select Run all test (Recommended) and click Next.

Click Next in the Confirmation window.

image

Let the test complete.  This will take some time.

Once the Validate a Cluster Wizard completed, review the report.  Warnings can be ignored in a test environment but should be addressed in a production environment.

Click Finish


Step 10: Create the Cluster

One Lab1, in the Failover Cluster Manager, click Create a Cluster in the Actions pane.

Click Next

Click Browse

Enter you’re the names of the servers that will be part of the failover cluster.  Separate the names with semicolons.  Click Check Names

Click OK

Click Next

On the Access Point for Administering the Cluster page, type in the Cluster Name field, Demo-Cluster (or any name that is appropriate).

Type in the IP address to be used for this cluster. I used 192.168.1.240

image

Click Next.

Click Finish.



Step 10: Enable the cluster shared volumes

In these next few sections, you will need to replace your FQDN with the ones that I am using.  From hear on out, we will say that my FQDN is ABCD.COM.

On Lab1, in the Failover Cluster Manager, expand. Demo-Cluster.ABCD.COM and then click Demo-Cluster.ABCD.COM.

On the right hand side in the Actions pane, click Enable Shared Volumes.

Select I have read the above notice and then click OK.


Step 11: Add one of your disks to the Cluster Shared Volume.

On the Failover Cluster Manager, right click Cluster Shared Volumes.

Click Add Storage.

Select Cluster Disk 2 (May be different for you).

Click OK.

In the Failover Manager, under Demo-Cluster.ABCD.COM click Cluster Shared Volumes

Expand Cluster Disk 2 and then verify it is using C:\ClusterStorage\Volume1 (Note: your exact path may be different.)


Step 12: Create a virtual machine in the cluster storage.

At this point you will create a virtual machine in accordance with your companies policy.  you will store the VM at C:\ClusterStorage\Volume1.

Once you build the virtual machine, open its properties.

Click Processor

Check Migrate to a physical computer with a different processor version.  This will allow the VM to fail over to a server that has a different processor.

image



Step 12: Configure your virtual machine to be able to fail over

On the Failover Cluster Manager, expand Demo-Cluster.ABCD.COM

Right click Services and applications and then select Configure a Service or Application.

Click Next

On this page, you select the application or service that you want to be able to failover.  Click Virtual Machine.

On the Select Virtual Machine page, check the name of your VM and click Next.

Click Next

Click Finish


Step 13:  Test the Live Migration of your virtual machine.

Start your virtual machine.

Open up event viewer or some other application and leave it on the screen.  You will use this to show that the VM did not shutdown or log off during the migration.

In the Failover Cluster Manager, right click your VM.

Point to Live migrate virtual machine to another node.

Click the option to live migrate the VM to your other node and then click Exit twice.

Monitor the server hosting the VM, it will change to the other server.

Open the Hyper-V manager on your other server and notice that your VM is running on it.

Wednesday, March 23, 2011

How to set Quota Points for VMs in VMM

In System Center Virtual Machine Manager, you can create a quota point system to restrict how many VMs your self service users can run at any one time.  By using the quota points, you can prevent your users from accidentally, or intentionally creating a Denial-of-Service attack on your host servers.
We all know that virtual machines do not have to be created equally.  In other words, they may consume more or less resources than other VMs.  For this reason, you can assign a different quota point value to different virtual machines.  That way a single user, or group of users will not fire up resource intensive VMs and bring your hosts to their knees.

To do this, open System Center Virtual Machine Manager.

On the menu bar, click Go \ Virtual Machines

Right click the VM that you want to change the default quota point value for. Click Properties

Click the Settings tab.

Notice the default value for the Quota is 1.  For VMs that are resource intensive, you may want to increase this number. 

Click OK when you are finished.

image

Tuesday, March 22, 2011

Change the description on a multi-boot server.

For those of use who need to have a server that can boot into multiple Operating systems, we may have an issue on the boot menu where we have different bootable operating systems with the same name.  Take a look below.
 

I got to this by clicking Start and then right clicking Computer and selecting Properties.

In the upper left, I clicked Advanced System Properties.

On the System Properties window, I clicked the Advanced tab.

In the Startup and Recovery box, I clicked Settings…


image

You can see in the Default Operating System dropdown, I have two Windows Server 2008 R2 configurations listed, Which one do I want to use?  Here is how to fix that.

Open an command prompt with Administrative level permissions.

Type bcdedit /enum and press Enter

We are interested in the Description and the Identifier.  Since the OS that I want to change the description is the current default boot, I simply need to look for an ID of {current}.

image

Now type bcdedit /set {current} description “What ever you want and press Enter

Once you are done, simply type bcdedit /enum and you will see your change.  This will be reflected in the Advance System Properties and more importantly, in the boot menu.

Monday, March 21, 2011

How to determine which ports your AD LDS instance is listening on.

 

On occasion, you may have misplaced your documentation on which ports AD LDS is listening on.  We have all “misplaced” our documentation before. 

Open a command prompt with administrative privileges on the server hosting the AD LDS instance.

Type dsdbutil “li I” q and press Enter

image

In the above image, you can see both the LDAP port and the secure LDAP port being used by the AD LDS instance.

Friday, March 18, 2011

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below.

image

The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings.


Create action
image
This give you a green triangle. The Create action creates a new mapped drive for users.

Replace Action
image
The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping.

Update Action
image
The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the mapped drive. If the drive mapping does not exist, then the Update action creates a new drive mapping.

Delete Action
image
The Delete action will give you a red ‘X’. This will remove a drive mapping.

Thursday, March 17, 2011

How to enable management of Remote Desktop Services with PowerShell

Like all OS components and software from Microsoft that you want to manage with PowerShell, you need to import the proper module.  To get a list of all available modules, open a PowerShell session.

Type Get-module –ListAvailable and press Enter.

Since the installed server roles, features and software determine the returned list, your list will be different then mine.  To ensure that I am able to import the module that I need, make sure the role, feature, or software is installed.  Once it is installed, you can import the appropriate module.

Import-Module RemoteDesktopServices

This will import the cmdlets associate with the role service of  Remote Desktop Session Host.  As you add additional role services, additional cmdlets will be available to you. 

Wednesday, March 16, 2011

What versions of Windows 2008 R2 is the Active Directory Recycle Bin available on?

The Active Directory Recycle Bin is available for:

  • Windows Server 2008 R2 Standard
  • Windows Server 2008 R2 Enterprise
  • Windows Server 2008 R2 Datacenter

The AD Recycle Bin is not available on:

  • Windows Server 2008 R2 for Itanium-Based Systems
  • Windows Web Server 2008 R2


Just remember that you must be at Windows Server 2008 R2 Forest functional level before AD Recycle Bin is available.

Tuesday, March 15, 2011

How to launch a PowerShell Script without typing the full path name

When you are in the PowerShell shell environment, executing a script can be a bit of a pain.  Normally you need to type the entire path to get the script to execute.  For example, you may need to type C:\Users\JohnDoe\Scripts\Myscript.ps1.  You do not have to do this.  If you are in the directory that the script resides, simple type .\MyScript.ps1 and it will execute

Reference: http://technet.microsoft.com/en-us/library/ee176949.aspx

Monday, March 14, 2011

How to get an external users information to pop up in Outlook without purchasing an Exchange CAL for them

Exchange CALs (Client Access License) can be expensive and you may not want to manage an email account for an external contact such as a contractor. You can still provide that contact data in your Exchange GAL (Global Address List) for your users to easily access without purchasing a CAL.

On the Exchange server, open the Exchange Management Console.

Expand Microsoft Exchange On-Premises (domain name) / Recipient Group.

Right click Mail Contact and select New Mail Contact. At this point you have a choice of configuring an existing contact from Active Directory, our creating that contact in Active Directory from the Exchange Management Console. From this article, select New Contact and click Next.

You can now select the OU to store this contact by checking Specify the Organizational Unit rather than using the default one and clicking Browse

image

The default container will be the Users container, unless you have redirected it.

Choose the OU to store the contacts. In the case below, an OU called External Contacts is being used.
Click OK

image

Fill in the information for the contact. Click Edit and provide the email address for the contact. Click Next.

image

Click New.

image

The status of this contact will change to Pending it will take a few seconds to create.

image

Once the status changes to Completed, click Finished

image
In testing on a client machine, the contact showed up in the Global Address List in Outlook.

Friday, March 11, 2011

How to create a drive map with GPO Preferences

Once you have your shared folders correctly configured, you can use Group Policy Preferences to configure the drive mappings on your clients.  This is a nice improvement from the days of using VBScript to map drives on your clients and it also saves us a lot of time in customizing the drive mappings.
In your Group Policy Management Console, either use an existing GPO, or create a new one.  In this case, I created a GPO called DriveMappings.

Expand User Configuration \ Preferences \ Drive Maps

Right click Drive Maps and select New \ Mapped Drive














In the New Drive Properties window, fill in the information below

In the Action: field, select Create

In the Location field, select the UNC path to your share.

In the Label as: field, provide a name.

In the Drive Letter: area, choose what is appropriate

Click OK.

image

If you want to designate a mapped drive for different users, you can use security groups to determine which users get which location mapped to them.  That way Drive G will point to one location for one set of users and drive G will point to another location for other users.

In the New Drive Properties window, click the Common tab.

Check the Item-level targeting check box and click the Targeting… button.

image

Click New Item.

From the drop down box, select Security Group.

image


To the right of the Group field, click the image Button.

Add in the security group that you want this drive mapping to apply to and click OK.

If you are concern about conflicts with other security groups that a user may be a member of, you can check the Primary Group check box.

image

That will set this preference to only process if the specified group is the users primary group.  To set a group as a primary group for a user, open that users object in Active Directory Users and Computers.

Click the Member Of tab.

Click the group that you want to make as the primary group for that user.

Click the Set Primary Group Button.

image

Thursday, March 10, 2011

How to take a list of user accounts located in different OUs and move them into one with PowerShell

In smaller environments, you will from time to time need to move user accounts from one Organizational unit to another.  Active Directory Users and Computers will work fine for this task. In larger environments, you may need to move hundreds at a time.  Using AD Users and Computers for a task like this is inefficient and will greatly increase the labor cost of the project.  The labor being yours of course.

This question came from one of my Windows 2008 Server classes.  It actually came as a question from a lab as to whether or not PowerShell could do this.  Not only can it do this, bit it can do it much faster and in a more robust way then the manual method.

To set this problem up, I created the OU structure below:

image

I have 3 users each in the Indianapolis, Denver, and Tampa OU.  I want to move 6 of those nine users into the Dallas OU.  This is a very small move.  Scale this problem out to 9,000 total users with 6,000 of them needing to be moved.  now we have a problem.  The script at the bottom will work for larger environments.

You first need to obtain a list in a text file of the users whom you need to move.  Below is our list:

Neil Armstrong
Buzz Aldrin
George Washington
Barbara Bush
John Doe
Jane Doe


All we need to do is to read this into PowerShell and have it move those user object to the new OU.  What fun would this be to leave it at that.  We need to provide some error checking and a report of any user accounts that were not found.  Let’s start with the basics.  How to move a user account from one OU to another.

I first open the PowerShell environment and imported the Active Directory cmdlets by typing import-Module ActiveDirectory.

Next I user the Get-ADUser cmdlet to grab the object of one of those user accounts.  I also assign it to the variable $UserAccount.

$UserAccount = Get-ADUser –Filter {Name –like “George Washington”}

The property of the user object called DistinguishedName will have the LDAP path to the user account, CN=George Washington, OU=Denver, DC=MCTNet, DC=com, which is the format needed for our next cmdlet.

Our next step is to move the user object to the new OU using the Move-ADObject cmdlet.

Move-ADObject $UserAccount.DistinguishedName –TargetPath “OU=Dallas,DC=MCTNet,DC=com”

Now let’s turn this into a script that will handle thousands of moves automatically and keep track of any problems.

<#
===========================================================
Script Name: MoveUsers.ps1
Author: Jason A. Yoder, MCT
Website: www.MCTExpert.com
Blog: www.MCTExpert.Blogspot.com
===========================================================

===========================================================
Script Purpose:
Demonstrate how to take a list of user names and move them
to a specified OU.  This script will also create a list
of any user accounts that were not found in Active
Directory
===========================================================


===========================================================
Requirements:
PowerShell V2
Designed to be run on a Domain Controller

===========================================================

===========================================================
Global Varibles

$UserAccount
User to hold the user object information

$UserList
Holds the list of user names from the text file.
#>

$ScriptPath = "E:\MoveUsers"
# The file path where all the scripts files are stored.

$UserListFile = "UserList.txt"
# File name of the the document holding the user names.

$TargetOU = "OU=Dallas,DC=MCTNet,DC=com"
# The target OU where you want the user accounts to
# be moved to.

$ErrorLog = "ErrorLog.txt"
# Text file that stores the error data.

$ErrorCount = 0
# Holds the number of errors the script experienced.

# == End of Global Variables ================================

# ===========================================================
# Functions

Function Prep-ErrorLog{
# Clears the error log and places a header in it.
# Line 1 Captures the current date/time
# Line 2 Creates the text of the header. Lines 3 and 4
# are part of that header.
# Line 5 clears the contents of the error log and writes the header.

    $Date = get-date
    $Header = "Error log for MoveUsers.ps1 `r
    Startdate $Date `r
    ======================================"
    Set-Content -Path $ScriptPath\$Errorlog -Value $Header

}
# --End of Function: Prep-ErrorLog--------------------------

Function Get-UserNames {
# Places the contents of the user list text file into the
# variable $UserList.
    $Global:UserList = Get-Content -Path $ScriptPath\$UserListFile
}
# --End of Function: Get-UserNames--------------------------

Function Move-UserAccounts ($UserList){
    # The for loop will cycle through each name from the
    # UserList.
    For ($i = 0; $i -lt $UserList.Count; $i++){
   
        # Get the User object that matches the user name
        # from the list.
        $TestName = $UserList[$i]
        $UserAccount = Get-ADUser -Filter{Name -like $TestName}
      
        # Move the User Object to the designated OU.
        Move-ADObject $UserAccount.DistinguishedName -TargetPath $TargetOU
        
        # If an error occurs, write it to the error log.
        If($? -eq $False) {
           
            # Error log text string.
            $ErrorText = "User $TestName not found in Active Directory"
           
            # Append the error log string to the error log file.
            Add-Content -Path $ScriptPath\$Errorlog -Value $ErrorText
           
            # Increment the Error Count variable.
            $Global:ErrorCount = $Global:ErrorCount+1
        }
    }
}
# --End of Function: Move-UserAccounts-----------------------

# == End of Functions =======================================
# ===========================================================
# Main Code:

# Write text to the screen to let the user know the script
# has started.
Write-Host "Script: MoveUser.ps Starting"

# Set the error action preference to allow the script to
# continue past non fatal errors.
$ErrorActionPreference="SilentlyContinue"

# Load the Active Directory module for PowerShell.
Import-Module ActiveDirectory

# Execute the functions
Prep-ErrorLog
Get-UserNames
Move-UserAccounts($UserList)

# Set the error action preference to continue the script should
# it encounter an error. It will display errors.
$ErrorActionPreference="Continue"

# Inform the user the script has complete with a count
# of the errors encountered.
Write-Host "Script Completed with $ErrorCount errors."

# == End of Main Code =======================================

The format for the UserList.txt is just the users First and Last name.  One entry per line.

Wednesday, March 9, 2011

Change Screen Resolution on Server Core

Changing the screen resolution on Server Core is not likely to be a day-to-day task for most administrators.  Microsoft did not bother creating a nice tool like SCONFIG in the R2 version of the software to help us with this.  To change the screen resolution in Server Core, you have to manually edit the registry.
On your Server Core, type regedit and press Enter. You will be presented with the graphical Registry Editor.

Expand HKLM\System\CurrentControlSet\Control\Video


image

Expand each GUID until you find the one that has a subkey labeled VolitileSettings.

Click the 0000 Key above the VolitileSettings subkey.

image

Double click the DefaultSettings.XResolution.

Select Decimal

Enter the number of horizontal pixels you want and click OK.

Repeat the process for the DefaultSettings.YResolution

image

I choose 640x480 for the resolution that I want.

Close the Registry Editor. Log off and then log back on to get your new resolution.