Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Script to query PC

Posted on 2014-09-22
Medium Priority
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 2000 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 $($PC.name)... ($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 $PC.name -count 1 -quiet){
			Write-Host "$($PC.Name) Online.  Please wait..." -foregroundcolor Green
			$BIOS = gwmi win32_bios -computer $PC.name
			$ComputerSystem = gwmi win32_ComputerSystem -computer $PC.Name
			$IP = gwmi -class Win32_NetworkAdapterConfiguration -computername $PC.name -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 $PC.name | ? { $_.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?
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

The recent Microsoft changes on update philosophy for Windows pre-10 and their impact on existing WSUS implementations.
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
This Micro Tutorial will go in depth within Systems and Security in Windows 7 and will go into detail regarding Action Center, Windows Firewall, System, etc. This will be demonstrated using Windows 7 operating system.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

580 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