Page 5 of 5 <12345
Topic Options
#208255 - 2014-01-03 05:59 PM Re: Asset Inventory to Access Database [Re: backfight]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4396
Loc: New Jersey
Well
 Code:
;for each $nic in Split(WMIQuery("ProductName","Win32_NetworkAdapter"),"|")
;if instr($nic,"miniport")=0 and instr($nic,"RAS")=0 and instr($nic,"Parallel")=0
;$NicCard = $nic
isn't complete - no Next or EndIf.

Put this in the data collection part:
 Code:
$aNICs = Split(WMIQuery("ProductName","Win32_NetworkAdapter"),"|")
Then, in the display / data write section, you use something like this:
 Code:
for each $nic In $aNICs
  ; ignore virtual and vpn adapters
  if instr($nic,"miniport")=0 and instr($nic,"RAS")=0 and instr($nic,"Parallel")=0
    'Found network adapter ' $nic ?
  EndIf
Next
This is untested, but should be pretty darn close.

Glenn

_________________________
Actually I am a Rocket Scientist! \:D

Top
#208262 - 2014-01-07 01:33 PM Re: Asset Inventory to Access Database [Re: matzas]
backfight Offline
Getting the hang of it

Registered: 2007-01-22
Posts: 61
Loc: Germany
Hi Glenn,
i get closer to my new prod. code :-) thanks for your support.

I Only have a few problems.

my code:
 Code:
;; KixGenerated: 2013/12/09 16:08:52 / Kix32 Version 4.62
; Hardware Inventory , OS Information & MS Key Inventory - Logon Script lists all Hardware & MS CD Keys per Client
; 
; Version 0.1 - Backfight - 09.12.2013
; UDFīs: UDF WMIQuery, UDF MEMORY, (DBLib.udf)
;
; Tasks:
; Identify Computer (@WKSTA)
;
; Query database
;  is this computer listed?
;    If so, was the last update more than 6 months ago?
;      If NOT, exit - nothing to do
;
; Need to perform an inventory
;
; Clear/Init the NEWDATA array
;
; Query for the following items and load the NEWDATA array with the results. 
; O/S Version
; Hardware Platform
; Installed Software  
;


; DESCRIPTION OF THE SCRIPT
;=======================================================================
; Collect all Hardware & OS Informationen from all WKST in the Domain to get a complete Inventory + all installed Microsoft Keys


Break On


; Declare variables
; ======================================================================

Dim $
DIM $CNstring				; Database variables
DIM $CMDtxt					; 
DIM $cmd					; 
DIM $rs						; 
DIM $cn						;
DIM $ModifyDateTime			; Return ModifyDateTime 
DIM $computername			; Workstation Name
DIM $username				; Username
DIM $osname					; OS Name
DIM $ServicePack			; SP
DIM $InstallDate			; Install Date
DIM $LastBoottime			; Last Boottime
DIM $OSSerial				; OS SN
DIM $SysManufacturer		; System Manufacturer
DIM $SysModel				; System Model
DIM $SysSerial				; System SN
DIM $CPUDescription			; CPU Description
DIM $CPUSpeed				; CPU Speed
DIM $SysMemory				; System RAM
DIM $VideoCard				; Video Card Name
DIM $VideoRes				; Video Resulution
DIM $NicCard				; Networkcard
DIM $nic					; NIC Var.
DIM $CDKey					; CDKeys (OS Key, MS Office, etc)
DIM $Privilegien			; User Privilegien
DIM $IP						; IP Adress
DIM $MAC					; Mac Hardware Adress
DIM $Uhrzeit				; Time
DIM $MonitorDescription		; Monitor Description
DIM $MonHersteller			; Monitor Manufactor
DIM $OSType					; Get OSType
DIM $wmiColl
DIM $wmiObj
DIM $DBpath
Dim $aProducts 			 	; array of product data in prod,Key format
DIM $Product				;
Dim $P   					; array pointer
DIM $Key					; CDKeys	
DIM $aData					;
DIM $aNICs					;NICS

Global $DEBUG				; Debug flag
Global $VERSION				; version string
;Global $MSG_LOG_, $ERR_LOG_		; log filenames - used by fMsg()


; Set program options
; ======================================================================
;$ = SetOption('Explicit', 'On')
;$ = SetOption('NoVarsInStrings', 'On')
$ = SetOption('NoMacrosInStrings', 'On')


; Define values
; ======================================================================
$DEBUG = 0
$VERSION = '1.0'

; CONFIGURE DATABASE PATH
; ======================================================================

$DBpath = "....\IT-Inventar.mdb"

CLS
AT (1,1) "Asset Audit Script Processing..."
SLEEP 2
CLS
BREAK ON CLS

; CONFIGURE DATABASE CONNECTION STRING
; ======================================================================
$CNstring="Driver={Microsoft Access Driver (*.mdb)}; DBQ=$DBpath"
$CMDtxt = "select * from COMPUTERS where computername = '@WKSTA'"
;'CNstring: ' $CNstring ?
;'  CMDtxt: ' $CMDtxt ?

If Not $DEBUG
  $cn = CreateObject ("ADODB.Connection")
  $cmd = CreateObject ("ADODB.Command")
  $rs = CreateObject ("ADODB.RecordSet")

  $cn.connectionstring = $CNstring
  $cn.Open
  $cmd.activeconnection = $cn
  $rs.cursortype = 3
  $rs.locktype = 3
  $rs.activecommand = $cmd

  $cmd.commandtext = $CMDtxt $rs.Open ($cmd)
EndIf

; MAIN Code
; ======================================================================



; COLLECT WORKSTAION ASSET INFORMATION
; ======================================================================
$MAC = @ADDRESS
$Uhrzeit = @time
$Privilegien = @PRIV
$IP = @IPADDRESS0
$ModifyDateTime = @DATE + " " + @TIME
$computername = @WKSTA
$username = @userid
$osname = WMIQuery("Caption","Win32_OperatingSystem")[0]
$OSType = WMIQuery("BuildType","Win32_OperatingSystem")[0]
$ServicePack = WMIQuery("CSDVersion","Win32_OperatingSystem")[0]
$InstallDate = WMIQuery("InstallDate","Win32_OperatingSystem")[0]
$LastBoottime = @date
$OSSerial = WMIQuery("SerialNumber","Win32_OperatingSystem")[0]
$SysManufacturer = WMIQuery("Manufacturer","Win32_ComputerSystem")[0]
$SysModel = WMIQuery("Model","Win32_ComputerSystem")[0]
$SysSerial = WMIQuery("SerialNumber","Win32_BIOS")[0]
$wmiColl = GetObject("WinMgmts:root/cimv2").ExecQuery("Select * FROM Win32_Processor ")
For Each $wmiObj in $wmiColl
  $CPUDescription = $wmiObj.Name	
Next
$CPUSpeed = WMIQuery("CurrentClockSpeed","Win32_Processor")[0]
$SysMemory = val(WMIQuery("TotalPhysicalMemory","Win32_LogicalMemoryConfiguration")[0])/1024
If $SysMemory = 0
  $SysMemory = Memory()
EndIf
$VideoCard = WMIQuery("Description","Win32_VideoController")[0]
$VideoRes = WMIQuery("VideoModeDescription","Win32_VideoController")[0]
$aNICs = Split(WMIQuery("ProductName","Win32_NetworkAdapter")[0],"|")
for each $nic In $aNICs
  ; ignore virtual and vpn adapters
  if instr($nic,"miniport")=0 and instr($nic,"RAS")=0 and instr($nic,"Parallel")=0
    $NicCard = $nic
  EndIf
Next
$wmiColl = GetObject("WinMgmts:root/cimv2").ExecQuery("Select * FROM Win32_DesktopMonitor")

For Each $wmiObj in $wmiColl
  $MonitorDescription = $wmiObj.Name
  $MonHersteller = $wmiObj.MonitorManufacturer
Next


; Get CD Key

$P = -1  ; pointer is "empty", since the first position is "0"

 Dim $RegArray, $RegView, $Value,$Array2,$guid
  $RegView=setoption("WOW64AlternateRegView","On")
  $RegArray = SearchReg("HKLM\Software\Microsoft","DigitalProductID",2)
  if @onwow64
    $Array2 = SearchReg("HKLM\Software\WOW6432NODE\Microsoft","DigitalProductID",2)
    $RegArray=ArrayAdd($RegArray,$Array2)
  endif
  If ubound($RegArray)<0
      ? 'No matching items found'
  Else
    For Each $Value In $RegArray
      If $Value
        $Product = ReadValue(Join(Split($value,'<=>DigitalProductId'),''),'ProductName')
        If $product=""
          $guid="{" + split(split($value,"{")[1],"}")[0] + "}"
          if instr($value,"WOW6432Node")
            $product=readvalue("HKLM\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + $guid,"DisplayName")
          else
            $product=readvalue("HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\" + $guid,"DisplayName")
          endif
        endif
        If $Product
          $Key = Get_Product_Key(ReadValue(Join(Split($value,'<=>DigitalProductId'),''), 'DigitalProductID'))
		  $P = $P + 1  ; increase array pointer
		  ReDim Preserve $aData[$P] ; increase the array, preserving prior contents
			$aData[$P] = $product + ': ' + $Key 
        EndIf
      EndIf
    Next
  EndIf
  $RegView=setoption("WOW64AlternateRegView",$RegView)
For each $aData[$P] in split (($aData[$P]),"|")
;	For Each $Key in $aData in split (($Key),"|")
;	Next

; ADD RECORDS TO THE DATABASE
; ======================================================================

If $DEBUG
 
  'MonHersteller: ' $MonHersteller ?
  'MonitorDescription: ' $MonitorDescription ?
  'IP: ' $IP ?
  'Uhrzeit: ' $Uhrzeit ?
  'MAC: ' $MAC ?
  'PRIVILEGIEN: ' $Privilegien ?
  'COMPUTERNAME: ' $computername ?
  'OSNAME: ' $osname ?
  'OSTYPE: ' $OSType ?
  'SERVICEPACK: ' $ServicePack ?
  'INSTALLDATE: ' $InstallDate ?
  'LASTBOOTTIME: ' $LastBoottime ?
  'OSSERIAL: ' $OSSerial ?
  'SYSMANUFACTURER: ' $SysManufacturer ?
  'SYSMODEL: ' $SysModel ?
  'SYSSERIAL: ' $SysSerial ?
  'CPUDESCRIPTION: ' $CPUDescription ?
  'CPUSPEED: ' $CPUSpeed ?
;  'SYSMEMORY: ' $SysMemory ?
  'VIDEOCARD: ' $VideoCard ?
  'VIDEORES: ' $VideoRes ?
;  'NICCARD: ' $NicCard ?
  'MODIFYDATETIME: ' $ModifyDateTime ?
  'USERNAME: ' $Username ?
;  'CDKey: ' $CDKey ?
	'CD Keys: ' ?
	For Each $Key in $aData
	$Key ?
	Next

Else

  If $rs.eof = -1 ; addnew is only needed if a record for this workstation was not found.
   $rs.addnew
  EndIf

 $rs.fields.item("MonHersteller").value = $MonHersteller
 $rs.fields.item("MonitorDescription").value = $MonitorDescription
 $rs.fields.item("IP").value = $IP
 $rs.fields.item("Uhrzeit").value = $Uhrzeit
 $rs.fields.item("MAC").value = $MAC
 $rs.fields.item("PRIVILEGIEN").value = $Privilegien
 $rs.fields.item("COMPUTERNAME").value = $computername
 $rs.fields.item("OSNAME").value = $osname
 $rs.fields.item("OSTYPE").value = $OSType
 $rs.fields.item("SERVICEPACK").value = $ServicePack
 $rs.fields.item("INSTALLDATE").value = $InstallDate
 $rs.fields.item("LASTBOOTTIME").value = $LastBoottime
 $rs.fields.item("OSSERIAL").value = $OSSerial
 $rs.fields.item("SYSMANUFACTURER").value = $SysManufacturer
 $rs.fields.item("SYSMODEL").value = $SysModel
 $rs.fields.item("SYSSERIAL").value = $SysSerial
 $rs.fields.item("CPUDESCRIPTION").value = $CPUDescription
 $rs.fields.item("CPUSPEED").value = $CPUSpeed
 $rs.fields.item("SYSMEMORY").value = $SysMemory
 $rs.fields.item("VIDEOCARD").value = $VideoCard
 $rs.fields.item("VIDEORES").value = $VideoRes
 $rs.fields.item("NICCARD").value = $NicCard
 $rs.fields.item("MODIFYDATETIME").value = $ModifyDateTime
 $rs.fields.item("USERNAME").value = $Username
 ;$rs.fields.item("CDKey").value = $CDKey
 $rs.fields.item("CDKey").value = $aData[$P]
 $rs.update
 $rs.Close

EndIf

Exit 0



; ======================================================================
; functions follow...
; ======================================================================



; UDF WMIQuery
; ======================================================================
;FUNCTION	WMIQuery
;
;ACTION		Queries WMI information from supported systems
;
;AUTHOR		Radimus
;
;CONTRIBUTORS	kdyer, Shawn, And Howard
;
;		gbarnas: altered EXECUTE function for NoVarsInStrings support
;                        Added support for pre-auth object
;			 
;
;VERSION	2.4.2
;
;DATE CREATED	12/22/2001
;
;DATE MODIFIED	04/02/2007 - GAB - added pre-authenticated object pointer support
;
;KIXTART	4.x
;
;SYNTAX		WMIQuery(what,from,[computer],[where],[where_arg],[objAuth])
;
;PARAMETERS	what
;            
;
;		from
;            	 - Win32 Collection
;
;		optional computer
;		 - defaults to local PC
;
;		optional where
;		 - addl parameter for a 'WHERE' clause. Used with $x
;
;		optional where_arg
;		 - addl parameter for a 'WHERE' clause. Used with $Where
;
;		optional objAuth
;		 - pre-authenticated token obtained from WMIAuthenticate
;
;RETURNS	Array 
;		@error 1 = Cannot create COM object on target PC
;
;REMARKS	9/2003 - This release alters the return from the function into an ARRAY, where previous versions
;		used a pipe '|' delimited string.  If you are updating to this version, check your code closely!
;		2/2004 - Added support for authentication
;
;DEPENDENCIES	kix 4.x+, WMI
;
;EXAMPLE	$make  = WMIQuery("Manufacturer","Win32_ComputerSystem")[0]
;		$modem = WMIQuery("Description","Win32_POTSModem",$remotePC,"Status","OK")[0]
;		for each $stick in WMIQuery("Capacity","Win32_PhysicalMemory")
;		  ? val($stick) / 1048576
;		next
;
;KIXTART BBS	http://www.kixtart.org/board/ultimatebb.php?ubb=get_topic;f=12;t=000117
;		http://download.microsoft.com/download/platformsdk/wmicore/1.5/W9XNT4/EN-US/wmicore.EXE 

Function WMIQuery($sWhat, $sFrom, Optional $sComputer, Optional $sWhere, Optional $x, Optional $root, Optional $pAuth)

  Dim $i, $sQuery, $objEnum, $sValue, $Tmp, $SystemSet, $objInstance 

  $sComputer = Trim(Join(Split($sComputer,'\'),''))

  If Not $sComputer Or $sComputer = @WKSTA
    $sComputer = '.'
  EndIf

  If Not $root
    $root = '\root\cimv2'
  Endif

  $sQuery = 'Select ' + $sWhat + ' From '+ $sFrom

  If $sWhere And $x
    $sQuery = $sQuery + " Where " + $sWhere + " = '" + $x + "'"
  EndIf

  If $pAuth
    $SystemSet = $pAuth
  Else
    $SystemSet = GetObject('winmgmts:{impersonationLevel=impersonate}!\\' + $sComputer + $root)
    If @ERROR Or Not $SystemSet
      Exit Val('&' + Right(DecToHex(@ERROR), 4))
    EndIf
  EndIf

  $objEnum = $SystemSet.ExecQuery($sQuery)
  If @ERROR Or Not $objEnum
    Exit Val("&" + Right(DecToHex(@ERROR), 4))
  EndIf

  For Each $objInstance in $objEnum
    $i = Execute(Chr(36) + 'sValue = ' + Chr(36) + 'objInstance.' + $sWhat)
    If VarType($sValue) & 8192
      $Tmp = $Tmp +'|' + Join($sValue,'|')
    Else
      $Tmp = $Tmp +'|' + $sValue 
    EndIf
  Next

  $WMIQuery = split(substr($Tmp,2),'|')
  Exit Val("&" + Right(DecToHex(@ERROR), 4))

EndFunction


; GET MS CD KEYS
; UDF from Allen. To be found under this link: http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=201729#Post201729
; ======================================================================

function Get_Product_Key($sproductid)
  Dim $aiKeyChars[24], $ilByte, $i, $iLOffset, $iUOffset, $bProductKey[15], $c, $nCur, $sCDKey
  For Each $c In Split("B C D F G H J K M P Q R T V W X Y 2 3 4 6 7 8 9")
    $aiKeyChars[$i]=Asc($c)
    $i=$i+1
  Next
  if len($sProductID)=2544
    $iLOffset=809
    $iUOffset=823
  else
    $iLOffset=53
    $iUOffset=67
  endif
  For $i = $iLOffset*2-1 To $iUOffset*2-1 Step 2
    $bProductKey[($i-($iLOffset*2-1))/2]=Execute("Exit &"+SubStr($sProductId,$i,2))
  Next
  For $ilByte = 24 To 0 Step -1
    $nCur = 0
    For $i=14 To 0 Step -1
      $nCur = $nCur * 256 ^ $bProductKey[$i] ; NOTE THE XOR! 
      $bProductKey[$i] = Int($nCur / 24)
      $nCur = $nCur Mod 24
    Next
    $sCDKey = Chr($aiKeyChars[$nCur]) + $sCDKey
    If $ilByte Mod 5 = 0 And $ilByte <> 0 $sCDKey = "-" + $sCDKey EndIf
  Next
  $Get_Product_Key=$sCDKey
EndFunction
 

Function SearchReg($Key,$Str,$SrcIn)
  Dim $Idx,$vName,$Value,$num,$SubKey,$fArr,$mbr
  $SearchReg = ''
  $num = 0
  $Idx = 0
  $vName = EnumValue($Key,$Idx)
  Do
    $mbr = ''
    If $SrcIn & 1
    $Value = ReadValue($Key,$vName)
     If InStr($Value,$Str)
       $mbr = $Key + "<=>" + IIf($vName,$vName,'<Default>')
     EndIf
    EndIf
    If ($SrcIn & 2) And InStr($vName,$Str)
      $mbr = $Key + "<=>" + $vName
    EndIf
    If $mbr
      ReDim Preserve $SearchReg[$num]
      $SearchReg[$num] = $mbr
      $num = $num + 1
    EndIf
    $Idx = $Idx + 1
    $vName = EnumValue($Key,$Idx)
  Until @Error
  $Idx = 0
  $SubKey = EnumKey($Key,$Idx)
  While $SubKey
    If ($SrcIn & 4) And InStr($SubKey,$Str)
      ReDim Preserve $SearchReg[$num]
      $SearchReg[$num] = $Key + '\' + $SubKey + "<=><KeyName>"
      $num = $num + 1
    EndIf
    $fArr = SearchReg($Key + "\" + $SubKey,$Str,$SrcIn)
    If @Error = 0
      For Each $mbr In $fArr
        ReDim Preserve $SearchReg[$num]
        $SearchReg[$num] = $mbr
        $num = $num + 1
      Next
    EndIf
    $Idx = $Idx + 1
    $SubKey = EnumKey($Key,$Idx)
  Loop

  Exit VarType($SearchReg) = 8
EndFunction
 

Function ArrayAdd($Array1, $Array2)
 ;Returns a new $Array1 
 Dim $n,$i
 $n = UBound($Array1) + 1
 REDIM PRESERVE $Array1[$n+UBound($Array2)]
 For $i = 0 to UBound($Array2)
   $Array1[$n+$i] = $Array2[$i]
 Next
 $ArrayAdd = $Array1
EndFunction


; UDF MEMORY
; ======================================================================
;;FUNCTION		Memory() 
;; 
;;AUTHOR		Glenn Barnas
;; 
;;ACTION		Returns the amount of Available Physical RAM in a local or remote system 
;; 
;;SYNTAX		Memory([system]) 
;; 
;;VERSION		4.0 
;; 
;;DATE			v1.0 - 2004/02/04
;; 
;;DATE REVISED		v2.0 - 2005/02/25 - updated to allow larger memory sizes (x86)
;;			v3.0 - 2007/10/05 - rewrite to support x64 systems, tighten code
;;			v4.0 - 2013/11/02 - rewrite to detect large memory blocks on post-Vista platforms
;; 
;;PARAMETERS		System - OPTIONAL - name of system to query. Default is local system
;;
;;REMARKS		Returns Physical RAM size available to the O/S using registry memory allocation map
;;			Returns @ERROR on registry read failure, or 13 / "Data is Invalid" if reg is empty
;;			DOES NOT return physical hardware ram value! Some systems allocate RAM to BIOS cache 
;;			or video adapters and this memory is not reported. This can be adjusted for using
;;			the second example below.
;; 
;;RETURNS		Integer - Available Physical RAM (in Megabytes) 
;; 
;;DEPENDENCIES		None 
;; 
;;TESTED WITH		WinXP, Vista, Win7, Win8
;;			Windows Server 2000, 2003, 2008, 2012
;;			Tested with up to 16G of RAM 
;; 
;;EXAMPLES		$RAM = Memory('ThatPC')		; Get the available RAM from a remote computer
;;			
;;			; Adjust for BIOS/Video ram to estimate total physical RAM by using the smallest
;;			; deployed DIMM module as an increment. Use "1024" for full GB increments.
;;			; If the GB flag is used, this method must be adjusted to define MSize in GB values
;;			; (e.g. 0.5 instead of 512). 
;;			$MSize = 512			; Size of smallest RAM module (DIMM)
;;			
;;			$Mem = Memory()			; get reported memory
;;			$Ma  = $Mem / $MSize		; determine number of modules installed
;;			
;;			; If a fractional module is detected, add another full module
;;			; this accounts for a fractional module used for BIOS cache or video RAM
;;			If $Mem Mod $MSize $Ma = $Ma + 1 EndIf
;;			
;;			; $Mem now holds a value based more closely on installer rather than available RAM
;;			$Mem = $Ma * $MSize		; Memory is #_modules * Mod_Size
;;			
;; 
;
Function Memory(Optional $_System, Optional $_fGB)

  Dim $_MemMap				; Physical Memory Map
  Dim $_Start, $_End, $_Step		; for/next start & step increment
  Dim $_Sum				; running sum of memory from map
  Dim $_Idx				; temporary index var
  Dim $_iMem				; Memory region size index
  Dim $_Error				; Error placeholder

  ; Insure $_System has "\\System\" format if it is specified 
  If $_System <> ''
    $_System = '\\' + Join(Split($_System, '\'), '', 3) + '\'
  EndIf

  ; Get the memory value from the registry 
  $_Idx = $_System + 'HKLM\hardware\resourcemap\system resources\physical memory'
  $_MemMap = ReadValue($_Idx, '.Translated')

  ; Check for invalid read and Return 
  If Len($_MemMap) = 0 Or @ERROR
    $Memory = 0				; return 0 Mbytes 
    $_Error = IIf(@ERROR, @ERROR, 13) 	; Return "Data is Invalid" if no error but data is blank 
    Exit $_Error
  EndIf

  ; determine system's O/S type based on architecture
  $_Idx = $_System + 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
  If ReadValue($_Idx, 'PROCESSOR_ARCHITECTURE') = 'AMD64'
    $_Step  = 40	; Define the step size based on the O/S Architecture
    $_Start = 33	; Offset where memory descriptor blocks start
    $_Sum   = 0.0	; no unreported base memory to account for
    $_iMem  = 10	; Memory size index
  Else
    $_Step  = 32	; Define the step size based on the O/S Architecture
    $_Start = 41	; Offset where memory descriptor blocks start
    $_Sum   = 737280.0	; account for base memory not identified in memory map - x86 only
    $_iMem  = 2		; Memory size index
  EndIf
  $_End = Len($_MemMap) - 8

  For $_Idx = $_Start to $_End Step $_Step
    $_Block = SubStr($_MemMap, $_Idx, $_Step)

    If SubStr($_Block, $_iMem, 1) > 3
      $_Sum = $_Sum + CDbl(Val('&' + SubStr($_Block, $_Step - 1, 2))) * 4294967296.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 3, 2))) * 16777216.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 5, 2))) * 65536.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 7, 2))) * 256.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 9, 2)))
    Else
      $_Sum = $_Sum + CDbl(Val('&' + SubStr($_Block, $_Step - 1, 2))) * 16777216.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 3, 2))) * 65536.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 5, 2))) * 256.0
                    + CDbl(Val('&' + SubStr($_Block, $_Step - 7, 2)))
    EndIf
  Next

  ; Sum is in Bytes - return the total as megabytes
  $Memory = CInt($_Sum / 1048576)
  Exit 0

EndFunction


1) i donīt understand why my script only works if i uncommented the following:
 Code:
;$ = SetOption('Explicit', 'On')
;$ = SetOption('NoVarsInStrings', 'On')


2) the next problem is that i donīt get the nic. The row in DB is empty.

3) i donīt get the trick to get cd keys in one row in db but split with "|". Here are my testings
 Code:
For each $aData[$P] in split (($aData[$P]),"|")
Next

 Code:
For Each $Key in $aData in split (($Key),"|")
Next


backfight

Top
#208265 - 2014-01-07 04:15 PM Re: Asset Inventory to Access Database [Re: backfight]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4396
Loc: New Jersey
1. If you are using KGen, it should report every variable that has not been declared. Look at the .RPT file that is created in the same folder where you built your script. It contains all the warnings. Post it if you need clarification of the contents.

2. This was explained above. The data query replaces the "|" delimited string with an array - you don't need to do this again. The code example provided for the display/data write can be used as-is for display and modified to write $Nic to the DB in the DB Write section. If you want a simple DB write logic, forget the For/Next and simply write a comma-delimited string to the DB record with Join($aData, ','). Put that in the command to write to the database as the Value.

3. I don't understand how you got
 Code:
For each $aData[$P] in split (($aData[$P]),"|")
Next
out of the example I posted:
 Code:
'CD Keys: ' ?
For Each $Key in $aData
  $Key ?
Next
Your code isn't valid. If you are doing a "For Each", you need two variables. One is the array of data and the other is the variable used to enumerate the array. You can't use the same var for both. For example:
 Code:
$Array = GetArray() ; function returns an array of values
For Each $Value in $Array  ; walk the array, assigning each element to "$Value" one at a time
  $Value ? ; do something with the value
Next
What you put in the For Each/Next loop will depend on your requirement. You might use this TWICE in your code, once in the debug section that displays the values, and again in the section that writes the data to the DB.

..................

I'll be honest and tell you you're falling into one of the most common development problems that young coders make - you're trying to work on a large project all at once.

When something doesn't work and can't be fixed in a few minutes, create a test script and include just what's needed for the part giving you grief - var declarations & initializations, data collection, and the data processing. So, for your NIC and CDKey issues, create two small scripts, one for each process. The code should init the vars you use, call the function to get the NIC or CDKey data, and then enumerate the results to display the values. This lets you focus on JUST what is needed for this to work with no other distractions. Then you can move the working code from the small scripts into the larger script.

In fact, this is where KGen excels..
Create Project.TXT and use it only to define the variables
Create a DataCollect.UDF file, and define ONE data collection set of function calls, maybe some WMI values.
Create a DataDisplay.UDF file, and in an If $DEBUG / EndIf block, display the value(s)collected above.
Create a DatabaseWrite.UDF file, and in an If Not $DEBUG / EndIf block, write the value(s) to the database.

Run KGen to combine these 4 files and all the required external functions. Verify that the data collection, display, and DB-Write functions work. Having a small number of similar data elements to work with will make debugging easier.

When this is working, and you've worked out any display and DB-Write issues, update the 3 UDF files to add another collect/display/write block. Focus on getting this to work, then repeat as necessary until all of the data is working. Not only does this help focus on developing specific blocks, it keeps the blocks in sequence in the collect, display, and DB-Write sections. This makes further debugging much easier.

I use KGen in this manner for all my larger projects. I actually have broken one project into many separate files:
- project.txt - the var init code
- Coll_01_xxx.UDF to Coll_07_xxx.UDF - separate files for each set of data collections
- Proc_01_xxx.UDF to Proc_07_xxx.UDF - separate files for each set of data processing
- ZZ_CommonFuncs.UDF - a set of project specific functions
KGen assembles these in alphabetical order, so I name them so all data collections come first, then all the data processing, followed by common functions and then public library functions. the "xxx" is a short description of the data being collected or processed.

Also, you would not believe the number of small script segments I have in the "Misc" folder of my dev library that have been created to test/validate the logic of some process. I keep them because I often revisit the logic for future projects, or when I find a potentially better way to do something. It's kind of like the "morgue" that artists use, just for code snippets. ;\)

Glenn
_________________________
Actually I am a Rocket Scientist! \:D

Top
#208289 - 2014-01-11 06:33 PM Re: Asset Inventory to Access Database [Re: Glenn Barnas]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4396
Loc: New Jersey
Please see the Script Vault post related to PC Inventory for a working example of PC Inventory processing. That post will collect a large amount of data and display it, and has examples of how to write the data to a SQL database. The SQL part of the script must be completed by the user, as it is up to the user as to which data elements are of interest and the type and structure of the database chosen.

A fully operational inventory system can be constructed in just a few hours by completing the database code portion.

Glenn
_________________________
Actually I am a Rocket Scientist! \:D

Top
#208541 - 2014-02-07 05:24 AM Re: Asset Inventory to Access Database [Re: Glenn Barnas]
AGorman Offline
Fresh Scripter

Registered: 2000-10-04
Posts: 7
Loc: Columbus, MS USA
Really impressed with the PC Inventory script. The problem I'm having is with the WMISysInfo function. Works great on my pc with WMISysInfo(). If I try WMISysInfo($sComputer) I get "Error: unexpected command!" on whatever the next line is. I used WMIAuthentication to get credentials and tried WMISysInfo(@Host,$WMIAuth) but still got same error for the next line. If I just run WMISysInfo() it runs great. Any ideas what I'm doing wrong? I have made no changes to WMISysInfo but just in case I removed it from my script and re-copied it but still won't work. Created another script with just the WMI Authentication function and the WMISysInfo function

$Host = 'PANASONIC-PC'
$WMIAuth = WMIAuthentication($Host,'user','password')
$Up = WMISysInfo($Host,$WMIAuth)
? $Up[0]

Still no go.

Top
#208544 - 2014-02-07 01:13 PM Re: Asset Inventory to Access Database [Re: AGorman]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4396
Loc: New Jersey
Hmm.. I haven't used the WMISysInfo remotely since developing our helpdesk app a while ago. Let me look into this today and I'll post the updates. Thanks for the heads-up, and nice to see an attempt at centralized collection!

Glenn
_________________________
Actually I am a Rocket Scientist! \:D

Top
Page 5 of 5 <12345


Moderator:  Glenn Barnas, NTDOC, Arend_, Jochen, Radimus, Allen, ShaneEP, Ruud van Velsen, Mart 
Hop to:
Shout Box

Who's Online
2 registered (morganw, mole) and 414 anonymous users online.
Newest Members
gespanntleuchten, DaveatAdvanced, Paulo_Alves, UsTaaa, xxJJxx
17864 Registered Users

Generated in 0.056 seconds in which 0.026 seconds were spent on a total of 13 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org