Skip navigation

Category Archives: General Discussion

Everything that goes on here.

So in the world of SCCM there are tons of moving parts and components.  I want to take some time to focus on some common issues with client installation and communication issues, as well as a couple of tools that make troubleshooting infinitely easier.


Tools

First up I want to list 3 of the primary tools I use for client side troubleshooting.

  1. Trace32 Log Reader
  2. SCCM Client Center
  3. JSandys CM Startup Script

Now the first item on that list, trace32 is by far the most valuable tool to the SCCM administrator outside of the console itself, perhaps even more so than the console.  It allows filtering, highlighting, real time updates, and just generally makes the logs readable.

SCCM Client Center, this tool attaches to the cm WMI Namespace and allows for nearly full control of the client on the target machine.  In terms of remediation, or even testing, there is no reason this tool shouldn’t be installed.

Config Manager Startup Script by Jason Sandys.  This script is easily configured for implementation and has fairly rich logging power for a vbscript, it’s also lighter weight than some of the other health scripts.  I highly recommend using this for maintaining client integrity, as well as offering an installer tool for the CM agent by secondary or third parties.


The Client

First, lets start with identifying the clients existence on the local machine.

Here’s where to look:

  • Control Panel > Configuration Manager (this is one of the quickest methods)
  • Task Manager (ctrl+shift+esc) > Processes > CcmExec.exe
  • Task Manager > Services > CcmExec
  • Control Panel > Admin Tools > Services > SMS Agent Host
  • c:windowssystem32ccm (32bit)
  • c:windowssyswow64ccm (64bit)
  • HKLMSOFTWAREMicrosoftSMSMobile ClientProduct Version (32bit)
  • HKLMSOFTWAREWow6432NodeMicrosoftSMSMobile ClientProduct Version (64bit)

This is a list of the primary locations to check for the presence of the client, it’s also useful for finding methods to script around identifying them.

 

The Client’s Jobs

Now lets discuss what the client does.  First lets recognize that the client is just a dictator for the most case, it tells multiple windows services what to do to complete specific tasks.  Until we need to break down what services do things specifically lets just treat the client as the primary initiator.

  • Policy updates and application
  • Manage downloads
  • System scans
  • Inventory reports

The client and server relationship relies heavily on BITS, Admin shares, RPC (at least for installation), WMI, AD, and WUA.

The client will regularly talk to the server, telling it about any changes it’s had since it’s last conversation, by way of xml.  It will also ask the server what it should be doing differently, to which the server sends the client it’s latest policy.  The client will review that policy then act, or do nothing depending on if there are any actionable changes.

Actionable changes could be installation of software, OS, OS configuration changes, even changes in the frequency of their conversations.  These exchanges of course are called policy updates, and I believe by default they are set to 90 minutes (no real reason to change it either).


Client Installation

There are multiple ways to install the SCCM client, and in a lot of ways, that method will vary depending on your environment.  I will stick to the basics and explain the process if done by server initiated push.  I will also discuss what is required.

First the server begins by initiating a PUSH, using local admin rights, it will copy down the CCMSETUP.EXE file to either c:windowsccmsetup or c:windowssystem32ccmsetup

A service named CcmSetup is made and it begins transferring the client contents to the local machine and finalizing installation and cleanup of the directory.

A log of the transaction is left in the ccmsetup folder named ccmsetup.log

Once this process is complete, the client will perform it’s first policy update and make it’s active client existence known to it’s respective primary server.

 

So what if installation fails?

This isn’t a perfect world.  If you are pushing into an existing environment, things may have accidentally found there way out of standards and or flat broken.

Lets discuss what is required on a local PC for a successful install:

  • Resolvable hostname (proper DNS entry)
  • Service account with local admin rights
  • RPC access to OS components (such as registry)
  • Admin$ shares
  • WUA (Windows Update Agent)

Instead of explaining exactly why for each of these, lets explain how to resolve potential problems with each.  I also want to treat this as an all inclusive troubleshooting guide for the client, so I won’t limit things to just install failures.  Truthfully, if any of these breaks after installation, the client will most likely not function as intended.

Improper DNS entry:

From the local machine there is little you can do to resolve this problem.  Two methods that could resolve the problem are:

ipconfig /registerdns

This will attempt to update the DNS records for all adapters of the local machine.

ipconfig /flushdns

This will dump all resolver cache data on the local machine. (long shot, but I’ve seen this clear up client DNS conflicts from the push)

Any additional resolution would need to be done by the Domain Admin on the DNS server with the improper pointer references.

Service Account with local admin rights:

This is a very simple solution.  Add the appropriate service account to the local admins group on the client PC.  For Installation and operation, this account needs to be set for the client to perform it’s jobs.

RPC Access:

This one can have you scratching your head at times, but a majority of the times it’s tied to a firewall.  Make sure that local firewalls have exceptions built in for the SCCM server.  When in doubt, disable the firewall software to verify if it’s the culprit or not.

Also ensure that the RPC (RpcSs) and RPC Endpoint Mapper (RpcEptMapper) services are Started.

Some of these changes may require a restart before taking effect so  be aware of that while troubleshooting RPC denials.  It’s also worth mentioning there are a multitude of applications that could disrupt this functionality, so be sure to thoroughly investigate the machine for potential culprits.

Admin$ Shares:

First off, the service Workstation (LanManWorkstation) is responsible for these shares, as well as all SMB protocols on the local machine.  If it’s disabled, you will not have these shares.

One of the most direct methods for enabling admin shares is in:

HKLMSYSTEMCurrentControlSetServicesLanManServerParametersAutoShareWks, 1

HKLMSYSTEMCurrentControlSetServicesLanManServerParametersAutoShareServer, 1

Then restart the PC.

Be aware this setting can be viewed as a security risk, and with that being said, some security software may actively disable them.  So treat your evaluation similarly to your RPC troubleshooting.

WUA Disabled:

The Windows Update service being disabled is a fairly simple solution provided there isn’t a GPO forcing it.  You can either enable and set the Windows Update service to Automatic (wuauserv).  Inside the control panel under Windows Update or Automatic updates set it to automatic.

WUA is responsible for system scans, patching, software delivery, essentially a vast majority of the clients functionality.  It is imperative that WUA is enabled.

Bits Admin:

During client installation you may encounter issues with bits failing to download and continuing to re-queue. The issue is generally tied to a stuck job in the bits queue.

From a command prompt you can use

bitsadmin /list /allusers

This will give you a list of jobs, if you see jobs in there:

bitsadmin /reset /allusers

will clear them all out.

For windows XP machines without bitsadmin get it here.

For Windows 7 Machines or Server 08 use the PowerShell module:

import-module bitstransfer

get-bitstransfer -allusers | remove-bitstransfer

For additional bits module cmdlets type:

get-command -module bitstransfer

WMI Failing:

WMI is an integral component of Windows, it could also be linked to issues you might be seeing with WUA being disabled, and with failing clients post and pre install.

The quickest way to verify if WMI is functioning as intended is to check it’s service under Computer Management:

Right-Click My Computer > Manage > Services and Applications > WMI Control > Properties

If you see:

Successfully Connected to: <Local Computer>

Then WMI is functioning correctly. Be mindful though, parts of WMI can fail without the whole of WMI failing, CCM classes/namespaces in WMI could still require a rebuild so be sure to investigate further if the client is installed but not functioning.

Error verbiage that would link to WMI failures will state namespace failures or WMI authentication errors etc. Fortunately repairing a CCM WMI namespace problem is fairly simple.

Open a command prompt:

net stop winmgmt

rename %systemroot%\system32\wbem\repository repository.old

net start winmgmt

Uninstall, or cleanup your CCM/CCMSETUP directories as prescribed in the uninstall section to rebuild the CCM repositories.

If you want to try and rebuild the corrupt namespaces without performing a client uninstall reinstall the following steps can be done from the command prompt as well (requires that a client be installed):

net stop winmgmt
c:
cd %systemroot%\system32\wbem


rename %systemroot%\system32\wbem\repository repository.old

regsvr32 /s %systemroot%\system32\scecli.dll

regsvr32 /s %systemroot%\system32\userenv.dll

mofcomp cimwin32.mof
mofcomp cimwin32.mfl
mofcomp rsop.mof
mofcomp rsop.mfl
for /f %%s in (‘dir /b /s *.dll’) do regsvr32 /s %%s
for /f %%s in (‘dir /b *.mof’) do mofcomp %%s
for /f %%s in (‘dir /b *.mfl’) do mofcomp %%s

net start winmgmt


Logs to Read, and Policy Updates

For the official list of log files, go here.

(http://technet.microsoft.com/en-us/library/bb693897.aspx)

 

I’m going to touch on the more immediate logs for troubleshooting the following issues.

  • Health
  • Policy
  • Connectivity
  • Licenses
  • Installs

Health:

CcmExec.Log, this log is one of the first stops for suspected bad installs.

ClientLocation.log, this log is a good place to verify that client has a healthy install with a site server.

StatusAgent.log, status messages for client components.  Also useful for connectivity issues.

Policy:

PolicyAgent.log, this holds policy request information, very helpful when pulling policy.

PolicyEvaluator.log, this log lets us know know if we are having issues applying policies.

Connectivity:

InternetProxy.log, if you are using unprotected DPs, this is the log to check.

Mpcontrol.log, logs record the state of the management point

LocationServices.log, attempted connectivity to MPs and DPs

Licenses:

Hman.log, if clients aren’t registering this is worth looking into.

Installs:

Ccmsetup.log, client installation happenings are recorded in this log.

Client.msi.log, output from the installer.


That concludes the overview of SCCM client installation and troubleshooting.  Happy problem solving.  For additional information on the client and troubleshooting check MSDN:

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

and be sure to get involved with

http://www.myitforum.com/absolutenm/PPLSearch.aspx

 


Today we are going to examine VBScript. Now, a bit of fair warning before we start on this.  This scripting language is a departure from our standard shell scripting.  VBScript is an automation scripting language for the Windows Script Host (WSH)/Internet Explorer (IE)/Internet Information Services (IIS), in short, this is the primary Windows scripting language.

Not to get too carried away on the subject, but this language uses a Component Object Model that allows direct (or indirect) action on just about every object within the windows environment and does so natively via the windows script host interpreter ((which is extensible) (wscript.exe or cscript.exe)).  There are nuances to that statement, and I encourage you to investigate it more thoroughly, however I’m going to jump right into some of the basics of using this language, then discuss the code below as we’ve done in the previous 2 posts.

First off, what is a component object model?  Put as simply as possible, they are exposed objects that you can manipulate in the environment by invoking their methods and properties.  This scripting language brings you dangerously close to windows development at times, but at it’s heart, it’s still very much a script.  Controlling environment objects and properties, performing sequenced tasks, and no compile.

Now, I’m going to introduce 4 new things with this script, I will name them now and explain them after we’ve reviewed the code:

Arrays

WMI

Subroutines & Functions (They can be the same, but in WSH they are different)

Loops

Function VBscript (blog)

The overall activity of this script is the same as our drivemounter batch script we made.  Lets take a look at the code.


'||========================================|| 
'||Author Daniel Belcher                   || 
'||Function drivemounter                   || 
'||Date 5/4/2011                           || 
'||========================================|| 
'|Objects, Variables, and Arrays *********** 
'==========================================/ 
'|Set number of items in array             '| 
'|Example: 3 drives would be (3,1) and 4   '| 
Dim ArrDrive(6,1)                          '| 
DriveCount = 7                             '| 
’|Define the Array to read                 ‘| 
    arrDrive(0,0) = "h:"                   '| 
    arrDrive(0,1) = “\uncpath1”            '| 
    arrDrive(1,0) = "i:"                   '| 
    arrDrive(1,1) = ”\uncpath2”            '| 
    arrDrive(2,0) = "j:"                   '| 
    arrDrive(2,1) = ”\uncpath3”            '| 
    arrDrive(3,0) = "k:"                   '| 
    arrDrive(3,1) = ”\uncpath4”            '| 
    arrDrive(4,0) = "l:"                   '| 
    arrDrive(4,1) = ”\uncpath5”            '| 
    arrDrive(5,0) = "m:"                   '| 
    arrDrive(5,1) = ”\uncpath6”            '| 
    arrDrive(6,0) = "n:"                   ‘| 
    arrDrive(6,1) = "\uncpath7"            ‘| 
‘|Define the Server to Ping for Net Check  ‘| 
Dim strSvr                                 '| 
    strSvr = "servertoping"                '| 
'========================================================================== 
Const DEBUGMSG = True    'True = Debug Messages, False = No Messages 
Dim oWShell 
    Set oWShell = CreateObject("WScript.Shell") 
Dim oWNet 
    Set oWNet = CreateObject("WScript.Network") 
Dim Target 
    Target = "." 
Dim oWMISvc 
    Set oWMISvc = GetObject _ 
("winmgmts:{impersonationLevel=impersonate}!\"&Target&"rootcimv2") 
Dim oPing 
    Set oPing = oWMISvc.ExecQuery _ 
("Select StatusCode From Win32_PingStatus where Address = '"&strSvr&"'") 
'|Main Run ================================================================= 
DriveMount        'Perform Function DriveMount 
Report            'Perform Function Report 
Wscript.Quit(0)   'Close Script 
'SubRoutines and Procedures ================================================ 
Sub Mount(letter,path) 
    oWNet.MapNetworkDrive letter,path 
End Sub 
'***************************************************** 
Sub Umount(letter) 
    oWNet.RemoveNetworkDrive letter 
End Sub 
'|Functions ================================================================ 
Function DriveMount 
'http://msdn.microsoft.com/en-us/library/aa394350(v=vs.85).aspx 
    For Each item in oPing 
        If IsNull(item.StatusCode) or item.StatusCode<>0 Then 
'**********Domain not reachable, unmount drives in arrDrive 
        x = 0 
          do until x = DriveCount 
             On Error Resume Next 
                Umount arrDrive(x,0) 
                       If debugmsg then msgbox "Umount"& vbcrlf _ 
                       &"Drive Letter: "&arrDrive(x,0)& vbcrlf _ 
                       &     "Error Number: "&Err.Number& vbcrlf _ 
                       &     "Error: "&Err.Description 
              Err.Clear 
        x = x + 1 
          loop 
        else 
'**********Domain exists, mount drives from arrDrive 

        x = 0 
          do until x = DriveCount 
             On Error Resume Next 
                Mount arrDrive(x,0), arrDrive(x,1)  
                       If debugmsg then msgbox "Mount"& vbcrlf _ 
                       &"Drive Letter: "&arrDrive(x,0)& vbcrlf _ 
                       &     "Error Number: "&Err.Number& vbcrlf _ 
                       &     "Error: "&Err.Description 
              Err.Clear 
         x = x + 1 
          loop 

        End if 
   Next 
End Function 
'***************************************************** 
Function Report 
      If Debugmsg then msgbox "Script completed" 
End Function 
'End ======================================================================
 

Copy and paste the code and save as a .vbs file (unless you have a specific editor, I recommend notepad to insure formatting is properly translated.)

Lets start with our 4 areas of interest we’ve focused on with the previous posts.

  1. Sequence
  2. Command usage
  3. Output usage
  4. Conditional logic

Sequence:

Sequencing and Command usage will be the most interesting topics this time around.  Unless wscript is pointed towards a specific function or sub, it reads everything in line.  This point is rather large when you consider BASH and POWERSHELL and a lot of other script languages which will error out if something is called that hasn’t been previously declared (speaking about functions and subroutines, variables must always be declared before usage).  However, the rule remains that everything is read one after another, or AS the interpreter is directed to read.

As a habit when I write my vbscripts I will almost always write them in this format. Variables, Run sequence, subs, functions.  There is no real reason for this outside of the fact I prefer to immediately see variables and prescribed run order.

Now lets look at our variable declaration and focus on what’s new.  An array, and a multidimensional one at that (more than two columns of data).  An array is an assortment of data stored in memory, think of it like a spreadsheet.  Row 0,1,2,3,4,5,6 and Column 0,1,2,3,4,5,6.  This would be a multidimensional array.  A simple array would be 1 Column (column 0) and however many rows as you wanted.  In this script I declare this array to be limited to 7 rows and 2 columns.  That sounds weird right, cause the declare clearly says (6,1) ?  Remember that 0 counts so 6 = 7 and 1 = 2, but you declare it by the integer value of the last entry.

Dim ArrDrive(6,1)

I then declare my Array entries by defining ArrayName(row,column) = data

arrDrive(0,0) = "h:"          '| 
arrDrive(0,1) = “\uncpath1”   '| 
arrDrive(1,0) = "i:"          '| 
arrDrive(1,1) = ”\uncpath2”   '|

...

From here on out when I need to utilize any of these pieces of data I can simply call them using their array name and position.  Another way to think of this is a shared variable name perhaps?

Now lets discuss our run sequence:

'|Main Run ================================================================= 
DriveMount      'Perform Function DriveMount 
Report          'Perform Function Report 
Wscript.Quit(0) 'Close Script 

This block of code dictates the run order of my script.  The first 2 are Functions I have defined, and the last is a wscript method to insure a clean exit (more on this in command usage).

Sequence is important. For organizations sake, I will take a quick and easy VBScript and build it in this fashion.  For me, and for others, it allows for simpler review and additions to be made to the script that could and will improve it’s functionality.  It’s also far simpler to isolate bad sections of your script and to target a specific function for testing.

Now let’s discuss the iteration statements that are introduced in the DriveMount function.  I will touch on the code more specifically when we break down what the script is doing, but an iteration statement is just a loop that continually performs a task until a certain condition has been met.  That could be reaching a certain number, that could be reaching the end of a file, that could be reaching the end of an array, etc.  In this script (although not how I would naturally do it) I’ve offered 2 concrete examples of vbscript loop statements for your review.

Finally, subroutines and functions.  Similar to labels, identical to the function I showed with BASH.  They are, put succinctly, sections of code that can be called by name to perform a fixed task.  In VBScript specifically a sub routine passes back no data, a function does.  So if I need to perform mathematical operations and reuse it as a variable elsewhere, I’d use a function*.  If I just need to move a file from one location to the next, a sub.  As a safe bet inside of VBScript, declare them all as functions, there is really no benefit I’ve found one way or the other.  I declare them as Sub and Function only to offer them as an example. Syntax for this is:

 Function Name                              Sub Mount                          

        Code to use                             Code to use 

End Function                                End Sub

If you wish to use arguments with these functions/subs you would use:

Function Name (arguement1, arguement2, etc)
 
                Code using arguments provided
 
End Function 

Command Usage:

Unlike our other scripting languages so far, the WSH doesn’t really utilize commands per say.  Command usage is actually called through a COM.  So when you build a vbscript, you spend the first portion of the script defining what COMs will be utilized in the script.  This is all part of my initial variable declaration (DIM statements or Declare Into Memory)

Dim oWNet 
    Set oWNet = CreateObject("WScript.Network") 

This is essentially creating the callable object or “commandoWNet for me to use moving forward.  What’s actually happening is I am using the WScript object to instantiate (create an instance of) the WshNetwork object for later method or property usage (exposing the object for manipulation).

This is how an object based language works, call the object, use the object, (and ideally) release the object.  When I later use these objects methods I will do so by invoking them.  Syntax comes in to play in these cases.

oWNet.MapNetworkDrive letter,path

That is the invocation of the WshNetwork MapNetworkDrive method which requires drive letter then path to map.  Hopefully that makes sense, it’s an extra step but allows for some amazing control and it remains rather light weight as it depends on existing objects for it’s control base as opposed to having them already built in.  However that’s not to say there aren’t commands built into the WSH but they are for conditional and iteration statements as well as integer, string, and date functions (w3schools.com has a nice breakdown as well) etc.

Output Usage and Conditional Logic:

For this script the output usage is in reading a ping response, mapping drives, and in exception handling (error catching).  We read the status code from the WMI Win32_PingStatus class object (list of WMI Classes) then use it as our condition.  We then loop through the array and perform the appropriate action while catching and clearing any potential errors.  We also redirect that error output to a popup message if DEBUGMSG Boolean is set to TRUE in our initial variable declaration.

Our conditional logic as stated before is in the form of IF statements.  I will demonstrate case statements in my PowerShell write up.  Case statements look for something (usually a specific string type) and respond in a defined way.  However a case statement is strictly defined where an IF statement is generally this or that, it will make more sense in the future I promise.


So what does this vbscript do?

In this script we open with our declarations.  We define our Array ArrDrive as a 7 row and 2 column array (0 counts, remember though declaration will be the last integer value so in this case: 6,1) and supply it with values.  We set a Boolean for debugging messages and we set our object instance for WScript.Network to oWNet.

We also start an instance of the WMI Service, and define a WQL that reads the ping status to a targeted server (strSvr) for us (Target=”.” means the local machine, it can be changed for remote PC name, more on wmi scripting).  (WMI is Windows Management Instrumentation, similar to the WSH objects it contains a series of namespaces, classes, methods, and properties to control the windows platform.  Essentially if you can do it on the Windows machine, there is a WMI namespace/class/method involved in it.)

Dim Target 
    Target = "."
Dim oWMISvc 
    Set oWMISvc = GetObject _
("winmgmts:{impersonationLevel=impersonate}!\"&Target&"rootcimv2")
Dim oPing 
    Set oPing = oWMISvc.ExecQuery _
("Select StatusCode From Win32_PingStatus where Address = ‘"&strSvr&"’")

Now that we have all that declared we move into our run sequence.  The Function DriveMount is first and it immediately performs a For Each statement through our oPing WQL and grabs the statuscode value and compares it with an IF statement.

For Each item in oPing 
         If IsNull(item.StatusCode) or item.StatusCode<>0 Then 

If there is no value, or the status code is anything but 0 (0 is a clean exit code, success, that’s what the status code is in its simplest form) then we aren’t in our appropriate network so we will begin a Dismount loop.  If the return value is 0 and is NOT null then we will perform a Mount loop.

Lets stop here for a second so I can explain this loop line for line, first the code sample:

‘**********Domain exists, mount drives from arrDrive
 

x = 0
  do until x = DriveCount 
     On Error Resume Next
        Mount arrDrive(x,0), arrDrive(x,1)   
              If debugmsg then msgbox "Mount"& vbcrlf _
              &"Drive Letter: "&arrDrive(x,0)& vbcrlf _ 
              & "Error Number: "&Err.Number& vbcrlf _
              & "Error: "&Err.Description 
     Err.Clear
x = x + 1
   loop 

We declare x as 0, we will enumerate this integer value with each pass of our iteration (loop).  Word of warning here, if using this method make doubly sure that you set your enumerate value outside of the loop or it will be re-declared each loop and become an infinite loop.

We do until x = DriveCount, we declared DriveCount as 7 at the start of the script.  This loop will loop 7 times.

On Error Resume Next, we will not let error outputs break our function, we will perform the next in line.

We run the Mount subroutine passing the letter and path arguments which we pull from our arrDrive array.  We use x to select our row (remember we are enumerating x) and select the appropriate column for the data to pass.

Now as an extra step, we check for the DEBUGMSG Boolean, if it’s TRUE, we generate a popup window that tells us what Subroutine is being used, drive letter, error number, and error message. (if the drives are already mounted it WILL error, the error is that the drives are already mounted, so this is helpful if we are chasing something down)

We clear the errors that may or may not have been generated.

Now we take x and we add 1 to it, so 0 becomes 1, 1 becomes 2, 2 becomes 3, etc on each successive pass.

Finally we terminate the statement with loop so that the WSH knows to return to the start of the loop statement.

Easy huh?  There is a lot of power to learning how to use loops and for each statements effectively.

I would normally have just made another for each statement against the array which would read it to the end, but I felt this serves as a great learning opportunity.

At this point our DriveMount function is complete so we move to the next Function in the run sequence which is Report.  Report runs a debugmsg check and tells us the script completed if debugmsg is true.

Now back to our run sequence where we close our script with

Wscript.Quit(0) 

This insures an exit code of 0 which is a universal “everything ran great, nothing to see here” output.

End Function

Next up we will be discussing PowerShell.  A very robust shell scripting language for the newer windows platforms (xp sp3+) that utilizes commands, .net, com, wmi, dcom, and the list goes on.  I’ll try to keep it lite.


Now for some bonus material, lets take a look at the Mount loop if I had used a For Each instead of a conditional loop:

x = 0
For Each object in arrDrive
    On Error Resume Next
       Mount arrDrive(x,0), arrDrive(x,1)
            If debugmsg then msgbox "Mount"& vbcrlf _
            &"Drive Letter: "&arrDrive(x,0)& vbcrlf _ 
            & "Error Number: "&Err.Number& vbcrlf _
            & "Error: "&Err.Description 
     Err.Clear
x = x + 1  
Next

You are probably thinking “this looks the same, why is this better?”.

When you perform a conditional loop statement it needs a stop point which is another factor you have to manage.  In this case we had to declare a maximum loop count (our DriveCount variable which was 7).  A for each statement will go through a list till the end and then move on.  You can think of a for each statement as “For Each item in whatever until the end.”

If you have any questions or corrections, please leave a comment and I’ll try and get back with you about it. For an unaltered version of this script to copy and paste, go here.


Stick to the Script Parts 1 – 4:

  1. Stick to the Script…
  2. Stick to the script #!/BIN/BASH…
  3. Stick to the script CreateObject(“Wscript.Shell”)…
  4. Stick to the Script PS C:> PowerShell …

Ok, so this has been out as a retail release for more than a year. (Originally released in Feb of 2010) I remember being completely psyched for this game.  A Sci-Fi FPS MMO made by a company about 2 hours from my house, what’s not to love?

 

 

Long story short, I’m not sure what happened but I never ended up buying it because of my new job and how busy I became etc.  However they just recently went FtP (Free to Play) and with a price like that it’s hard NOT to play right?

Anyway, lets keep this simple:

Graphically, the game has a very stylized look.  Nothing amazing per say, but it has a clean look about it.  The interface, although functional, feels and looks a bit clunky.  It would be nice for a native method to scale it down, but overall the games appearance is sharp enough that it remains appealing.

Sound wise, the game is alright.  Though admittedly the music gets turned down rather fast so I can hear people run around in pvp.  The sound is clear enough, and diverse enough that you can use them for audible cues.

Gameplay, well I will say this first off.  I like the gameplay, the mechanics, the pve (surprisingly) and the competitive play.  I did not however, start out liking them.  The simplest way that I can put it is this, there is an amazing simplicity to the 4 class system that works, and enough diversity play style wise to keep me entertained.  The 4 classes are:

Assault: General tank and heavy artillery.  The class take and deal a considerable amount of damage when speced properly and in pvp can be a king for offensive objective control.

Recon: Stealth? Melee? Sniper? Yea that about sums the class up.  Very very sneaky.

Medic: Poisons and heals.  Decent damage if required to fight.  Overall this class plays well in pve and pvp for their healing and general CC utility.

Robotics: Turrets, drones, heal stations, and recharge stations.  The assault in pvp can be the offensive objective king, but a robotics player is the defensive one.  Similar to medic in the amount of versatility, but forced largely to choose mobility or survivability.

Each class has 3 trees, one of which is a universal tree called balance.  The other 2 are class specific that focuses on play style specialties.  For instance, assault is: balance, tank explosive. 

I can honestly say as well from my perspective, that balance seems very real.  I have yet to be on any particular class and just feel as if I am hopelessly lost against a particular pairing.  Like any class based shooter, you should expect limitations to your role, and respond to fill it.

At the same time, the min maxing that people enjoy from other MMO titles exists here as well, so it IS capable to get an edge, it’s not the kind of thing that is out of hand.  To be honest with you, I feel CoD titles are less in balance with unlocks than this title is.

Another point of interest is the AvA system, achievements, PvE instances, and just random loot hunting that turns this into a very fun and addictive title.  I highly recommend you give it a try (it’s free after all) and just play your way up to 20.  You might be surprised, and feel free to contact me in game.

lotekness

Global Agenda

Alright, so continuing our discussion on scripting with Bash scripting in Unix and Linux.  In the same way that command interprets a script to perform actions in order so does bash.  What’s the difference then?  The sheer volume or tools available to script and manipulate the environment is greatly increased.  The manageability of output, the variety of conditionals, arrays, and integration of the shell into the environment.

It’s worth mentioning up front, I could spend days on the subject of any of these scripting languages.  However for the sake of space and interest, I will still keep things high level.  It’s ALSO worth mentioning that Bash/shell scripting is something of a nix requirement.  Not that you have to know shell scripting to use the OS, but it’s certainly a primary part of the culture.  Bash scripting also works within OSX environments (since it’s built on BSD), however some research and testing will be required to find the similarities between their nix and others which leads to my next topic…

Linux and Unix {

If you are reading this, I will assume you know what Linux and Unix are.  If not, here’s some reading material for Unix and Linux.  What you may or may not be aware of is that although there is a great level of standardization as maintained by IEEE POSIX standards, there is also a lot of distribution specific tools or practices.  In other words, a person can generally port work from one distribution to another, but should never assume a one size fits all solution across the board.  Which is precisely why there are so many distributions, because one size does not fit all, at least not to everyone’s tastes.

I also want to take a moment to point out that this is not a flaw. Although standardization is a good thing, limited options are not. There are other standards that GPL licensed software (generally linux)adheres to that gives it reliable standards or compliance. They also maintain partial POSIX compliance as well. It’s an interesting subject, and the differences are fairly minor in most cases. Do not be scared by the options, determine what it is you want and go from there if you are interested in trying.

Now a days the user experience one has come to expect from Windows or OSX is easily found with a popular Linux distribution (Ubuntu and Fedora immediately come to mind).

     Bash Scripting {

Now lets take a look at a very simple script that I’ve briefly modified from Mendel Cooper’s guide for an example on here:


#!/bin/bash#Log Cleanup
#Author: Daniel Belcher
#4/30/11
#Built for tutorial purposes
#Idea for script from beginner example
#in advanced bash scripting guide:
#http://tldp.org/LDP/abs/html/sha-bang.html#Variable declaration
LDIR="/var/log/"
DATE=`date '+%m%d%y'`
RUID=0
E_USER=1#Checking for root user, exiting with error code 1 if not root
if [ "$UID" -ne "$RUID" ]
then
          echo "User needs to be root"
exit $E_USER
fi
#Copying the current messages and wtmp logs to an archive with date code
cp $LDIR"messages" $LDIR"messages."$DATE;
     cp $LDIR"wtmp" $LDIR"wtmp."$DATE;
#Taking the last 10 lines from that log and writing it to the current
#messages and wtmp to reset them.
tail -n 10 $LDIR"messages."$DATE > $LDIR"messages"
          tail -n 10 $LDIR"wtmp."$DATE > $LDIR"wtmp"                
   sleep .5
#Finding all messages and wtmp files with an
#access time of 7 days or more and deleting them.
find $LDIR -iname messages.* -atime 7 -exec rm {} ; #could also swap –exec rm etc for –delete 
             find $LDIR -iname wtmp.* -atime 7 | xarg rm 


Save as a .sh

then

chmod +x scriptname.sh

Now same as with our batch script, lets focus on 4 things.  Hopefully some similarities begin to present themselves.

  1. Sequence
  2. Command usage
  3. Output usage
  4. Conditional logic

Sequence:

Now similarly to the command shell, Bash reads the script line for line.  However instead of GOTO statements in Bash, we would actually build functions. (I do not have an example in this script but the syntax is generally name_of_function() { work to perform }.  I’ll discuss this more with PowerShell and VB script).  All lines are read as if they were typed at the console.  Here you will see I also do something that we didn’t do within the batch file.  Variable declaration (LDIR=”/var/log/”) then I can call it again in the script as $LDIR.

This allows you to take a commonly used command, object, integer, or string and set it to something easily repeatable inside the script.  Variables can be declared at run time, as an argument, or produced from script output to name a few methods for declaration.  They are integral to programming in general.  As far as sequence is concerned, as long as the variable is declared before it’s called you are fine.

Command usage and Output usage:

Now hopefully you are seeing that the commands available in a shell are what does most of the heavy lifting in terms of work.  Something worth learning in command usage is piping.  Piping is taking the output of one command and using it as the input for another (to put it simply).  A visual I’ve always liked to use in understanding what is happening is this:

A lake brings water to your home.  A pipe exists between the lake and your faucet (very simple). On the course to your house a series of filters are applied to weed out what you don’t want from the water by the time it reaches your house.  In this case the lake is the source or original input, and the filters are the series of commands applied to the pipe before the final output at your faucet.

So in pseudo code: lake-water | filter-fish | filter-algae | filter-dirt > glass-of-water.drk

The end result is that water is transported through that pipe and all unwanted elements are removed until we finally have our desired glass of water to drink.

In this case we use:

find $LDIR -iname wtmp.* -atime 7 | xarg rm 

This will take the findings from the FIND command and pass it to xarg which initiates rm and deletes these files.

Hopefully this is beginning to paint a clearer picture of pipe and command usage.  Shells that allow for command piping are a God send and allow for some very elegant solutions to complex problems in simple one liners that a user could easily alias, but that’s another subject entirely.

Conditional Logic:

Now in an identical fashion to our batch file we are performing an IF statement.  IF statements are one of, if not the most, commonly used conditional statements.  Notice there is a very distinct difference in the syntax used here in comparison to the one we used in our batch.  The testing method and outcome are still the same however, so do not be deceived.  IF statements put simply are: if it’s this then do that.  Since conditional tests are capable of greater complexity (and will be with all other script engines we discuss going forward) it needs to be terminated so the script knows when the conditions or work statements are final. We close this IF statement in Bash script by spelling IF backwards FI.

The same is true for all conditionals within bash.  They will open spelled forward and close in reverse.  Elif … file case … esac; when you begin to learn what and how logic is applied in scripts you will know how to appropriately apply the syntax.

So what does this Bash script do?

The script opens with a shabang! (#!/bin/bash) which tells the shell that it’s a script to be interpreted by the bash shell found in the bin folder.

Next it declares 4 variables, LDIR (log directory path), DATE (current date no special characters month date year), RUID (Root user id), and E_USER (error code to use if the user fails our user check).

Now we check a shell variable $UID (current user’s ID #) and see if it’s different than the $RUID (-ne = not equal). If it’s not the root user we exit with the error code # assigned to $E_USER.

If we pass that check we will now copy the messages and wtmp files under the /var/log/ folder to their same folder as filename.currentdate.  Example: messages.050111

Now we take the last 10 lines of that file and output it to the primary log files messages and wtmp effectively overwriting the previous data and truncating that file.  > operator on the command line is a redirect (as we saw with our > nul in the batch file).

Finally we take and search that folder for all files following the archived file syntax and search for an access time greater than 7 days then we delete them.  I’ve used two different formats for deletion to show the different possible ways of doing this.

     } gnitidE shaB

} xinU dna xuniL

In my next post I’m going to break into vb scripting, which is a considerable departure from the shell relative scripting we’ve looked at so far.  However I will return to another form of shell scripting with PowerShell, stay tuned.


Just for another example, how would this script look utilizing a function?

#!/bin/bash#Log Cleanup 
#Author: Daniel Belcher 
#5/1/11#Variable declaration 
LDIR="/var/log/" 
DATE=`date '+%m%d%y'` 
RUID=0 
E_USER=1#Checking for root user, exiting with error code 1 if not root 
if [ "$UID" -ne "$RUID" ] 
then 
         echo "User needs to be root" 
exit $E_USER 
fi 
#Function to create backup, truncate, and purge old log files. 
cleanup () { 
                 cp $LDIR$1 $LDIR$1"."$DATE; 
                         tail -n 10 $LDIR$1"."$DATE > $LDIR$1 
                                 sleep .7 
                         find $LDIR -iname $1.* -atime 7 -exec rm {} ; 
                 return 0 
                 } 

#Calling function cleanup () and passing 1 argument

cleanup messages 
cleanup wtmp

exit 0

A lot cleaner.  Hopefully you can see the benefits of functions now, or even loops as we will examine in the future.


Stick to the Script Parts 1 – 4:

  1. Stick to the Script…
  2. Stick to the script #!/BIN/BASH…
  3. Stick to the script CreateObject(“Wscript.Shell”)…
  4. Stick to the Script PS C:> PowerShell …

If you survived this, was it just luck?

There is nothing on this earth that we can build or design that can not be taken away from us in the blink of an eye. All of what we have is fleeting, there is only that which we store up in heaven that holds any real value.

How does one do that? Through faith.

What does that mean ‘through faith’? To believe in Jesus Christ.

What does ‘believe’ mean? To continually embrace as Lord, Savior, and treasure of your life.

It is his to give, and it is his to take. The immeasurable amount of mercy that is shown to us to even draw our next breath is amazing! There is nothing this storm has taken that can not be brought back. There is also an amazing faith and resilience in the people of this state that I’ve grown to love, and a lot more heads that are looking up.

Praise God.

So I was in Tennessee on Sunday for Easter, and the conversation came up regarding scripting and programming. Now I’ve heard a lot of people discuss scripting with a sense of unapproachable grandeur and well, nothing could be further from the truth. Some scripting languages share objects/classes/methods etc. as your more robust programming languages, but quite honestly, it’s just a method for causing objects to behave in a sequenced manner according to your wishes. Not much different than a script an actor might read from.

Much like actors, who perform better for certain roles, script languages have better fits in certain areas than others. I intend for this to be a multipart post to discuss different script languages moving forward, but lets start with the basics. I’m going to break down 4 popular, widely used, scripting languages and show a few simple examples of them at work.

“Well, how is that different than a program?”

Well, the primary reason they are different is programming yields binary files. Essentially all the coding you do is then changed into unreadable machine code that performs what the developer intended.

Scripting is code that tells a binary file what to do. The binary file that reads the script is called an interpreter. So it will dynamically take code that is human readable and translate it to the computer.

Scripting is very versatile, but generally speaking you aren’t creating anything, only controlling what presently exists. More sophisticated shells (bash, PowerShell) will allow you to extend functionality of current commands etc., but generally speaking it’s still scripting unless it results in a new program all together.

In the end, the dynamic nature of scripting makes it a preferable solution for real time solutions, and automation in computer infrastructures. It’s also considerably easier to debug and resolve issues as there aren’t lengthy compile processes between build outs. However, there are times when a script just won’t cut it and you need to build an application.

Batch Editing {

Let’s start with one that a lot of people in the windows world are already very familiar with and start establishing an idea of what a script is.

With batch editing, the .bat extension identifies to the interpreter that the file is to be read as a script by the command shell. Anything you can do within the cmd prompt can be sequenced and completed in a batch file. It’s read sequentially line for line and accepts GOTO statements as well as IF clauses and LOOPs.

Let’s break down a simple batch file I use for drive mounting and dismounting at login:


@echo off
Rem —————————————————
Rem Drive Mounter
Rem Author: Daniel Belcher
Rem Modify drive letters and paths to match need
Rem Place in Startup folder for login init
Rem —————————————————

Rem Check for Corporate connection
ping -n 1 addresstoping > nul
If %errorlevel% EQU 0 (GOTO MOUNT) Else GOTO UMOUNT

Rem Drive Mounter
Rem Modify this section to match your desired paths

:MOUNT
net use /p:yes > nul
net use h: \UNCPATHONE > nul
net use i: \UNCPATHTWO > nul
GOTO END

Rem Drive Umounter
Rem Modify this section to match paths for Umount
:UMOUNT
net use /p:no > nul
net use /d h: > nul
net use /d i: > nul
GOTO END

:END


I just want to focus on 4 things here.

  1. Sequence
  2. Command usage
  3. Output usage
  4. Conditional logic

Sequence:

As a batch file is read by the command shell its read line, by line. This is equivalent to someone typing these commands one after another. If you wish to jump around in the script you can use GOTO or RETURN.

The commands “net” and “ping” should be familiar commands to any windows administrator. They are all part of the native shells command base. This is fairly standard in any shell scripting which is more akin to controlling commands than objects.

As with all scripts there is an output to be utilized. When you are building a sequence it’s important to check for a return and respond accordingly. An example of output capture here is done with %errorlevel% which is a standard output variable with the command shell. It’s also possible to declare variables inside a batch file using SET VARIABLE = STRING/ACTION/STATEMENT (that’s a bit beyond scope for what I’m covering here). You will also notice I tail most statements with a > nul. What’s being done here is called a redirect, that is, redirecting the output to a file or another command, in this case a null value which causes no console output.

Finally conditional statements. As it’s name implies, it’s a statement that checks for a certain condition. In this short script we are checking if the value of our %errorlevel% variable is equal to 0. This is defined by the conditional IF. So what we are asking the script here is, if ping has no errors GOTO MOUNT, else GOTO UMOUNT.

So what does this batch file do?

It calls the command shell, requests that it pings addresstoping 1 time and if there is no errors (destination is reachable) it goes to mount the network drives to the local machine. If the host is unreachable it clears potential instances of those drive mappings and then closes out.

If you want more information on batch commands and batch in general, read up.

} gnitidE hctaB

 

In my next post(s) I will give some examples of Bash scripting, PS scripting, and VB scripting.  I will also dedicate more focus towards them and try to explain their strong points and usages. 


Stick to the Script Parts 1 – 4:

  1. Stick to the Script…
  2. Stick to the script #!/BIN/BASH…
  3. Stick to the script CreateObject(“Wscript.Shell”)…
  4. Stick to the Script PS C:> PowerShell …

As I slowly gained consciousness on my swivel chair to the heavy panting of my corgi in my face, I realized we were in the middle of a pretty nasty storm.

So I got the kids and wife up (well she was already up) and went downstairs to wait it all out.

Score us 0 storm 3.

1 Table umbrella, smashed.
1 glass table, shattered.
1 dog house, demolished.

Also, our trash can was down, so storm 4…..And no power, 5.

I’m thankful no one was hurt, and just as quickly as the storm came it was gone. I’m sure there is a metaphor in there somewhere, but I’m too tired to think.

Hmm, lack of sleep.

Storm 6….

Roughly 1978 years ago, an act occurred, to fulfill a plan set in motion before time began. Before the earth and stars,  before light or dark.  That I might be saved from the sins of man.

Glory to God, and praise to Christ for taking the wood and the nails that I would not feel the wrath of He who sent Him. A right justice that a wretch like me deserves for an existence in defiance to the God who made me.

God’s grace is immeasurable, his love unstoppable, and my need….undeniable.

 

Recently we were told to take our 7 month old daughter Maggie to be reviewed for early intervention. She qualified! In all areas of development! It was like being hit with a sack of rocks. More so for my wife even than I. Our daughter nearly died during child birth, and was without decent oxygen and blood circulation before they successfully removed her. So to some end we knew that this might be possible, and we of course knew she was behind or not quite right on some of her milestones. However, having it there in your face is just overwhelming.

Fortunately through the state of Alabama and members of our faith family who are occupational therapists, we gathered a lot of great information and had a review conducted in our home for placement almost immediately after the initial review. We were told hand in hand is the one of the top early intervention places here in Alabama so we sought placement with them.

We trust God for everything.  He who promised is faithful, and if he has his eye on the sparrow we knew that he had his hands firmly rested on us.  That being said, Amanda and I spent a lot of time discussing in depth our Savior and then I placed the infamous question on my wife. 

“What if God is most glorified in our daughter being mentally handicapped?”

 


The Joy of a Husband {

I take my role as Spiritual leader in this house very seriously.  This was a time of necessary spiritual growth, and I was lead to, well, lead.  However, this was a time when I wanted to give my life up for my wife so she wouldn’t feel that pain of facing this realization!  We can’t place our joy in anything that is not eternal; our children included.  They are a blessing, and a source of joy, but inevitably we must fix ourselves firmly on our Savior. 

Though my flesh and my heart may fail me, the Lord is my strength and my portion forever.

It was a night of tears, prayer, and anguish.  Amanda continues to amaze me, she recognized immediately that she was more interested in the hand of blessing and not the hand itself.  The most amazing part of that to me, was she was MORE upset that she wasn’t loving God as she realized she should.

                   Wow. 

I continued to pray over my wife and daughter as she prayed for herself and for Maggie.

3 Amazing things happened:

  1. The following day our sister in law sent an email pouring her heart out to Amanda essentially discussing the exact same thing we had discussed in private the night before.  Also saying that she had felt compelled to pray for complete healing for Maggie, and was praying for our peace.  It’s worth mentioning no outward signs have been given regarding the emotional struggles my wife has been dealing with. –thank you Spirit-
  2. A few minutes after our prayer request went out for Maggie to be accepted into Hand in Hand, another email came in to let us know we were accepted into Hand in Hand.
  3. My wife felt the Spirit move and found Joy in seeing God at work in her life.  The word was alive and she now understands what it means to find Joy in God.  This of course, to me, is the greatest.
    The greatest Joy of a teacher is when their students can grasp it.  More importantly when that student is your best friend and greatest earthly love.  I’m so thankful God allowed me to be a part of that growth.

    } dnabsuH a fo yoJ ehT


So now where are we on Maggie? Hey, don’t you have a son too?

The Joy of a Father {

During the giggly bear’s evaluation (Maggie), they had marked her off for quite a few things.  Some of the more specific ones was not even attempting to mimic speech, using her hands around the midline, bring things to her mouth, lift up on her hands while on her belly.

So guess what she’s started doing?  Yea, and today while I was at work she apparently was using a sippy cup.. 

sippy cup

We aren’t where we need to be yet, but I have faith we will get there.


Now for my road dog (Will).  Will has a habit of grabbing phones and having long fake conversations with people.  Lately he’s become increasingly more upset that I go to work everyday.

“Why you go work air-day daddy?” “You go work day daddy?” “No, you no go work day daddy.”

It’s sweet, but it’s become something that grates on my nerves constantly explaining myself for keeping the lights on to my kid…

Anyway, today Amanda gave me a heads up that he was pretending to talk to me on her cell phone over messenger.  So I stopped what I was doing and dialed her cell phone and had a (surprisingly) lengthy conversation (well for a 3 year old) on the phone.  As I hung up the phone and I heard:

“Ok, I go now, I love you very much daddy”

… there aren’t words.  Seeing my son grow, seeing his love, his personality, and now starting to see signs of his grasping of the Gospel….. As we were pulling into the neighborhood the other night from who knows where hearing that little voice:

“Mommy, Jesus loves you, and he loves me too.”

                   ….. The prayer that my son will one day be my brother ….

talkin to daddy

…….We’re working on it!

} rethaF a fo yoJ

So recently we had to perform an AD cleanup of aged computer objects in our environment.  For a lot of companies this is a pretty standard procedure, for others, it’s just ignored (as was the case for us for a while).

Anyway, in the course of completing this task we had looked at a few scripts and tools that others had written/published around the internet and I inevitably got the bright idea to sit and write a tool for us to use in PowerShell.  So I setup my goals and fired up the old editor and went to work.


Objectives:

  • Identify aged objects
    • To identify aged objects, I went with the PasswordLastSet property of the object. There really isn’t a much better one to utilize, and it works off a 30 day cycle so it’s close enough.
  • Write out data for records
    • For write out I built a switch (–report) that will utilize the export-csv cmdlet to export a record of machines to the current users desktop.
  • Move objects to different OU
    • For moving objects I used the Move-ADObject cmdlet from the activedirectory module available with win 7 and server 2008 features.
  • Generic (no non standard add ins)
    • To keep it generic I chose to use the activedirectory module since we are running on 2008 servers, and migrating to windows 7. This insures future state usage, and prevents additional downloads or installs for functionality.
  • Modular (sometimes you just want a report)
    • To keep it modular, I built the (-move) switch. Unless the user explicitly defines this then the script will only report what was requested. Either to console output, or to a csv on the desktop (-report).
  • Versatile for targeting object date ranges and OUs
    • To insure versatility, I left 3 variables to be declared. $TIME, $TARGETR, $TARGETM. Date range, target OU to read, and Target OU to move respectively.
  • Script initially with potential to integrate in profile as a function
    • To build it as a standalone script, I originally had a (-help) switch that would output similar information as the get-help blah-blah –examples. Now with it functionized, I’ve removed that and added an overall function name to the code.

How it works:

Once applied to the PowerShell profile it can be called using get-adinactivecomputer.  By default it requires a date range either specified in <number>d for days or <number>y for years and a target OU to search from.  If these variables aren’t applied at the command line the function will request them at run time.

If –move and –report are specified then the function will need a target OU to move the items to and will generate a list with Object names and PasswordLastSet dates on the desktop and attempt to move them to the specified OU.  The switches must be declared at the command line but all variables are requested at run time if not stated before hand.


Now the nuts and bolts…..

admove1

First we check for the $TIME variable and request if it’s not present, then insure it’s in string format.  We’ll check that string for a d or a y to determine how to handle the string and then convert it to an appropriate integer value.  We’ll also bailout if we can’t distinguish the range (since this is a has the potential of causing serious AD harm we want to insure the user is accurate in their input).

Second we’ll check for the –report switch and if it’s present we’ll run the internal ADCLEANUP function and pipe it to export-csv $homedesktopinactivecomputers.csv.  If it’s not then we’ll just generate output to the console.  We pass the $TIME and $TARGETR variable to this function.

Third we check for the –move switch, and if it’s present run the internal function MOVEOLD and pass it the $TARGETM variable.

Fourth and final step, we nullify a global variable set during the ADCLEANUP function.

 


admove2

First step of the ADCLEANUP function is to insure the activedirectory module is loaded.  Next it verifies that a $TARGETR variable exists, if not it will prompt for one.  It then will take and search AD for the distinguished name of the OU provided. 

Next we build a date range variable using .Net Date Math.  We will subtract the total number of days by the integer value provided in $TIME from Today’s date and store that in $COMPARE. 

Now we declare a global variable $ADLIST that grabs all computer objects with PasswordLastSet property less than or equal to $COMPARE from the $TARGETR OU.

We then process those objects with a ForEach into a PSObject for reporting purposes specifying the Name and PasswordLastSet properties.  I did this mainly to guarantee a clean csv export.

 


admove3

The MOVEOLD function is fairly straight forward.  We check for the $TARGETM variable, if it doesn’t exist we prompt for an input.  We then build $TARGETM into a manageable string, then again we set it as a proper OU.  We run the $ADLIST through another ForEach statement and use Move-ADObject to relocate each $ITEM to $TARGETM.

 


I posted this script on the script center repository.  I didn’t build in any error catching which I should have, and plan to revisit that at a later date.  I enjoyed writing it so much I wanted to take some time to dissect it and discuss it a bit.  Hopefully this information proves useful to someone with similar goals and or general interest. 

For the the Microsoft.Powershell_profile.ps1 and Microsoft.PowershellISE_Profile.ps1 version of the script, perform the following steps in order:

Uncomment lines 4 and 193

Delete lines 7 through 50

Delete: ,[switch]$HELP from line 6

Delete line 46

Modify line 60 to read:                    `n`nTry get-help Get-InactiveADComputer -Examples`n";break}