Skip navigation

Monthly Archives: September 2011

So in my last two posts I was discussing how to build a script for forcing a SCCM client inventory and how to build a custom collection for them to deploy to.

There is still one more problem, as I stated in the first post, you need to run the script against the proper interpreter.  As more and more people begin to adopt Windows 7 x64 into their environments this issue will become more and more prevalent.  Fortunately there is a simple solution.  Build in your package source directory multiple batch files that contain the following in them:

if exist %systemroot%\SysWOW64\cscript.exe goto 64
cscript "inventory.vbs /full"
exit
:64
%systemroot%\SysWOW64\cscript.exe "inventory.vbs /full"
exit

You will want to build one for each variant of the script you will be running.  This also eliminates the need of creating double of every package>program and prevents you from having to do any advertisement restrictions, it will all be managed at run time.  Modify lines 2 and 5 of your bat file for whatever you need to be run and you are all set.

Finally, one more note of interest.

When building your advertisement, make sure the data is being downloaded before execution (default setting).  For good measure make sure it’s also enabled for unprotected distribution points under the advertisement schedule page.

download

As far as the command line is concerned it just needs to be:

batfilename.bat

That’s it for now. 


Also, I plan on posting a guide for building a Powershell script you can schedule to pull AD information to a SQL database which you can leverage for quick information gathering. Until then, have a good one.

Ok, so as I discussed in my previous post I built multiple collections that determine client inventory health.

So the end result is the ability to build collections based off of machines who haven’t reported to one or more inventory types for X number of days and have the script deployed to them auto-magically with the corresponding inventory type.

This is one of the areas where SCCM (from the console level) becomes pretty restrictive.  In MSSQL you have access to a couple of functions that make determining time frames very simple.  In this case DATEDIFF and GETDATE which combined provide a nice simple statement for determining a fixed time frame.

DATEDIFF(d, column-to-check, GETDATE()) >= 30

 

Ok, great.  So what’s the problem?  Well when building collections in SCCM you have to use WQL, and it doesn’t have such a robust function set.  Fortunately there is a way around this, and I’m going to give a few SQL queries you can use to build some inventory health collections.

Start by building a new empty collection, and during the creation process make a standard query rule and save it.  Now right click and go to properties of your new collection and copy it’s Collection ID.

Now, open up your sql management studio and connect to your site server DB.  Make sure you are connected to the proper DB and run the following query:

select QueryExpression from v_CollectionRuleQuery
where CollectionID = '(pasted collection id)'

 

What you should see is the SQL being used on the back end to present to your console.  Now what you need to do is update this column to match whatever query you need.  Bear in mind, when you are redefining things inside this query they need to match the WQL schema for the console to get the information it needs.  I’ll show you examples later.  I also want to point out, this is not supported by Microsoft, and if you don’t properly structure your Update statement you could end up hosing all your collections, so be safe.  Now here is how you do it.

Update v_CollectionRuleQuery
Set QueryExpression = ‘whatever query statement you want’
where CollectionID = ‘(pasted collection id)’

 

Now when you update membership and refresh that collection you should see results to match your query.  Ok, now here’s the kicker.  Never modify this collections query properties from inside SCCM, the changes you made will be overwritten if you do.

Now, about those queries I promised you.


--No Inventory for 30 days
SELECT SMS_R_System.ItemKey, SMS_R_System.DiscArchKey, SMS_R_System.Name0, 
   SMS_R_System.SMS_Unique_Identifier0,SMS_R_System.Resource_Domain_OR_Workgr0,
			SMS_R_System.Client0 
			FROM
				System_DISC AS SMS_R_System 
					JOIN softwareinventorystatus AS sw 
						ON 
					SMS_R_System.ItemKey = sw.ClientId 
						JOIN WorkstationStatus_DATA AS wks 
							ON
						wks.MachineID = sw.ClientId 
			WHERE
				DATEDIFF(dd,sw.LastUpdateDate,GETDATE()) > 30 
					AND
				DATEDIFF(dd,wks.LastHWScan,GETDATE()) > 30


--No Hinv 30 days
SELECT SMS_R_System.ItemKey, SMS_R_System.DiscArchKey, SMS_R_System.Name0, 
		SMS_R_System.SMS_Unique_Identifier0,
			SMS_R_System.Resource_Domain_OR_Workgr0, SMS_R_System.Client0 
		FROM System_DISC AS SMS_R_System 
		JOIN WorkstationStatus_DATA AS wks 
				ON 
			 wks.MachineID = sms_r_system.ItemKey
		WHERE 
			DATEDIFF(dd,wks.LastHWScan,GETDATE()) > 30


--No Sinv 30 days
SELECT SMS_R_System.ItemKey, SMS_R_System.DiscArchKey, SMS_R_System.Name0, 
		SMS_R_System.SMS_Unique_Identifier0, 
			SMS_R_System.Resource_Domain_OR_Workgr0, SMS_R_System.Client0 
		FROM 
		System_DISC AS SMS_R_System 
			JOIN softwareinventorystatus AS sw 
				ON
			SMS_R_System.ItemKey = sw.ClientId 
		WHERE 
			DATEDIFF(dd,sw.LastUpdateDate,GETDATE()) > 30


--Client with no DDR
SELECT SMS_R_System.ItemKey, SMS_R_System.DiscArchKey, SMS_R_System.Name0, 
		SMS_R_System.SMS_Unique_Identifier0,
			SMS_R_System.Resource_Domain_OR_Workgr0, SMS_R_System.Client0 
			FROM System_DISC AS SMS_R_System 
				JOIN softwareinventorystatus AS sw 
					ON
				SMS_R_System.ItemKey = sw.ClientId
					JOIN WorkstationStatus_DATA AS wks 
						ON 
					wks.MachineID = sw.ClientId 
			WHERE 
				DATEDIFF(dd,sw.LastUpdateDate,GETDATE()) > 5 
					AND 
				DATEDIFF(dd,wks.LastHWScan,getdate()) > 5 
					AND 
				SMS_R_System.Client0 = 0


If you need to specify a collection for exclusion (which if you build all of these you may want to exclude machines in the NO inventory collection) append this to the end of your query.

						and
					SMS_R_System.ItemKey not in (select ResourceID from v_cm_res_coll_CollectionID)


 

And there you have it.  When writing your update line I would change these sql queries to be one line and remove the comment obviously.  There is also a LimitToCollectionID column you might want to apply any specific restrictions to.

Hopefully these past two posts help a few people looking to take an automated stance to proactively resolving inventory reporting issues on clients.  For anyone else:

  1. Hopefully you learned something about sql?
  2. You got a nice refresher on the collection query views name?

 

Have a good one.

Update: Code has been re-written from the previous post to make full use of WMI as the means of execution, and scripting dictionary to simplify reporting and controls

Alright, so I’ve got a bit of a problem.

A large volume of data_loader kick backs, and resynch requests.  The problem is, for one reason or another, the clients inventory data is being held up.  Sure, plenty of machines are only missing records for maybe 3, 4, or 5 days.  However I’ve started to see machines that aren’t getting a record in for about 15 days or more.

This shall not stand!  Mind you I’m not going to fix these one by one either.  So what now?

Script!

So I begin to dive into the CCM namespace looking for a method to force a full inventory. Which brings me to the InvAgt class.  Great!  But wait, I don’t see any method for just forcing an inventory.

This is no longer the object used in the script, but leaving here for reference:

I’ll save you the rest of the story and just get to what I found.  According to Technet, the best way to “script” the solution is to delete the InventoryActionID from the InventoryActionStatus in WMI and use the CPApplet COM automation class to invoke the rescan.

They were also nice enough to provide their own code so it was made increasingly more simple to build the following script as I already had the core functionality objects defined for me.  Now, I needed to weaponize code for deployment…. Perhaps weaponize isn’t the best term, but I needed it to deploy and do some work via SCCM.

So I decided to allow 4 arguments and 2 switches that would allow me to perform:

  1. Hardware Inventory (hinv)
  2. Software Inventory (sinv)
  3. Discovery Data (ddr)
  4. File Collection (file)

 

I also wanted to be able to fire this off in 2 methods, one to clear the old inventory instance ID information and force a full inventory or just force an inventory.  I also wanted to be able to run this in a verbose mode to check and see if all actions were being completed as requested.  So I added the following switches:

  1. /full
  2. /debug

 

So the end result is the ability to build collections based off of machines who haven’t reported to one or more inventory types for X number of days and have the script deployed to them auto-magically with the corresponding inventory type.

I also set the script so someone could use it ad-hoc on a machine by double-clicking.  The default behavior is to NOT delete the IDs but to initialize all 4 of the inventory calls.  I also provided CONST declarations at the top so anyone could add or remove what they want in there (they will however need to modify the arrays arrinvtypes and arrkeys to match as well as the select case statement to add additional arguments).

For people that don’t give a hoot about SCCM (there are plenty of you, shockingly enough) feel free to examine the way the loops and conditionals are being used in this script.  They coorelate back to the fundamentals I have covered previously in my stick to the script series.

  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…

 

Finally, the code…..

'||============================||
'||Author Daniel Belcher       ||
'||Full HInv                   ||
'||Date 9/22/2011			   ||
'||Updated 11/7/12             ||
'||============================||
'==================================================================================
'Usage: For any prefered deployment method
'This script can:
'	1) Initiate Soft, Hard, Discover, File Collection on a client PC
'	2) Clear agent inv cache and perform full collection
'
'	cscript.exe inventory.vbs
'
'It's possible to target single inventory types or cherry pick them as needed.
'Accepted arguements are:
'1) hinv (performs a hardware inventory)
'2) sinv (performs a software inventory)
'3) ddr  (performs a discovery data)
'4) file (performs a file collection)
'
'Accepted switches are:
'1) /full (blows away all inv cache for declared inventories and initiates request)
'2) /debug (runs the script verbose to check things are running)
'Using /full or /debug it's best to target an inventory type, but not required.
'
'All arguements and switches are case insensitive.
'
'|Objects, Variables, and Constants ***********************************************
'==================================================================================
'Constant strings for cleanup and initialization subroutines.
'==================================================================================
Option Explicit
Dim oWShell,oWmiLoc,oDict,Args,sArgs,nArgs
Dim Item,x,Full,DEBUGMSG
	Set Args 	= Wscript.Arguments
	Set	NArgs 	= Wscript.Arguments.Named
    Set oWShell = CreateObject("WScript.Shell")
    Set oWmiLoc = CreateObject("WbemScripting.SWbemLocator")
    Set oDict 	= CreateObject("Scripting.Dictionary")
'Add additional INV types here with IDs and update Case & dictionary key item pairs
Const sHinv = "Hardware Inventory Collection Cycle"	
	CONST Hinv = "{00000000-0000-0000-0000-000000000001}":oDict.Add sHinv, Hinv
Const sSinv = "Software Inventory Collection Cycle"
	CONST Sinv = "{00000000-0000-0000-0000-000000000002}":oDict.Add sSinv, Sinv
Const sDDR  = "Discovery Data Collection Cycle"
	CONST DDR  = "{00000000-0000-0000-0000-000000000003}":oDict.Add sDDR,  DDR
Const sFile = "Standard File Collection Cycle"
	Const File = "{00000000-0000-0000-0000-000000000010}":oDict.Add sFile, File
'|Main Run ***********************************************************************
'=================================================================================
'Checking for Named arguments
If NArgs.Exists("Full") Then
	Full = TRUE
		Else
	Full = FALSE
End If
		if NArgs.Exists("debug") Then
				DEBUGMSG = TRUE
					Else
				DEBUGMSG = FALSE
		End If
'Check for Unnamed arguments
If Args.Unnamed.Count > 0 Then
	If DEBUGMSG then wscript.echo "Unnamed arguments Found..."
	'Looping arguments looking for declared Inv types
	For Each item In Args
		Select Case lcase(item)
			Case "hinv"
				If Full Then
					DelInvActionID sHinv
						wscript.sleep 1500
				End If
					RunInvAction sHinv
			Case "sinv"
				If Full Then
					DelInvActionID sSinv
						wscript.sleep 1500
				End If
					RunInvAction sSinv
			Case "ddr"
				If Full Then
					DelInvActionID sDDR
						wscript.sleep 1500
				End If
					RunInvAction sDDR
			Case "file"
				If Full Then
					DelInvActionID sFile
						wscript.sleep 1500
				End If
					RunInvAction sFile
		End Select
	Next
else
	'If no Unnamed arguments then loop through appropriate arrays
	'based on /full or not
	If DEBUGMSG Then wscript.echo "No Unnamed Arguments found, " _
	&"checking for full switch..."
	If Full Then
		If DEBUGMSG Then wscript.echo "/Full switch used, " _
		&"clearing caches..."
		For Each item in oDict.Keys
			DelInvActionID item
				wscript.sleep 1500
		Next
	End If
		If DEBUGMSG Then wscript.echo "Initiating HINV, SINV, DDR, " _
		&"and File Collection now..."
	For Each item in oDict.Keys
		RunInvAction item
			wscript.sleep 1500
	Next
End If
Report
Wscript.Quit(0)
'SubRoutines *********************************************************************
'=================================================================================
'Sub to delete the InventoryActionID as requested
Sub DelInvActionID(guid)
		On Error Resume Next
	Set oInvAgt = oWmiLoc.ConnectServer(,"root\ccm\invagt")
			oInvAgt.Delete "InventoryActionStatus.InventoryActionID='"& _
				oDict.Item(guid)&"'"
	If DEBUGMSG Then wscript.echo "Clearing "& _
		oDict.Item(guid)&" from InventoryActionStatus"
End Sub
'*********************************************************************************
'Sub to initialize Inventory Cycle requested
Sub RunInvAction(name)
		On Error Resume Next
Dim smsclient:Set smsclient=GetObject("winmgmts://./root/ccm:sms_client")
	smsclient.triggerschedule(oDict.Item(name))
		If DEBUGMSG Then wscript.echo "Running "&name
End Sub
'**********************************************************************************
'Sub to report script completion if /debug
Sub Report
         If DEBUGMSG Then wscript.echo "Complete" 'Set for popup on script complete
End Sub
'End ******************************************************************************
'==================================================================================

I want you to think of a few things that will help you to remain mission minded. For the record, these are things I ask myself, or pose to myself on a regular basis; today has been one of those days.

 

God is sovereign, he placed you where you are.

You will be going into work, or staying home, or taking rest today because it was ordained by God. This same God knit you together in your mother’s womb, he also knit the people around you in their mother’s womb. The people you will see today are intended for you to see, they are not an accident.

Do you believe that?

 

You have nothing to fear or worry over, your food, your clothing, your social status.

Do you know what it is to be hungry? Do you know what it is to be a social pariah? Do you know what it is to be underdressed. Now ask yourself this, what did my worrying do to improve/resolve this problem? I believe when you evaluate that you realize it contributed nothing. I believe you will realize it is in God’s hands.

Do you believe that?

 

We go day in and day out, neglecting our God.

Our very hearts and minds drift from him towards desires of the flesh. Towards what will satisfy us physically and emotionally, we whore ourselves to it. Our work, our children, our church, our friends, ourselves.

Do you believe that?

 

We do not deserve one iota of respect, patience, peace, mercy, or love from the almighty being that created us.

We deserve to die, we are like dust before the lord. Apart from God and then compared to God, we don’t even register. We couldn’t even stand in his presence! We couldn’t even look at him!

Do you believe that?

 

This same God sent his only son, himself, in the flesh, to DIE for YOU.

Do you believe that?

 

We are forgiven, we are forgiven, we are forgiven, WE ARE FORGIVEN!

Do you believe that?

 

Who can stand before our God!? Who can hold back his hand!? How can anyone not be amazed by our God? If you see him, hear him, feel him, know him, then how can you not be amazed by our God?

Do you believe that?

 

From the overflow of our hearts comes praise and worship.

What is praise? If your child learns to walk, if you get a new car, if you got a great deal on clothes; how do you react? You want to tell everyone about it, if you are like me you can’t shut up about it! That is praise, how much MORE then should we praise God? What has been done for us? We are forgiven, we are loved, we are provided for, we will live forever, we are heirs to the throne, we are children of the light. Why would we not talk about it? If our God is in control, and we are forgiven even though all signs say we shouldn’t be; then why are we not on FIRE to tell people?

 

There is no feasible excuse outside of: we don’t believe.

Recently I was subjected to a “spill” regarding a lack of “can do attitude”.

Now lets be clear on this.

This speech came to my team after disclosing that certain job functions owned by others should be completed by others.  Mind you, our assistance is certainly available if needed, but if it falls out of our realm of requirement or ability it shouldn’t be our responsibility for it’s completion.

There have been other times where saying “no” was tied directly towards not following a path that would lead to serious operational and financial issues at a later time.  These instances were met with the same response.

This type of mentality leads to a lot of frustration, in my environment, and in others.  Not to mention stress for those around who have to audible and absorb the shock of reckless decision making.  Especially decision making that is driven by a single party, who against advisement; persists on a course of destruction.  On the way vilifying those who oppose them from a sense of stewardship and reason.

This has become a serious problem in our business culture.  I do believe, for the sake of innovation, we need to challenge things.  I do believe we need to ask “why not”, but when the answer for why not is sound you need to stop.  The best I can figure is that this mentality is simply driven by the ego, or ignorance of the individual making the decisions.  Either they trust themselves far more than their advisors, or they don’t fully grasp what they are being advised about.  In some instances it may be both, and all they can see is the future praise they expect to receive upon crossing their finish line.  What’s worse?  This behavior is greatly encouraged in management.  The individuals who are supposed to manage and decide on the greater interest of the company are taught to do so off their gut and some pop-psych concept of anything is possible.

What is wrong with saying no?  What is wrong with saying the cost of this implementation and it’s continued support far outweighs any of it’s benefits?  What is wrong with saying I can’t do something?  What is wrong with saying, “we have people paid to perform these jobs, why is it on our plate and not theirs?”

Nothing, there is nothing wrong with it.  The argument might come up that we aren’t team players, but the last time I checked a team was the sum of all members and not one member doing the work of all the other members.  Each has a role to serve and they serve it, that is a team.  Carrying the burden of a few or supporting team members where you can, sure, but not out right taking over their position.

To someone in management reading this I would tell you these two things that will infinitely improve your situation and your subordinates:

  1. Don’t commit from a position of ignorance
    • Ignorance of the subject, or it’s criteria
  2. Trust your subordinates
    • Trust their advisement
    • Trust their knowledge

    One last thing on trust. If you can’t trust them, why are they still working for you?

    Alright, so last time I closed out my(sql) post I promised some more advanced queries etc.  Well let’s first start by playing around with some basic query syntax.

    Think back to what I wrote about it being a logical grouping of data like a spreadsheet.  So surely we can pull specific data right?  Of course, this is where sql shines, and it couldn’t be simpler.

    select user_id0 from temp.test_users; 

     

    Pretty simple right?  Ok, well let’s grab user id’s and their location, that should also be simple enough.

    select user_id0, location from temp.test_users;

     

    Now how about just the user’s located in Birmingham, al?

    select user_id0, location from temp.test_users 
    	where location like 'birmingham%';

     

    Ok, let’s take a moment now and examine what we’ve just covered here in such rapid succession. These are simple select statements, and the primary data retrieval method in SQL.

    select <column, names> from <server.database.table> 
    	[where <conditions of the search>]

     

    You can use * for column names to select them all, and using where is not required for your statements, but advised for a precise query.  Couldn’t be easier could it?  A cool little tidbit too is using as in your query to modify your column names, using our previous select for user id’s and location lets do it again and rename our columns User ID and Place:

    select user_id0 as 'User ID', location as 'Place' 
    	from temp.test_users 
    where location like 'birmingham%';

     

    What?  That’s it?  Pretty nifty huh?  Ok, let’s turn the difficulty up a little bit now and join tables for a cross reference.  Ok, I built a bogus phonebook table with similar data to our test_users table.  In that table I have some phone numbers, but not the full name of the users.  I want to pull the users full name and phone number, here’s how I could do that:

    select test.last_name, test.first_name, phone.number 
    	from test_users as test 
    left outer join phonebook as phone 
    	on 
    phone.userid = test.user_id0;

     

    Ok, you can put the paper sack away, and breathe easy.  That’s not nearly as complex as it looks or sounds.  Let’s break it down piece by piece and examine it real fast.  First we will look at the output:

    +-----------+------------+--------------+
    | last_name | first_name | number       |
    +-----------+------------+--------------+
    | belcher   | daniel     | 205-111-1111 |
    | rich      | derrek     | 813-111-1113 |
    | george    | amanda     | 205-111-1112 |
    +-----------+------------+--------------+

     

    In our select statement we see column last_name, first_name, and number.  We examined earlier about using ‘as’ to define a name, and that’s what we have done during that select statement.  We’ve named the table test_users as test and phonebook table as phone.

    So, before defining the column name we are selecting, we have to identify FROM which table.  In this case; test.last_name, test.first_name, phone.number

    Now, let’s examine the data I put into phonebook to better understand how this join is working.

    +--------+---------+----------------+--------------+
    | userid | last    | location       | number       |
    +--------+---------+----------------+--------------+
    | dbel   | belcher | birmingham, al | 205-111-1111 |
    | ageo   | george  | birmingham, al | 205-111-1112 |
    | drich  | rich    | tampa, fl      | 813-111-1113 |
    +--------+---------+----------------+--------------+

     

    Ok, as you can see, the userid column is identical to our user_id0 from test_users which makes it a prime anchor point for our join. So we perform a left outer join on test.user_id0 and phone.userid.

    Now wasn’t that easy?

    Finally we are going to look at a subquery.

    select user_id0, last_name, first_name 
    	from test_users 
    where location in ('birmingham, al') 
    order by user_id0;

     

    This should prove very simple to read.  If the data stored under location matches birmingham, al then it is pulled.  You could easily add more criteria to the subquery by adding it along with a comma to separate the value.  So; where location in (‘birmingham, al’,’tampa, fl’)

    There are other ways to achieve similar outcomes using OR and AND, but this is a much cleaner and shorter method for doing it.

    That’s it for now, perhaps I’ll have another sql post with even more interesting sql techniques in the future.

    To all things God gets the glory.  This is something of a doctrinal mantra, but is it something you believe?

    We know that God is faithful according to Scripture.  Having on a multitude of occasions fulfilled his promises to his elect.  Not necessarily in their lifetimes, but certainly fulfilled.

    So what do these two things tell us about God’s character, and what it should mean to his elect?

    Its never too late, and nothing is impossible. 

    God is most glorified when we are most incapable of receiving glory.  That is what is meant when it is said “my power is made perfect in your weakness” when we are removed, and God is the only one to receive the due credit, he will be most glorified.

    So take heart, that when you are broken, and all appears lost  There is God, and in him there is our hope. 

    So then what does his faithfulness have to do with that? 

    Well he has promised that all good to those who love him and are called according to His purpose for His glory.  If you are His, and in you is His glory, and that glory is in your good; how can you lose?

    I don’t say that from a prosperity stand point, but from a point of faith and promise.  In the vastness that is God’s grace and mercy, we find even more to love him for.

    In our brokenness we find his Glory, and like everything he does, it’s a beautiful reversal.