Sign in to follow this  
Followers 0
jefhal

PowerShell to get computer properties

14 posts in this topic

These examples are working. However, my end goal is to show a freespace to disk size ratio. To do that I'd like to have PowerShell do the parsing of the individual values rather than using AutoIT to sort through the output afterwards. My problem is how to get PowerShell to spit out the values one at a time to AutoIT...

Dim $pid, $pid2, $ourOutput, $strComputer
     $strComputer = "myComputerName"
; Open with connections to STDIN and STDOUT
     $pid = Run("powershell.exe Get-WmiObject -computer " & $strComputer & " win32_SystemEnclosure | select serialnumber", @SystemDir, @SW_HIDE, 3)
     StdinWrite($pid, @CRLF)
; Call with no string param to close STDIN
     StdinWrite($pid)
     
     While 1
         $ourOutput &= StdoutRead($pid)
         If @error Then ExitLoop
     WEnd
         
     MsgBox(0, "", $ourOutput)
     $pid = ""
     $ourOutput = ""

; Open with connections to STDIN and STDOUT
     $pid2 = Run("powershell.exe get-wmiobject -computer " & $strComputer & " -class win32_logicaldisk | where-object {$_.drivetype -match 3} ", @SystemDir, @SW_HIDE, 3)
     StdinWrite($pid2, @CRLF)
; Call with no string param to close STDIN
     StdinWrite($pid2)
     
     While 1
         $ourOutput &= StdoutRead($pid2)
         If @error Then ExitLoop
     WEnd
         
     MsgBox(0, "", $ourOutput)

...by the way, it's pronounced: "JIF"... Bob Berry --- inventor of the GIF format

Share this post


Link to post
Share on other sites



maybe i'm stupid

but why using powershell to make things easier to do with autoit

ok, you have to learn WQL, but it will be easy after

search on the forum for WMI example uing the com objects, or tell me what it the purpose of the script, and i think i can do it entirely in autoit


-- Arck System _ Soon -- Ideas make everything

"La critique est facile, l'art est difficile"

Projects :

[list] [*]Au3Service : Run your exe as service V3 / Updated 29/07/2013 Get it Here [/list]

Share this post


Link to post
Share on other sites

where can i find powershell ??


-jaenster

Share this post


Link to post
Share on other sites

where can i find powershell ??

Just click here:

SUPERTURTLE


...by the way, it's pronounced: "JIF"... Bob Berry --- inventor of the GIF format

Share this post


Link to post
Share on other sites

maybe i'm stupid

but why using powershell to make things easier to do with autoit

ok, you have to learn WQL, but it will be easy after

search on the forum for WMI example uing the com objects, or tell me what it the purpose of the script, and i think i can do it entirely in autoit

Powershell just seems a bit simpler than WMI code to achieve the same result. I also like that it will let me do active directory functions using a similar syntax, rather than having to learn wmi and adsi, etc. I still use AutoIT for the glue to hold it all together, however.

I don't know of a direct AutoIT command, yet, that will let me, for example, get the Dell Service Tag of a computer, or query a remote machine to find the diskspace and freespace on all hard drives at one time....


...by the way, it's pronounced: "JIF"... Bob Berry --- inventor of the GIF format

Share this post


Link to post
Share on other sites

New to all of this. But is there a way to take the output of your script and have it put into another batch file?

What I need to do is automate the computer naming process on our newly ghosted systems. Our naming convention is a "D" (for Dell) and the service tag. Like "D51VCG31". So it would be nice if I could use this script to read the service tag from the system at first boot, then change the computer name to D+servicetag. I have a script that allows me to change the name and reboot, but I need to specify the name first so unless there is a way to make the output from the first script enter into into the second, I would need to find a way to combine the two.

Any ideas?

Share this post


Link to post
Share on other sites

@TBOMB

Can you show the script and maybe we can help ?!

Regards

ptrex

Sure. It uses WMI and windows scripting to change the name and I know that there is a way to also get the Dell service tag using WMI as well, so I guess I need to have something that pulls the service tag, adds a "D" in front and plugs it in as a variable for the following script to use as the new name.

Anyway, not my script, it was one included in a scripting book I bought.

<?xml version="1.0" ?>

<package>

<job id="ChangeComputerName" prompt="no">

<?job error="false" debug="false" ?>

<runtime>

<description>

Change the computer name of the specified computer.

</description>

<named helpstring="Run command against single specified computer" name="computer" required="true" type="string"/>

<named helpstring="Display detailed messages" name="verbose" required="false" type="simple"/>

<named helpstring="File to log names which can't be reached" name="log" required="false" type="string"/>

<named helpstring="Reduce timeout wait by pinging before attempting" name="ping" required="false" type="simple"/>

<named helpstring="New computer name" name="name" required="true" type="string"/>

</runtime>

<object id="fso" progid="Scripting.FileSystemObject"/>

&lt;script id="MultiComputer" language="VBScript">

<![CDATA[

'----------------------------------------------------------

' Rollback System Restore Point

'----------------------------------------------------------

'make sure we're running from CScript, not WScript

If LCase(Right(WScript.FullName,11)) <> "cscript.exe" Then

If MsgBox("This script is designed to work with CScript, but you are running it under WScript. " & _

"This script may produce a large number of dialog boxes when running under WScript, which you may " & _

"find to be inefficient. Do you want to continue anyway?",4+256+32,"Script host warning") = 7 Then

WScript.Echo "Tip: Run ""Cscript //h:cscript"" from a command-line to make CScript the default scripting host."

WScript.Quit

End If

End If

'if ping requested, make sure we're on XP or later

Dim bPingAvailable, oLocalWMI, cWindows, oWindows

bPingAvailable = False

Set oLocalWMI = GetObject("winmgmts:\\.\root\cimv2")

Set cWindows = oLocalWMI.ExecQuery("Select BuildNumber from Win32_OperatingSystem",,48)

For Each oWindows In cWindows

If oWindows.BuildNumber >= 2600 Then

bPingAvailable = True

End If

Next

Share this post


Link to post
Share on other sites

Sorry, cut off most of the code, here's what comes after:

'check for required paramaters

If Not WScript.Arguments.Named.Exists("computer") Or Not WScript.Arguments.Named.Exists("name") Then

WScript.Arguments.ShowUsage

WScript.Quit

End If

'was ping requested?

If WScript.Arguments.Named.Exists("ping") Then

If bPingAvailable Then

Verbose "will attempt to ping all connections to improve performance"

Else

WScript.Echo "*** /ping not supported prior to Windows XP"

End If

End if

'either /list, /computer, or /container was specified:

Dim sName

If WScript.Arguments.Named("list") <> "" Then

'specified list - read names from file

Dim oFSO, oTS

Verbose "Reading names from file " & WScript.Arguments.Named("list")

Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")

On Error Resume Next

Set oTS = oFSO.OpenTextFile(WScript.Arguments.Named("list"))

If Err <> 0 Then

WScript.Echo "Error opening " & WScript.Arguments.Named("list")

WScript.Echo Err.Description

WScript.Quit

End If

Do Until oTS.AtEndOfStream

sName = oTS.ReadLine

TakeAction sName

Loop

oTS.Close

Elseif WScript.Arguments.Named("container") <> "" Then

'specified container - read names from AD

Dim oObject, oRoot, oChild

Verbose "Reading names from AD container " & WScript.Arguments.Named("container")

On Error Resume Next

Set oRoot = GetObject("LDAP://rootDSE")

If Err <> 0 Then

WScript.Echo "Error connecting to default Active Directory domain"

WScript.Echo Err.Description

WScript.Quit

End If

Set oObject = GetObject("LDAP://ou=" & WScript.Arguments.Named("container") & _

"," & oRoot.Get("defaultNamingContext"))

If Err <> 0 Then

WScript.Echo "Error opening organizational unit " & WScript.Arguments.Named("container")

WScript.Echo Err.Description

WScript.Quit

End If

WorkWithOU oObject

Elseif WScript.Arguments.Named("computer") <> "" Then

'specified single computer

Verbose "Running command against " & WScript.Arguments.Named("computer")

TakeAction WScript.Arguments.Named("computer")

End If

'display output so user will know script finished

WScript.Echo "Command completed."

' ----------------------------------------------------------------------

' Sub WorkWithOU

'

' Iterates child objects in OU; calls itself to handle sub-OUs If

' /recurse argument supplied

' ----------------------------------------------------------------------

Sub WorkWithOU(oObject)

For Each oChild In oObject

Select Case oChild.Class

Case "computer"

TakeAction Right(oChild.Name,len(oChild.name)-3)

Case "user"

Case "organizationalUnit"

If WScript.Arguments.Named.Exists("recurse") Then

'recursing sub-OU

Verbose "Working In " & oChild.Name

WorkWithOU oChild

End If

End Select

Next

End Sub

' ----------------------------------------------------------------------

' Sub TakeAction

'

' Makes connection and performs command-specific code

' ----------------------------------------------------------------------

Sub TakeAction(sName)

'verbose output?

Verbose "Connecting to " & sName

'ping before connecting?

If WScript.Arguments.Named.Exists("ping") Then

If Not TestPing(sName,bPingAvailable) Then

LogBadConnect(sName)

Exit Sub

End If

End If

'#############################################

'# COMMAND CODE GOES HERE #

'#-------------------------------------------#

'# #

Dim oWMIService, cComputers, oComputer, ErrResults

On Error Resume Next

Verbose " Attempting to connect to " & sName

Set cComputers = QueryWMI(sName,"root\cimv2","Select * From Win32_ComputerSystem","","")

If Not IsObject(cComputers) Then

WScript.Echo " *** Error connecting to " & sName

Else

For Each oComputer In cComputers

If WScript.Arguments.Named.Exists("ping") Then

If TestPing(WScript.Arguments.Named("name"),bPingAvailable) Then

WScript.Echo " *** " & WScript.Arguments.Named("name") & " already responds to ping"

Exit sub

End if

End if

Verbose " Renaming " & sName & " to " & WScript.Arguments.Named("name")

ErrResults = oComputer.Rename(WScript.Arguments.Named("name"),Null,Null)

If ErrResults <> 0 Then

WScript.Echo " *** Error renaming: " & ErrResults

Else

Verbose "Rename successful. Restart of remote computer is necessary."

End If

Next

End If

'# #

'#-------------------------------------------#

'# END COMMAND CODE #

'#############################################

End Sub

' ----------------------------------------------------------------------

' Sub LogBadConnect

'

' Logs failed connections to a log file. Will append if file already exists.

' ----------------------------------------------------------------------

Sub LogBadConnect(sName)

If WScript.arguments.Named.Exists("log") Then

Dim oLogFSO, oLogFile

Set oLogFSO = WScript.CreateObject("Scripting.FileSystemObject")

On Error Resume Next

Set oLogFile = oLogFSO.OpenTextFile(WScript.Arguments.Named("log"),8,True)

If Err <> 0 Then

WScript.Echo " *** Error opening log file to log an unreachable computer"

WScript.Echo " " & Err.Description

Else

oLogFile.WriteLine sName

oLogFile.Close

Verbose " Logging " & sName & " as unreachable"

End If

End If

End Sub

' ----------------------------------------------------------------------

' Function TestPing

'

' Tests connectivity to a given name or address; returns true or False

' ----------------------------------------------------------------------

Function TestPing(sName,bPingAvailable)

If Not bPingAvailable Then

WScript.Echo " Ping functionality not available prior to Windows XP"

Exit Function

End If

Dim cPingResults, oPingResult

Verbose " Pinging " & sName

Set cPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery("SELECT * FROM Win32_PingStatus WHERE Address = '" & sName & "'")

For Each oPingResult In cPingResults

If oPingResult.StatusCode = 0 Then

TestPing = True

Verbose " Success"

Else

TestPing = False

Verbose " *** FAILED"

End If

Next

End Function

' ----------------------------------------------------------------------

' Sub Verbose

'

' Outputs status messages if /verbose argument supplied

' ----------------------------------------------------------------------

Sub Verbose(sMessage)

If WScript.Arguments.Named.Exists("verbose") Then

WScript.Echo sMessage

End If

End Sub

' ----------------------------------------------------------------------

' Sub LogFile

'

' Outputs specified text to specified logfile. Set Overwrite=True To

' overwrite existing file, otherwise file will be appended to.

' Each call to this sub is a fresh look at the file, so don't Set

' Overwrite=True except at the beginning of your script.

' ----------------------------------------------------------------------

Sub LogFile(sFile,sText,bOverwrite)

Dim oFSOOut,oTSOUt,iFlag

If bOverwrite Then

iFlag = 2

Else

iFlag = 8

End If

Set oFSOOut = WScript.CreateObject("Scripting.FileSystemObject")

On Error Resume Next

Set oTSOUt = oFSOOut.OpenTextFile(sFile,iFlag,True)

If Err <> 0 Then

WScript.Echo "*** Error logging to " & sFile

WScript.Echo " " & Err.Description

Else

oTSOUt.WriteLine sText

oTSOUt.Close

End If

End Sub

' ----------------------------------------------------------------------

' Function QueryWMI

'

' Executes WMI query and returns results. User and Password may be

' passed as empty strings to use current credentials; pass just a blank

' username to prompt for the password

' ----------------------------------------------------------------------

Function QueryWMI(sName,sNamespace,sQuery,sUser,sPassword)

Dim oWMILocator, oWMIService, cInstances

On Error Resume Next

'create locator

Set oWMILocator = CreateObject("WbemScripting.SWbemLocator")

If sUser = "" Then

'no user - connect w/current credentials

Set oWMIService = oWMILocator.ConnectServer(sName,sNamespace)

If Err <> 0 Then

WScript.Echo "*** Error connecting to WMI on " & sName

WScript.Echo " " & Err.Description

Set QueryWMI = Nothing

Exit Function

End If

Else

'user specified

If sUser <> "" And sPassword = "" Then

'no password - need to prompt for password

If LCase(Right(WScript.FullName,11)) = "cscript.exe" Then

'cscript - attempt to use ScriptPW.Password object

Dim oPassword

Set oPassword = WScript.CreateObject("ScriptPW.Password")

If Err <> 0 Then

WScript.Echo " *** Cannot prompt for password prior to Windows XP"

WScript.Echo " Either ScriptPW.Password object not present on system, Or"

WScript.Echo " " & Err.Description

WScript.Echo " Will try to proceed with blank password"

Else

WScript.Echo "Enter password for user '" & sUser & "' on '" & sName & "'."

sPassword = oPassword.GetPassword()

End If

Else

'wscript - prompt with InputBox()

sPassword = InputBox("Enter password for user '" & sUser & "' on '" & sName & "'." & vbcrlf & vbcrlf & _

"WARNING: Password will echo to the screen. Run command with CScript to avoid this.")

End if

End If

'try to connect using credentials provided

Set oWMIService = oWMILocator.ConnectServer(sName,sNamespace,sUser,sPassword)

If Err <> 0 Then

WScript.Echo " *** Error connecting to WMI on " & sName

WScript.Echo " " & Err.Description

Set QueryWMI = Nothing

Exit Function

End If

End If

'execute query

If sQuery <> "" Then

Set cInstances = oWMIService.ExecQuery(sQuery,,48)

If Err <> 0 Then

WScript.Echo "*** Error executing query "

WScript.Echo " " & sQuery

WScript.Echo " " & Err.Description

Set QueryWMI = Nothing

Exit Function

Else

Set QueryWMI = cInstances

End If

Else

Set QueryWMI = oWMIService

End If

End Function

' ----------------------------------------------------------------------

' Function QueryADSI

'

' Executes ADSI query. Expects variable sQuery to include a COMPLETE

' query beginning with the provider LDAP:// or WinNT://. The query String

' may include a placeholder for the computer name, such as "%computer%".

' Include the placeholder in variable sPlaceholder to have it replaced

' with the current computer name. E.g.,

' sQuery = "WinNT://%computer%/Administrator,user"

' sPlaceholder = "%computer%

' Will query each computer targeted by the script and query their local

' Administrator user accounts.

' ----------------------------------------------------------------------

Function QueryADSI(sName,sQuery,sPlaceholder)

Dim oObject

sQuery = Replace(sQuery,sPlaceholder,sName)

On Error Resume Next

Verbose " Querying " & sQuery

Set oObject = GetObject(sQuery)

If Err <> 0 Then

WScript.Echo " *** Error executing ADSI query"

WScript.Echo " " & sQuery

WScript.Echo " " & Err.Description

Set QueryADSI = Nothing

Else

Set QueryADSI = oObject

End If

End Function

]]>

</script>

</job>

Share this post


Link to post
Share on other sites

@TBOMB

This is indead a looooong script !!

Maybe this can get you started :

$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$strComputer = "localhost"

$Output=""
$Output = $Output & "Computer: " & $strComputer  & @CRLF
$Output = $Output & "==========================================" & @CRLF
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
$colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystemProduct", "WQL", _
                                          $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

If IsObj($colItems) then
   For $objItem In $colItems
      $Output = $Output & "Caption: " & $objItem.Caption & @CRLF
      $Output = $Output & "Description: " & $objItem.Description & @CRLF
      $Output = $Output & "IdentifyingNumber: " & $objItem.IdentifyingNumber & @CRLF
      $Output = $Output & "Name: " & $objItem.Name & @CRLF
      $Output = $Output & "SKUNumber: " & $objItem.SKUNumber & @CRLF
      $Output = $Output & "UUID: " & $objItem.UUID & @CRLF
      $Output = $Output & "Vendor: " & $objItem.Vendor & @CRLF
      $Output = $Output & "Version: " & $objItem.Version & @CRLF
      if Msgbox(1,"WMI Output",$Output) = 2 then ExitLoop
      $Output=""
   Next
Else
   Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_ComputerSystemProduct" )
Endif

You can easily add a "D" in front of the TAG and fit it in the script you showed before.

regards

ptrex

Share this post


Link to post
Share on other sites

@TBOMB

This is indead a looooong script !!

Maybe this can get you started :

<snip>

You can easily add a "D" in front of the TAG and fit it in the script you showed before.

regards

ptrex

Thanks, I'll start toying with it and see if I can't make it work.

Share this post


Link to post
Share on other sites

ptrex,

I was just asking someone last night at a PowerShell demonstration if AutoIt could pull WMI objects, and he wasn't sure. Thanks for this snippet! :whistle:

Share this post


Link to post
Share on other sites

@2tim3_16

Actually the example doesn't use powershell but pure WMI.

This one does :

#include <Constants.au3>

$Cmd = '$colItems = get-wmiobject -class "Win32_Registry" -namespace "root\CIMV2" `'&@CR& _
       '-computername "." '&@CR& _
       'foreach ($objItem in $colItems) {'&@CR& _
       'write-host "Caption: " $objItem.Caption'&@CR& _
       'write-host "Current Size: " $objItem.CurrentSize'&@CR& _
       'write-host "Description: " $objItem.Description'&@CR& _
       'write-host "Installation Date: " $objItem.InstallDate.substring(6,2)'& _
       '"/" $objItem.InstallDate.substring(4,2)'& _
       '"/" $objItem.InstallDate.substring(0,4)'& _
       '" $objItem.InstallDate.substring(8,2)'& _
       '" $objItem.InstallDate.substring(10,2)'& _
       '" $objItem.InstallDate.substring(12,2)'&@CR& _
       'write-host "Maximum Size: " $objItem.MaximumSize'&@CR& _
       'write-host "Name: " $objItem.Name'&@CR& _
       'write-host "Proposed Size: " $objItem.ProposedSize'&@CR& _
       'write-host "Status: " $objItem.Status'&@CR& _
       '}'

; -noexit -noprofile -command help about_automatic_variables"

$PowerShell = Run('PowerShell.exe -command '&$Cmd, "", @SW_HIDE , _
                $STDERR_CHILD + $STDOUT_CHILD + $STDIN_CHILD)       

StdinWrite($PowerShell,@CRLF) 
StdinWrite($PowerShell)

While 1
    $line = StdoutRead($PowerShell)
    If @error Then ExitLoop
    ;If $line <> "" Then
    ConsoleWrite($line)
    ;EndIf
Wend

While 1
    $line = StderrRead($PowerShell)
    If @error Then ExitLoop
    ConsoleWrite( "STDERR read: "& $line& @CR)
Wend

Enjoy !!

ptrex

Share this post


Link to post
Share on other sites

Actually the example doesn't use powershell but pure WMI.

Right. I was at a PowerShell demonstration, and was asking about AutoIt using WMI without using PowerShell. :whistle:

But thanks for the example using PowerShell as well! :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0