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
  • 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?
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.
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.


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

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Join & Write a Comment

You may have already been in the need to update a whole folder stucture using a script. Robocopy does it well and even provides a list of non-updated files in a log (if asked to). Generally those files that were locked by a user or a process by the …
Introduction: Recently, I got a requirement to zip all files individually with batch file script in Windows OS. I don't know much about scripting, but I searched Google and found a lot of examples and websites to complete my task. Finally, I was ab…
In this video, we discuss why the need for additional vertical screen space has become more important in recent years, namely, due to the transition in the marketplace of 4x3 computer screens to 16x9 and 16x10 screens (so-called widescreen format). …
This Micro Tutorial will give you a introduction in two parts how to utilize Windows Live Movie Maker to its maximum editing capability. This will be demonstrated using Windows Live Movie Maker on Windows 7 operating system.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now