Script to query PC

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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

akalyan911Technical ConsultantCommented:
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..
Dale HarrisProfessional Services EngineerCommented:
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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
WellingtonISAuthor Commented:
can this be modified to print to a csv?
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Gabriel CliftonNet AdminCommented:
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

WellingtonISAuthor Commented:
I don't think I have the quest tools installed.
WellingtonISAuthor Commented:
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
WellingtonISAuthor Commented:
Just installed the quest tools.  Running now...
Dale HarrisProfessional Services EngineerCommented:
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.
WellingtonISAuthor Commented:
I'm just running.  What's the file name going to be??? Or will it just pop when it ends?
Dale HarrisProfessional Services EngineerCommented:
The file outputted is computerinfo.txt.  It will fill up as it's running so you can check on the data it's getting.
Dale HarrisProfessional Services EngineerCommented:
You can add the command
 notepad .\computerinfo.txt 

Open in new window

if you want it to open it up.
Gabriel CliftonNet AdminCommented:
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

WellingtonISAuthor Commented:
This worked great! Thanks.  To bad it's not a csv so I can seperate it out. But thanks!
Dale HarrisProfessional Services EngineerCommented:
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.
WellingtonISAuthor Commented:
I did it's just a mess but I got the info  which is most important!  thanks again for your help.
Dale HarrisProfessional Services EngineerCommented:
You're welcome.  I'm glad I could help!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.