Skip navigation

Tag Archives: sccm

Ok, so I didn’t see this documented anywhere, but found a need to reduce additional I/O from our SCCM application folder (thanks RCM and BCP).

Anyway, thanks to Stack Overflow and a random post I ran across about enumerating and changing registry values simply, here’s an example that would move them from e: to a similar folder structure on i:

( I’ve modified these to make them readable within the sites format, be sure to delete any breaks and have them as a single line before copying them into your console.)

get-itemproperty -path HKLM:\software\microsoft\sms\tracing\* tracefilename | 
%{set-itemproperty -Path $_.PSPath TraceFilename -Value 
( $_.TraceFilename -Replace "e:","i:")}

and

get-itemproperty -path HKLM:\Software\Microsoft\sms\providers\ "Logging Directory" | 
%{set-itemproperty -Path $_.PSPath "Logging Directory" -value 
( $_."Logging Directory" -Replace "e:","i:")}

( I’ve modified these to make them readable within the sites format, be sure to delete any breaks and have them as a single line before copying them into your console.)

Finally restart the sms_executive service and you should be good to go.

I’ve updated the inventory enforcement script and post for anyone who utilizes it. It should be cleaner now as it only depends on wmi for the inventory actions.

Here’s the link back.

Alright, so if you read my previous post for AD to DB then this post will make more sense.  However if you haven’t; then now would be a good time to… go ahead, I’ll wait.

Now one of the primary purposes I had for this data was to leverage it against my v_r_system view and determine which active assets are missing their client.  Well that’s fine and good, but I had been in the habit of taking that data and then performing a DNS check for the entries using a Powershell script written by Jason Sandys.  Originally I was using a vbscript I wrote to do so, but found his to be far more efficient since it made use for the DNS class in .Net.  But I digress, the end result is that I had quite a few additional steps to determine which machines were active, and ready for remediation either locally by desktop support, or by my remote repair tools.

So, what to do?  Why not query what I need, run the DNS check from a data set, then write the results back to my data warehouse?  This script requires a few things:

  1. Working, integrated credential for querying the SCCM DB; and permission to drop, insert, and create for the DB warehouse.
  2. Table within the data warehouse with the AD data provided with my AD to DB script to join against the SCCM DB data.
  3. Established linked servers between the two databases to perform the join (stored query in the script calls the join from the SCCM DB server, so the link is required there)

 

Now that we have that out of the way lets discuss the variables that need to be modified here.

  • $db – SCCM Database for the primary site server
  • $sqlsrvr – SCCM Database Server Name
  • $db2 – Data Warehouse DB
  • $sqlsrvr2 – Data Warehouse Server Name
  • $table – Data Warehouse AD Table

 

Alright, so there it is, now time for the code; which I want to apologize in advance for it’s wide column width (download):

#We expect errors for hosts we can't find, so running silently
	$ErrorActionPreference = "SilentlyContinue"
#Configuring connection and query variables for the sql client adapter
$db = "sms_abc" 					#sccm database
$sqlsrvr = "SCCMDBServer"  			#sccm db Server Name
$db2 = "DataWarehouse"				#Data Warehouse db
$sqlsrvr2 = "DataWarehouseServer"	#Data Warehouse Server Name
$table = "ADtablefromDatawarehouse"	#The table where AD data is stored
$sqlquery = "select sys.Name0 from $sqlsrvr.$db.dbo.v_r_system as sys join `
			$sqlsrvr2.$db2.dbo.$table as adlist on adlist.ad_machine = sys.name0`
			where DATEDIFF(d,passwordlastset,getdate()) <= 30 and Client0 = 0 or`
			DATEDIFF(d,passwordlastset,getdate()) <= 30 and Client0 is null"
#Performing the query and writing to a data set
$sqlcon = New-Object System.Data.SqlClient.SqlConnection("Data Source=$sqlsrvr;Integrated Security=SSPI;Initial Catalog=$db;")
	$cmd = New-Object System.Data.SqlClient.SqlCommand
		$cmd.CommandText = $SQLQUERY
			$cmd.Connection = $SQLCON
	$sqladapter = New-Object System.Data.SqlClient.SqlDataAdapter
		$sqladapter.SelectCommand = $CMD
			$DS = New-Object System.Data.DataSet; $DS.Tables.Add("SQLQuery")
	[Void]$sqladapter.Fill($DS.Tables["SQLQuery"])
$sqlcon.Close()
#Building new table in SQL for DNSQuery
$table = "NoClientDNSRecord"	
	$sqlcon = New-Object System.Data.SqlClient.SqlConnection("Data Source=$sqlsrvr2;Integrated Security=SSPI;Initial Catalog=$db2;")
$sqlcon.Open()
	$cmd = $sqlcon.CreateCommand()
		$cmd.CommandText = "drop table $table"
			[Void]$cmd.ExecuteNonQuery() 
		$cmd.CommandText = "create table $table (Name varchar(150) not null Primary key,IP varchar(25), Reverse varchar(150), status varchar(50))"
			[Void]$cmd.ExecuteNonQuery() 
#Performing a DNS query against each machine in our SQL data set
foreach($row in $DS.Tables["SQLQuery"].rows){
	$system = $row[0]
	$sys = New-Object PSObject
		$sysname = $system.ToLower().Trim()
			$sys | Add-Member -MemberType NoteProperty -Name Name -Value $sysname
	#Getting IP address for the host name
	$sys | Add-Member -MemberType NoteProperty -Name IP -Value "-"
		$sys.IP = [System.Net.DNS]::GetHostEntry($sysname).AddressList | select -First 1
			$firstOctet = ($sys.IP -split "[.]")[0].Trim()
	#Getting reverse address from dns for the host name
	$sys | Add-Member -MemberType NoteProperty -Name Reverse -Value "-"
		$sys.Reverse = [System.Net.DNS]::GetHostEntry($sys.IP).HostName | select -First 1
			$sys.Reverse = ($sys.Reverse -split "[.]")[0].ToLower().Trim()
				if ($sys.Reverse -eq $firstOctet){$sys.Reverse = "-"}
	#Writing a status for the entry based on  name and reverse lookups.	
	$sys | Add-Member -MemberType NoteProperty -Name Status -Value "-"
		if		($sys.IP -eq "-")			`
		{$sys.Status = "Could not Resolve IP"}
		elseif	($sys.Reverse -eq "-")		`
		{$sys.Status = "IP Address not found in reverse zone"}
		elseif	($sys.Name -ne $sys.Reverse)`
		{$sys.Status = "IP registered to another system"}
		else								`
		{$sys.Status = "OK"}
#Writing values to SQL
$cmd.CommandText = "insert $table values ('$($sys.name)','$($sys.ip)','$($sys.reverse)','$($sys.status)')"; [Void]$cmd.ExecuteNonQuery()}
$sqlcon.close()

 

I’d recommend using PowerGUI for reviewing/modifying this code as it’s by far the best (free) powershell editor available.

Until next time, have a good one!

So I had another problem, and one I know I’m not alone in…

I’ve got clients that are failing, won’t install, have corrupt wmi repositories, and obviously I can’t deploy a repair solution to them so what do we do?

Well like most people in an enterprise environment (or smaller I’m sure) we maintain a logon script, and considering that this script will run come hail or high water it is clearly the best possible automated resolution point possible.

There have been some really great log on health check scripts written by a lot of great people in the MyITForum community, and having used two of the more popular ones I’ve decided there are some great things in both of them, but in one case more than what I need; and the other just short of my needs.

So what do we do?  Simple, write our own; which you can download from a link at the bottom of this post.

So lets first look at what it takes to run this script:

CmLogonFrameWork.wsf + config.xml

At run time you can configure 4 override settings:

  • /log:”c:\windows”

This will write the logfile to the windows directory.

  • /config:”somefilesomewhere.xml”

This will load the specific config file you need, useful if you have multiple configurations for multiple machine/user types.

  • /events

This will force the script to write events to the event log regardless of how it’s defined in the config.xml

  • /debug

This will force the script to error verbosely, which will become useful if you are going to extend the code and need to see the error output.

So what does the script do?  Well I’ve put my horrible Visio skills to work to give you the obfuscated flowchart that might very well make you want to claw your face off (included in the script download).  However I’ll give you a quick overview of the intended functionality to save you from all the head scratching and the “what was this guy smoking” statements you might have as you read it.

It’s best to think about this script in 5 blocks:

  1. Initialization
  2. System Check
  3. SCCM Check
  4. SCCM Configuration
  5. Close Out

 

Initialization:

This block is fairly straight forward.  We gather arguments, enforce a cscript execution (for cleanliness more than anything), generate our first log entry, load the configuration file, and write a LastRun entry to HKLM\Software\SccmHealth for tracking of changes and repair mechanisms later.

The only potential repair function during this phase would be to the XMLDom (and all the script will attempt to do is register the component).  If OS version checks fail, or the XML file cannot be read then the script will close with an error in the log.

System Check:

The system check is also fairly straight forward.  We first check the admin account if one is configured, we check the admin shares, we check the list of services defined in the config, and finally we verify that the root/cimv2 is accessible in WMI.

Repairs that would occur in this phase are the enabling of admin shares via service and registry values.  Services are configured per the config file if they are not presently in that state. And finally if it’s enabled, an attempted wmi rebuild would be performed if wmi fails its check (there are two distinct repair types determined by the version of windows).

SCCM Check:

Now things get a bit more confusing, but I’ll keep it high level since I have a bit of an election system in the script on what repair method is the best option.

Check the CM namespace in WMI, then the service, then the executable, and finally the setup files.  If all 4 fail or 3 of 4 then a standard installation will occur.  If only the namespace fails then a reinstallation is attempted provided that option is allowed, if not then a wmi repair is attempted if it is allowed.  There are other checks that manipulate the outcome such as your configuration options obviously and when the last repair date was attempted on the asset.

SCCM Configuration:

This section is very straightforward.

Check the Site code, and check the cache size, if they don’t match the config, we change them to match.

Close Out:

As our final phase we load any additional scripts identified in the config file, generate our System Check, SCCM Check, and SCCM Configuration check report card.  If remote logging is enabled we write the final output there as well, and finally we deconstruct our objects and  terminate the script with or without errors depending on the outcome of course.

Tips for Extending:

The two custom objects being used here in this script are cls_Logging and cls_Dict which are instantiated as Logging and Config respectively.

A list of these classes and how they work can be found here (logging) and here (config).

I’ve also included a test.vbs that extends the script to give you an idea of some of very basic examples of extended functionality.  I would recommend you avoid adding anything to the primary script, but instead extend it all as a separate script and have it performed at the end of the script, unless of course it’s an entirely new object that you wish to build into this tool then by all means have at it.

 

If you have any questions, suggestions, or if you find bugs please comment so I can answer them or repair them, thanks.

Download:

Version 2.1.3

Ran into this on a failing MP repair in our DMZ.  The error was a 1603, and according to the mp.msi logs it was unable to create the virtual directories for the MP to function.  What was looking like a complete IIS rebuild turned out to be a known issue surrounding BITS; and a far simpler solution then I had originally imagined.

The long and short or it; uninstall and reinstall the BITS feature, then reinstall the MP site component and bam.

 

A simple vbscript I use for manual client installation. It does some basic quick checks and fixes before begining an install. One could feasibly use this for health checking, but it’s not nearly as robust as my actual logon framework or other scripts from people like Jason Sandys or Dan Thompson.

The variables strAdmin (local admin service account), strCcmSetup (path to folder with the ccmsetup.exe), and strArguement (install string) need to be defined before running the script. It’s worth mentioning that strCcmSetup is just the path to ccmsetup.exe, there is no need to actually type ccmsetup.exe into the path and it’s best if you don’t since I didn’t bother writing anything in to verify if it is or isn’t. The script will auto append the executable to that variable so ccmsetup.exe in the path will give you ccmsetup.execcmsetup.exe

'Author Daniel Belcher             ||
'CCMsetup Function                 ||
'Date 2/11/2011 rev 5/20/2011      ||
'==================================||
'|Objects, Variables, and Constants ********************************************
'=============================================================================||
'|| Non-Standard Installer Variables - Please define them                     ||
'|| Admin Account
	strAdmin = "domain\user"
'|| Path to ccmsetup.exe
	strCcmSetup = "\\path\where\ccmsetup.exe\resides\"
'|| Install string
	strArguement = "/noservice SMSSITECODE=ABC SMSSLP=SERVER.ADDRESS " _
				& "SMSFSP=SERVER.ADDRESS"
'                                                                             ||
'=============================================================================||
Const DEBUGMSG = False 'Boolean to use for testing False = Silent True = Verbose
Const ForAppending = 8
Dim oWShell
Set oWShell = CreateObject("WScript.Shell")
Dim oFSo
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oNet
Set oNet = CreateObject("Wscript.Network")
ComputerName = oNet.ComputerName
Dim Target
Target = "."
Dim oWMISvc
Set oWMISvc = GetObject("winmgmts:\\"&Target)
'|Main Run *******************************************************************||
'=============================================================================||
WriteLog "Starting "&Wscript.Scriptname&" on "&ComputerName,2
PreReq
CCMSetup
Report
'SubRoutines *****************************************************************||
'=============================================================================||
Sub WriteLog(msg,mtype)
'Subroutine for writing the log
logname = wscript.scriptname&".log"
if not oFSo.FileExists(logname) then
oFSo.CreateTextFile(logname)
end if

msgline = "<![LOG["&msg&"]LOG]!><time="&""""&DatePart("h",Time)
msgline = msgline &":"&DatePart("n",Time)&":"&DatePart("s",Time)
msgline = msgline &".000+0"""&" date="""&Replace(Date,"/","-")
msgline = msgline &""""&" component="""&WScript.ScriptName
msgline = msgline &""" context="""" type="""&mtype
msgline = msgline &""" thread="""" file="""&WScript.ScriptName& """>"

Set oLogFile = oFSo.OpenTextFile(logname, ForAppending, True)
    oLogFile.WriteLine msgline
oLogFile.Close
if DEBUGMSG then wscript.echo msg&" "& mtype
End Sub
'*******************************************************************************
Sub SvcStart(service)
'Attempts to start a service
Set WMIServices = oWMISvc.ExecQuery _
("Select * from Win32_Service where name = '"&service&"'")
     For Each item in WMIServices
         if lcase(item.startmode) <> "automatic" then
                             item.ChangeStartMode("Automatic")
         end if
         start = item.startservice()
         wscript.sleep 4000
           if start <> 0 Then
                   WriteLog "ERROR: Failed to start the "&service&" Service, " _
                   & "investigation required", 3
                             wscript.quit(0)
                    else
                    WriteLog "Succesfully started "& service &" Service",1
           end if
     next
End Sub
'|Functions ******************************************************************||
'=============================================================================||
Function PreReq
'Prerequisite check for client installation
Set WMIServices = oWMISvc.ExecQuery _
("Select * from Win32_Service")
strService = "lanmanworkstation"
regAdminSPath = "HKLM\SYSTEM\CurrentControlSet\services\LanmanServer\" _
				& "Parameters\"
 For Each item in WMIServices
          if lcase(item.name) = strService then
             if lcase(item.state) <> "running" then
                writelog "Warning: "&strService&" was not running, " _
                & "attempting to start...", 2
                SvcStart strService
             else
                 writelog strService& " was found running, OK", 1
             end if
          end if
 next
if not oFSO.FolderExists("\\"&computername&"\admin$") then
WriteLog "Warning: Admin shares not available, attempting to add " _
		& "registry key...", 2
    On Error Resume Next
oWShell.RegWrite regAdminSPath & "AutoShareWKS", 1, "REG_SZ"
              if err.Number <> 0 then
WriteLog "ERROR: "&regAdminSPath&"AutoShareWKS, 1 failed to write, or " _
		&"already exists.", 3
                  else
WriteLog regAdminSPath&"Notice: AutoShareWKS, 1 written succesfully. " _
					& " Restart required to take effect.", 2
              end if
Wscript.Echo "AutoShareWKS key was written to: " &vbcrlf _
          &regAdminSPath & vbcrlf _
          &"Please restart the machine, and rerun this script"
else
WriteLog "Admin$ shares found, and working.", 1
end if
Set AdminCheck = GetObject("WinNT://" & oNet.ComputerName _
							& "/Administrators,group")
if AdminCheck.IsMember("WinNT://"& strAdmin) then
WriteLog "User "&strAdmin&" found in Local Adminstrators group", 1
        else
WriteLog "Warning: User "&strAdmin&" not found in Local Administrators group",2
        on Error Resume Next
           AdminCheck.Add("WinNT://"&strAdmin)
        if Err.Number <> 0 then
WriteLog "ERROR: Unable to add "&strAdmin&" to the Local Administrators group",3
           Wscript.Echo "Unable to add "&strAdmin&" to local Admins." & vbcrlf _
           &"Please do so manually and rerun this script."
           Wscript.Quit(0)
        end if
end if

End Function
'*******************************************************************************
Function CCMSetup
'Client detection and installation
Set WMIServices = oWMIsvc.ExecQuery _
("Select * from Win32_Service where name ='ccmexec'")
boorun = true
   for each objservice in WMIServices
       strservice = lcase(objservice.name)
           if strservice = "ccmexec" then boorun = "False"
   next
if not boorun then
For Each service in WMIServices
  if lcase(service.state) <> "running" then
     svcStart "ccmexec" 'Attempt to start service if stopped
WriteLog "Warning: CcmExec service found, but was not running, " _
		& "attempting to start...", 2
  end if
next
WriteLog "SCCM client service, CcmExec found, closing script", 1
	exit function
end if
if boorun then
oWShell.run strCcmsetup&"ccmsetup.exe " & strArguement
        WriteLog "CcmSetup has begun using: ccmsetup.exe"& strArguement,1
end if

End Function
'******************************************************************************
Function Report
 If DEBUGMSG then msgbox "Complete" 'Set for popup on script complete
End Function
'End *************************************************************************||
'=============================================================================||

As has become my standard, the logs are written in a markup that works with trace32.

Ok, so I’ve not posted anything for a few days and I felt the need to throw a brief technical post up with a code snippet from a current project I’m working on. I’m building a health check logon script and as part of that framework I wanted to build a logging object. Since the target format has to be vbscript for what I’m doing, I’ve built it as such, and in a format that views nicely inside of trace32 and trace64.

The idea was to build an object that would perform a simple task, write a log file…. then write a log file, or an event, then write only error events, but could also buffer and dump a final error or success log as a split log to another remote location. All configurable via properties, but with only two exposed methods to control it all (write & writeremote). This object is instantiated by:

Dim Logging
Set Logging = New cls_Logging

Call Logging.Write("my message",1)

Wscript.Quit(0)

Simple enough, no? It’s also worth mentioning I wrote the code so that a constant could be set within the instantiating script of DEBUGMODE and if TRUE it will error, else suppresses all error output.

Here’s the code:

'=================================================================================
'Logging Class ===================================================================
'=================================================================================

'Not required for WSF, but is when in standard VBS
Const ForAppending = 8

'Log and Event writer object
Class cls_Logging
'Class for logging to file and event viewer

Private oWShell,oNet,oFSo,Filehandle,rFilehandle
Private fPath,strRFPath,fMaxSize,fLogname,strRemoteErr,BoolEvent,BoolRemote,oDict

Private Sub Class_Initialize()
    'Object Init subroutine
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
    Set oWShell 	= CreateObject("Wscript.Shell")
	Set oNet 		= CreateObject("Wscript.Network")
	Set oFSo 		= CreateObject("Scripting.FileSystemObject")
	Set oDict		= CreateObject("Scripting.Dictionary")
		LogEvent 	= False
		RemoteLog	= False
		Path 		= Left(WScript.ScriptFullName,(Len(WScript.ScriptFullName)_
						-Len(WScript.ScriptName)))
		File 		= LCase(oNet.ComputerName)
		MaxSize = 2
End Sub

'---------------------------------------------------------

Private Sub Class_Terminate()
	'Object Termination subroutine
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	If bOpen Then
		Filehandle.close
	End If
		Set oWShell = Nothing
		Set oNet = Nothing
		Set oFSo = Nothing
		Set Filehandle = Nothing
		Set fPath = Nothing
		Set fMaxSize = Nothing
		Set fLogname = Nothing
		Set BoolEvent = Nothing
End Sub

'---------------------------------------------------------
'File name properties, for changing and retrieving the log file name
Public Property Let File(strFile)
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	If (InStr(StrReverse(strFile),"gol.")) <> 0 Then
		fLogname = strFile
	Else
		fLogname = strFile & ".log"
	End If
End Property
		Public Property Get File()
		    If Debugmode Then On Error Goto 0 Else On Error Resume Next
				File = fLogname
		End Property

'---------------------------------------------------------
'Path name properties, for changing and retrieving the path to logs
Public Property Let Path(strPath)
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
		If (InStr(StrReverse(strpath),"\")) <> 1 Then
			fPath = strPath & "\"
		Else
			fPath = strPath
		End If
End Property
		Public Property Get Path()
		    If Debugmode Then On Error Goto 0 Else On Error Resume Next
			Path = fPath
		End Property
		
'---------------------------------------------------------
'Fully concatenated file name property for retrival.
		Public Property Get FullFileName()
			FullFileName = Path & File
		End Property

'---------------------------------------------------------
'Property for setting maximum file size of log file
Public Property Let MaxSize(strVal)
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	fMaxSize = Cint(strVal) * 1048576
End Property
		Public Property Get MaxSize()
    		If Debugmode Then On Error Goto 0 Else On Error Resume Next
			MaxSize = fMaxSize
		End Property

'---------------------------------------------------------
'Boolean property to determine if the filehandle is in use
Private Property Get bOpen()
	If Debugmode Then On Error Goto 0 Else On Error Resume Next	
		If IsObject(Filehandle) Then
			bOpen = True
		Else
			bOpen = False
		End If
End Property

'---------------------------------------------------------
Public Property Let LogEvent( blValue)
'Bool property that dictates event viewer rights
	BoolEvent = blValue
End Property
	Private Property Get LogEvent()
		LogEvent = BoolEvent
	End Property
	
Public Property Let RemoteLog( blValue)
'Bool property that dictates if logging occurs to remote location
	BoolRemote = blValue
End Property
	Private Property Get RemoteLog()
		RemoteLog = BoolRemote
	End Property
Public Property Let RemotePath( strPath)
		If (InStr(StrReverse(strpath),"\")) <> 1 Then
			strRFPath = strPath & "\"
		Else
			strRFPath = strPath
		End If
End Property
	Public Property Get RemotePath()
		RemotePath = strRFPath
	End Property

'---------------------------------------------------------
Private Sub RemoteErrBuffer( strKey,  strItem)
'Method to concactenate new items under one key at the end of the string
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
		Dim concat

	If Not oDict.Exists(strKey) Then
		Call oDict.Add(strkey, stritem)
	Else
		concat = oDict.Item(strKey)
		concat = concat & "|:|" & strItem
			oDict.Remove(strKey)
		Call oDict.Add(strKey,concat)
	End If

End Sub

'---------------------------------------------------------
Public Function ErrBuffer()
'Method to return contents of the error buffer
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
    
    Dim ItemToSplit, ItemArray, item
	
	ItemToSplit = oDict.item("remotelog")
	
	ItemArray = Split(ItemToSplit, "|:|")
	
	ErrBuffer = ItemArray
	
End Function
'---------------------------------------------------------
Public Sub WriteRemote(strVal)
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
    	
	If Not CreateRemote Then
		Exit Sub
	End If

		rFilehandle.WriteLine strVal

End Sub

'---------------------------------------------------------
'Subroutine for creating the remote log file and instantiating the handle
Private Function CreateRemote()
    If Debugmode Then On Error Goto 0 Else On Error Resume Next

	Dim FileProperty,Logsize

	CreateRemote = False

	If Not oFso.FolderExists(RemotePath) Then 
		Call Write(RemotePath & " Does not exist, or is unreachable.",3)
			Exit Function
	End If 

	If Not oFSo.FileExists(RemotePath & File) Then
		oFso.CreateTextFile(RemotePath & File)
	Else
		oFSo.DeleteFile(RemotePath & File)
			oFso.CreateTextFile(RemotePath & File)
	End If    
		If Not IsObject(rFilehandle) Then
	       	Set rFileHandle = oFSo.OpenTextFile(RemotePath & File, _
	       	 ForAppending, True)
	    End If
	If oFSo.FolderExists(RemotePath) Then
		CreateRemote = True
	End If
End Function

'---------------------------------------------------------
'Subroutine for writing log entries
Public Function Write( msg,  mtype)
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	Dim msgline, etype
		Call Create()

		If Not bOpen Then
			Call Create()
		End If
    msgline = "<![LOG["&msg&"]LOG]!><time="&""""&DatePart("h",Time) _
    &":"&DatePart("n",Time)&":"&DatePart("s",Time)&".000+0"""&" date=""" _
    &Replace(Date,"/","-")&""""&" component="""&Left(WScript.ScriptName, _
    Len(WScript.ScriptName)-Len(".vbs"))&""" context="""" type="""&mtype _
    &""" thread="""" file="""&Left(WScript.ScriptName,Len(WScript.ScriptName)_
    -Len(".vbs"))& """>"

	Filehandle.WriteLine msgline


		Select Case Mtype
			Case 1
				etype = 0
			Case 2
				etype = 2
						If LogEvent Then
					oWShell.LogEvent etype, msg
						End If 
					Call RemoteErrBuffer("remotelog", msg  & "," & "2")
			Case Else
				etype = 1
						If LogEvent Then
					oWShell.LogEvent etype, msg
						End If
					Call RemoteErrBuffer("remotelog", msg  & "," & "1")
		End Select
	
End Function

'---------------------------------------------------------
'Subroutine for rolling over log file at file size limit
Private Sub Rollover()
    If Debugmode Then On Error Goto 0 Else On Error Resume Next
	If bOpen Then
		Filehandle.Close
	End If
	oFso.CopyFile FullFileName, Left(FullFileName,(Len(FullFileName)-1)), True
		oFSo.DeleteFile FullFileName
	Set FileHandle = oFSo.OpenTextFile(FullFileName, ForAppending, True)			
End Sub

'---------------------------------------------------------
'Subroutine for creating the log file and instantiating the handle
Private Sub Create()
    If Debugmode Then On Error Goto 0 Else On Error Resume Next

	Dim FileProperty,Logsize

	If Not oFSo.FileExists(FullFileName) Then
		oFSo.CreateTextFile(FullFileName)
	End If    
		If Not bOpen Then
	       	Set FileHandle = oFSo.OpenTextFile(FullFileName, ForAppending, True)
	    End if
	Set FileProperty = oFSo.GetFile(FullFileName)
				Logsize = FileProperty.size
	If Logsize > MaxSize Then
			Filehandle.WriteLine "\\\\\\\\\\File Size Reached//////////"
		Call Rollover()
	End If
End Sub
End Class

I built a scripting dictionary wrapper as well which was inspired by work from Dan Thomson in his health check script. I’ll most likely post it next after I feel it’s complete.

If you found this object helpful, or otherwise, I would appreciate it if you rated it on script center.

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 ******************************************************************************
'==================================================================================