Script to query PC

Posted on 2014-09-22
Last Modified: 2014-09-23
I need a script to query Computer names, Model Numbers and OS info.  I have WMIC but I was hoping for something that doesn't time out as much? Actually I can query WMIC for the compuer names and Models but not the OS. And WMIC gives a lot of RPC errors too.
Question by:WellingtonIS
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 2
  • +1

Expert Comment

ID: 40336857
Hi WellingtonIS,
No way to do this with the command line utilities dsget and dsquery. A VBScript solution follows:
Option Explicit

Dim adoCommand, adoConnection, strBase, strFilter, strAttributes
Dim objRootDSE, strDNSDomain, strQuery, adoRecordset
Dim dtmDate, lngSeconds, str64Bit, strDN, strOS
Dim objShell, lngBiasKey, lngBias, k, intDays

' Specify number of days. If the computer password has not been changed
' in this number of days, the account is considered stale.
intDays = 180

' Determine date the specified number of days in the past.
' would just now be expired.
dtmDate = DateAdd("d", - intDays, Now())

' Retrieve DNS name of the domain.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")

' Obtain local Time Zone bias from machine registry.
' This bias changes with Daylight Savings Time.
Set objShell = CreateObject("Wscript.Shell")
lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\" _
  & "TimeZoneInformation\ActiveTimeBias")
If (UCase(TypeName(lngBiasKey)) = "LONG") Then
  lngBias = lngBiasKey
ElseIf (UCase(TypeName(lngBiasKey)) = "VARIANT()") Then
  lngBias = 0
  For k = 0 To UBound(lngBiasKey)
    lngBias = lngBias + (lngBiasKey(k) * 256^k)
End If

' Convert the datetime value to UTC.
dtmDate = DateAdd("n", lngBias, dtmDate)

' Find number of seconds since 1/1/1601 for this date.
lngSeconds = DateDiff("s", #1/1/1601#, dtmDate)

' Convert the number of seconds to a string
' and convert to 100-nanosecond intervals.
str64Bit = CStr(lngSeconds) & "0000000"

' Setup ADO objects.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection

' Search entire Active Directory domain.
strBase = "<LDAP://" & strDNSDomain & ">"

' Filter on computer objects where the password has not been changed
' in the specified number of days and the account is not disabled.
strFilter = "(&(objectCategory=computer)" _
  & "(pwdLastSet<=" & str64Bit & ")" _
  & "(!userAccountControl:1.2.840.113556.1.4.803:=2))"

' Comma delimited list of attribute values to retrieve.
strAttributes = "distinguishedName,operatingSystem"

' Construct the LDAP syntax query.
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 200
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False

' Run the query.
Set adoRecordset = adoCommand.Execute

' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
  ' Retrieve values and display in comma delimited format.
  strDN = adoRecordset.Fields("distinguishedName").Value
  strOS = adoRecordset.Fields("operatingSystem").Value
  Wscript.Echo """" & strDN & """,""" & strOS & """"
  ' Move to the next record in the recordset.

' Clean up.
Similar can be done in PowerShell.

Try this, may it works..
LVL 16

Accepted Solution

Dale Harris earned 500 total points
ID: 40336890
Here's a PowerShell version we use that gives you a lot of info.  You can slice it up how you like it since the variables are pretty easy to understand:

#You must have Quest AD Tools installed
Add-PSSnapin "*Quest*"

$List = gc .\list.txt
"PCName;SN;Description;Network;IP;Location;Manufacturer;Model;ManagedBy;OS;OU;MAC;User" > Computerinfo.txt
$Total = $List.count
$i = 0
foreach ($Computer in $List){
$PC = Get-QADComputer "*$Computer*"
"Searching for $($ ($i of $Total)"
	if ($PC -eq $null){
		#The computer is not in AD, so skip it
		Write-Host "$Computer match not found in AD" -foregroundcolor Yellow
		#Part of the info needs the host to be online, the other info is in AD
		if (Test-Connection $ -count 1 -quiet){
			Write-Host "$($PC.Name) Online.  Please wait..." -foregroundcolor Green
			$BIOS = gwmi win32_bios -computer $
			$ComputerSystem = gwmi win32_ComputerSystem -computer $PC.Name
			$IP = gwmi -class Win32_NetworkAdapterConfiguration -computername $ -filter 'IPEnabled="True"' | select -expand IPAddress | ?{$_ -notlike "169*"} 
			$Location = $IP.split(".")[2]
			$Manufacturer = $BIOS.manufacturer
			$Model = $ComputerSystem.model.trim()
			$SN= $BIOS.serialnumber
			$MAC = (gwmi -Class Win32_NetworkAdapterConfiguration -Computername $ | ? { $_.IpAddress -eq $IP }).MACAddress
			$User = $ComputerSystem.username
			#Put null values for each item above
			Write-host "$($PC.Name) is offline." -foregroundcolor Red
			$BIOS = ""
			$ComputerSystem = ""
			$IP = ""
			$Location = ""
			$Manufacturer = ""
			$Model = ""
			$SN = ""
			$MAC = ""
			$User = ""
		}#end if
		$Description = $PC.Description
		$Network = "NIPR"
		$Managedby = $PC.ManagedBy
		$OS = $PC.OSName
		$OU = ($PC.dn.split(",")[2]).split("=")[1]
		#Output all into a text file called ComputerInfo.txt
		"$PCName;$SN;$Description;$Network;$IP;$Location;$Manufacturer;$Model;$ManagedBy;$OS;$OU;$MAC;$User" >> Computerinfo.txt
	}#end if
}#end for loop

Open in new window


Author Comment

ID: 40336891
can this be modified to print to a csv?
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

LVL 13

Expert Comment

by:Gabriel Clifton
ID: 40336892
I know you prefer no WMIC but,
for /f "skip=1 delims=^|" %a in ('wmic os get Name') do echo %a

Open in new window


Author Comment

ID: 40336900
I don't think I have the quest tools installed.

Author Comment

ID: 40336916
For /f...  I need a list of PCs?  and wmic os get name is only going to give me the OS name I need the PC name and model number too

Author Comment

ID: 40336975
Just installed the quest tools.  Running now...
LVL 16

Expert Comment

by:Dale Harris
ID: 40336990
It outputs everything into the same directory as you run the script from.  All you have to do is open excel and click the Data tab.  Then click From Text and separate by semicolon (;) when using the wizard.  The headings will also be useful for you.

Author Comment

ID: 40337003
I'm just running.  What's the file name going to be??? Or will it just pop when it ends?
LVL 16

Expert Comment

by:Dale Harris
ID: 40337022
The file outputted is computerinfo.txt.  It will fill up as it's running so you can check on the data it's getting.
LVL 16

Expert Comment

by:Dale Harris
ID: 40337026
You can add the command
 notepad .\computerinfo.txt 

Open in new window

if you want it to open it up.
LVL 13

Expert Comment

by:Gabriel Clifton
ID: 40337032
I was just giving a point in the script. This is crude but:
@echo off

for /f %%s in ('dsquery computer "OU=ComputerOU,DC=Domain,DC=COM" -limit 0 -o rdn ^|sort') do call :sysinfo %%s

set sysname=%1
set sysname=%sysname:"=%
echo %sysname% >>sysinfo.csv
for /f "skip=1 delims=^|" %%a in ('wmic /node:%sysname% os get Name') do echo %%a >>sysinfo.csv
wmic /node:%sysname% computersystem get model >>sysinfo.csv
echo. >>sysinfo.csv

goto :eof

Open in new window


Author Closing Comment

ID: 40337393
This worked great! Thanks.  To bad it's not a csv so I can seperate it out. But thanks!
LVL 16

Expert Comment

by:Dale Harris
ID: 40338471
You can easily separate it out in excel using the "Data" tab, and selecting "From Text".  When it takes you through the wizard, ensure you're separating by semicolon and each column will have it's own data.

I'm glad it worked for you!  You could use the Export-CSV option, but I prefer using text files and importing into Excel.

Author Comment

ID: 40338930
I did it's just a mess but I got the info  which is most important!  thanks again for your help.
LVL 16

Expert Comment

by:Dale Harris
ID: 40338938
You're welcome.  I'm glad I could help!

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

While working, an annoying popup showing below will come and we cannot cancel or close it form the screen. The error message will come again and again.
On some Windows 7 (SP1) computers, Windows Update becomes super slow even the computer is reasonably fast.  There's one solution that seemed to have worked well for me (after trying a few other suggested solutions).
This Micro Tutorial will teach you how to the overview of Microsoft Security Essentials. This is a free anti-virus software that guards your PC against viruses, spyware, worms, and other malicious software. This will be demonstrated using Windows…
This Micro Tutorial will give you a introduction in two parts how to utilize Windows Live Movie Maker to its maximum capability. This will be demonstrated using Windows Live Movie Maker on Windows 7 operating system.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question