souldjer777

Best Practices - Powershell AutoIT - Recommendations please!

15 posts in this topic

Good Morning AutoIT Gurus,

I'm trying to get an idea of what to do here... I have a list of powershell commands I want to run against remote computers to get data... then I want to act on that data. So I don't know what path to take... Should I have powershell export the data into CSV format then read that data into an AutoIt GUI to finally act on that output by sending commands to run against powershell again?

Say I have a computer that's acting badly... and I can run powershell commands to determine what the network settings are and output that to csv with a specified delimeter ... then I have autoit read the csv output from powershell - create the gui that gives me the option to make changes on the fly to the dns, dhcp etc. for that computer where AutoIT will send back to powershell?

Does that sound like the best way to do things?

I want to keep things simple... I may have to distribute this AutoIT app so I can't have folks installing / downloading / checking versions ... DLL's etc. It's just not worth the hassle and I love AutoIT's portability - it's pure freakin genius.

Please make a recommendation and please leave an example of best practices to call powershell from AutoIT.

YES I'VE LOOKED IN THE FORUMS, Googled site:autoitscript etc... I've   And if anything... it just confuses me even more and makes things more complicate... and AutoIT has done exactly the opposite of that for forever. Slightly losing my mind... lol

(BTW - WMI worked fine until the csv output values actually contained "," commas in them!  That screwed everything up for me - and now I remember why I gave up) 

EXAMPLE: Bad csv output example from windows command prompt:

wmic path Win32_process Get Caption,CommandLine,Description /FORMAT:CSV > test.txt

test.txt

...

C:Program Files (x86)AdaptivaAdaptivaClientbinOneSiteClient64.exe,OneSiteClient64.exe

...

See that "," in the above line? - it's ruining WMI for me... they are all over in the output and quite honestly ruin my day. That comma is necessary for that command to run... so I can't just delete the comma... so I'm screwed.

Can't use WMI... It's just a bad idea with PowerShell being the standard going forward. It's honestly too bad really, I had all my commands lined up and ready to go... just to get screwed by a delimiter and PowerShell let's you choose a delimiter - thank God.

Thank you all!  I appreciate all the help / feedback / input. I LOVE AutoIT  :ILA2:


"Maybe I'm on a road that ain't been paved yet. And maybe I see a sign that ain't been made yet"
Song Title: I guess you could say
Artist: Middle Class Rut

Share this post


Link to post
Share on other sites



WMI:

You do not need to call WMIC. Please have a look at Scriptomatic in the Example Scripts forum. This example generates AutoIt code for you. The returned data is returned to variables or files.

PS:

When you search the forum for "Powershell ptrex" you will find a lot of threads discussing ho AuutoIt and Powershall can interact.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

I appreciate that... thank you water - you are a master at all that you do.

I've been looking at ptrex's forum topics... I believe I have to use PS (PowerShell) going forward so no WMIC - sad but true - still not sure what to do... like starting from scratch imo... nothing looks that familiar.

I'm weeding through the results of all my searches now...

AutoIT Meeting Powershell:

'?do=embed' frameborder='0' data-embedContent>>

Powershell - COM

'?do=embed' frameborder='0' data-embedContent>>

(SAPIEN)

I didn't know what AutoItX was till today when I finally gave up on WMI 02/06/2014 (little late to the party - lol) ... "DLL/COM control.  Add AutoIt features to your favorite programming and scripting languages! Also features a C# assembly and PowerShell CmdLets"

Man oh man... don't know where I'm going with all this...

Should I try this to get output from PowerShell?  or is there a better practice? Just waiting for more advice.
 

Snippet from Malkey's post...


 

Func _PowerShell($sCmd, $sDir = "")
    $sCmd = StringReplace($sCmd, '"', '"""') ; Enables any internal quotes to be read in AutoIt's Run function which runs the powershell commands in powershell.
    Local $text = '', $Pid = Run('"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" ' & $sCmd, $sDir, @SW_HIDE, 2 + 4)
    While 1
        $text &= StdoutRead($Pid, False, False)
        If @error Then ExitLoop
        Sleep(10)
    WEnd
    While 1
        $text &= StderrRead($Pid)
        If @error Then ExitLoop
        ConsoleWrite(@LF & "!#------------------------# Error #---------------------------# " & @LF)
    WEnd
    Return $text
EndFunc   ;==>_PowerShell

Yeah, I'm not the best programmer, just creative in workarounds :idiot:  I'll get started the code now to see what I get.


"Maybe I'm on a road that ain't been paved yet. And maybe I see a sign that ain't been made yet"
Song Title: I guess you could say
Artist: Middle Class Rut

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Would you stick with WMI if this problem could be solved?

(BTW - WMI worked fine until the csv output values actually contained "," commas in them!  That screwed everything up for me - and now I remember why I gave up)

Edited by water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Example:

his code (generated by Scriptomatic) writes all properties of all processes to Notepad.

; Generated by AutoIt Scriptomatic

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

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

If IsObj($colItems) then
   For $objItem In $colItems
      $Output = $Output & "Caption: " & $objItem.Caption & @CRLF
      $Output = $Output & "CommandLine: " & $objItem.CommandLine & @CRLF
      $Output = $Output & "CreationClassName: " & $objItem.CreationClassName & @CRLF
      $Output = $Output & "CreationDate: " & WMIDateStringToDate($objItem.CreationDate) & @CRLF
      $Output = $Output & "CSCreationClassName: " & $objItem.CSCreationClassName & @CRLF
      $Output = $Output & "CSName: " & $objItem.CSName & @CRLF
      $Output = $Output & "Description: " & $objItem.Description & @CRLF
      $Output = $Output & "ExecutablePath: " & $objItem.ExecutablePath & @CRLF
      $Output = $Output & "ExecutionState: " & $objItem.ExecutionState & @CRLF
      $Output = $Output & "Handle: " & $objItem.Handle & @CRLF
      $Output = $Output & "HandleCount: " & $objItem.HandleCount & @CRLF
      $Output = $Output & "InstallDate: " & WMIDateStringToDate($objItem.InstallDate) & @CRLF
      $Output = $Output & "KernelModeTime: " & $objItem.KernelModeTime & @CRLF
      $Output = $Output & "MaximumWorkingSetSize: " & $objItem.MaximumWorkingSetSize & @CRLF
      $Output = $Output & "MinimumWorkingSetSize: " & $objItem.MinimumWorkingSetSize & @CRLF
      $Output = $Output & "Name: " & $objItem.Name & @CRLF
      $Output = $Output & "OSCreationClassName: " & $objItem.OSCreationClassName & @CRLF
      $Output = $Output & "OSName: " & $objItem.OSName & @CRLF
      $Output = $Output & "OtherOperationCount: " & $objItem.OtherOperationCount & @CRLF
      $Output = $Output & "OtherTransferCount: " & $objItem.OtherTransferCount & @CRLF
      $Output = $Output & "PageFaults: " & $objItem.PageFaults & @CRLF
      $Output = $Output & "PageFileUsage: " & $objItem.PageFileUsage & @CRLF
      $Output = $Output & "ParentProcessId: " & $objItem.ParentProcessId & @CRLF
      $Output = $Output & "PeakPageFileUsage: " & $objItem.PeakPageFileUsage & @CRLF
      $Output = $Output & "PeakVirtualSize: " & $objItem.PeakVirtualSize & @CRLF
      $Output = $Output & "PeakWorkingSetSize: " & $objItem.PeakWorkingSetSize & @CRLF
      $Output = $Output & "Priority: " & $objItem.Priority & @CRLF
      $Output = $Output & "PrivatePageCount: " & $objItem.PrivatePageCount & @CRLF
      $Output = $Output & "ProcessId: " & $objItem.ProcessId & @CRLF
      $Output = $Output & "QuotaNonPagedPoolUsage: " & $objItem.QuotaNonPagedPoolUsage & @CRLF
      $Output = $Output & "QuotaPagedPoolUsage: " & $objItem.QuotaPagedPoolUsage & @CRLF
      $Output = $Output & "QuotaPeakNonPagedPoolUsage: " & $objItem.QuotaPeakNonPagedPoolUsage & @CRLF
      $Output = $Output & "QuotaPeakPagedPoolUsage: " & $objItem.QuotaPeakPagedPoolUsage & @CRLF
      $Output = $Output & "ReadOperationCount: " & $objItem.ReadOperationCount & @CRLF
      $Output = $Output & "ReadTransferCount: " & $objItem.ReadTransferCount & @CRLF
      $Output = $Output & "SessionId: " & $objItem.SessionId & @CRLF
      $Output = $Output & "Status: " & $objItem.Status & @CRLF
      $Output = $Output & "TerminationDate: " & WMIDateStringToDate($objItem.TerminationDate) & @CRLF
      $Output = $Output & "ThreadCount: " & $objItem.ThreadCount & @CRLF
      $Output = $Output & "UserModeTime: " & $objItem.UserModeTime & @CRLF
      $Output = $Output & "VirtualSize: " & $objItem.VirtualSize & @CRLF
      $Output = $Output & "WindowsVersion: " & $objItem.WindowsVersion & @CRLF
      $Output = $Output & "WorkingSetSize: " & $objItem.WorkingSetSize & @CRLF
      $Output = $Output & "WriteOperationCount: " & $objItem.WriteOperationCount & @CRLF
      $Output = $Output & "WriteTransferCount: " & $objItem.WriteTransferCount & @CRLF
   Next
   ConsoleWrite($Output)
   FileWrite(@TempDir & "\Win32_Process.TXT", $Output )
   Run(@Comspec & " /c start " & @TempDir & "\Win32_Process.TXT" )
Else
   Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_Process" )
Endif


Func WMIDateStringToDate($dtmDate)

    Return (StringMid($dtmDate, 5, 2) & "/" & _
    StringMid($dtmDate, 7, 2) & "/" & StringLeft($dtmDate, 4) _
    & " " & StringMid($dtmDate, 9, 2) & ":" & StringMid($dtmDate, 11, 2) & ":" & StringMid($dtmDate,13, 2))
EndFunc

Does it work for your Adaptiva process?


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Thanks again water... I very much appreciate the feedback and help!

I could see how I might change the output... instead of using " & @CRLF" I could use a special personal delimiter like "~|:<|>:|~" and put a "@CRLF" on the final return value... and then write that to an array :)  That would work :)

But again, man oh man, and I don't want to but I gotta get my hands on PowerShell to get on the MS train.


"Maybe I'm on a road that ain't been paved yet. And maybe I see a sign that ain't been made yet"
Song Title: I guess you could say
Artist: Middle Class Rut

Share this post


Link to post
Share on other sites

No delimiter is needed. Modify the script so it fills the array with the needed data.

Example:

; Generated by AutoIt Scriptomatic

#include <Array.au3>

$colItems = ""
$strComputer = "."
$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\")
$colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL")
If IsObj($colItems) Then
    Global $i = 0
    Global $aResult[$colItems.Count][3]
    For $objItem In $colItems
        $aResult[$i][0] = $objItem.Caption
        $aResult[$i][1] = $objItem.CommandLine
        $aResult[$i][2] = $objItem.Description
        $i = $i + 1
    Next
    _ArrayDisplay($aResult)
Else
    MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_Process")
EndIf

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

That code did the trick :) But I did get it to work with the delimiter as well - so I posted that code below.

Concerning your code above - Any idea how to get rid of the ListView limitation?

Some commands are too long for the _ArrayDisplay to show.

Array Element Max Length (DisplayArray)

'?do=embed' frameborder='0' data-embedContent>>

Thanks again water!

; Generated by AutoIt Scriptomatic
#include <Array.au3>
#include <File.au3>
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$strComputer = "."
Global $aArray

If FileExists (@TempDir & "\Win32_Process.TXT") Then FileDelete (@TempDir & "\Win32_Process.TXT")

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

If IsObj($colItems) then
   For $objItem In $colItems
      $Output = $Output & "Caption: " & $objItem.Caption & "~|:<|>:|~"
      $Output = $Output & "CommandLine: " & $objItem.CommandLine & "~|:<|>:|~"
      $Output = $Output & "CreationClassName: " & $objItem.CreationClassName & "~|:<|>:|~"
      $Output = $Output & "CreationDate: " & WMIDateStringToDate($objItem.CreationDate) & "~|:<|>:|~"
      $Output = $Output & "CSCreationClassName: " & $objItem.CSCreationClassName & "~|:<|>:|~"
      $Output = $Output & "CSName: " & $objItem.CSName & "~|:<|>:|~"
      $Output = $Output & "Description: " & $objItem.Description & "~|:<|>:|~"
      $Output = $Output & "ExecutablePath: " & $objItem.ExecutablePath & "~|:<|>:|~"
      $Output = $Output & "ExecutionState: " & $objItem.ExecutionState & "~|:<|>:|~"
      $Output = $Output & "Handle: " & $objItem.Handle & "~|:<|>:|~"
      $Output = $Output & "HandleCount: " & $objItem.HandleCount & "~|:<|>:|~"
      $Output = $Output & "InstallDate: " & WMIDateStringToDate($objItem.InstallDate) & "~|:<|>:|~"
      $Output = $Output & "KernelModeTime: " & $objItem.KernelModeTime & "~|:<|>:|~"
      $Output = $Output & "MaximumWorkingSetSize: " & $objItem.MaximumWorkingSetSize & "~|:<|>:|~"
      $Output = $Output & "MinimumWorkingSetSize: " & $objItem.MinimumWorkingSetSize & "~|:<|>:|~"
      $Output = $Output & "Name: " & $objItem.Name & "~|:<|>:|~"
      $Output = $Output & "OSCreationClassName: " & $objItem.OSCreationClassName & "~|:<|>:|~"
      $Output = $Output & "OSName: " & $objItem.OSName & "~|:<|>:|~"
      $Output = $Output & "OtherOperationCount: " & $objItem.OtherOperationCount & "~|:<|>:|~"
      $Output = $Output & "OtherTransferCount: " & $objItem.OtherTransferCount & "~|:<|>:|~"
      $Output = $Output & "PageFaults: " & $objItem.PageFaults & "~|:<|>:|~"
      $Output = $Output & "PageFileUsage: " & $objItem.PageFileUsage & "~|:<|>:|~"
      $Output = $Output & "ParentProcessId: " & $objItem.ParentProcessId & "~|:<|>:|~"
      $Output = $Output & "PeakPageFileUsage: " & $objItem.PeakPageFileUsage & "~|:<|>:|~"
      $Output = $Output & "PeakVirtualSize: " & $objItem.PeakVirtualSize & "~|:<|>:|~"
      $Output = $Output & "PeakWorkingSetSize: " & $objItem.PeakWorkingSetSize & "~|:<|>:|~"
      $Output = $Output & "Priority: " & $objItem.Priority & "~|:<|>:|~"
      $Output = $Output & "PrivatePageCount: " & $objItem.PrivatePageCount & "~|:<|>:|~"
      $Output = $Output & "ProcessId: " & $objItem.ProcessId & "~|:<|>:|~"
      $Output = $Output & "QuotaNonPagedPoolUsage: " & $objItem.QuotaNonPagedPoolUsage & "~|:<|>:|~"
      $Output = $Output & "QuotaPagedPoolUsage: " & $objItem.QuotaPagedPoolUsage & "~|:<|>:|~"
      $Output = $Output & "QuotaPeakNonPagedPoolUsage: " & $objItem.QuotaPeakNonPagedPoolUsage & "~|:<|>:|~"
      $Output = $Output & "QuotaPeakPagedPoolUsage: " & $objItem.QuotaPeakPagedPoolUsage & "~|:<|>:|~"
      $Output = $Output & "ReadOperationCount: " & $objItem.ReadOperationCount & "~|:<|>:|~"
      $Output = $Output & "ReadTransferCount: " & $objItem.ReadTransferCount & "~|:<|>:|~"
      $Output = $Output & "SessionId: " & $objItem.SessionId & "~|:<|>:|~"
      $Output = $Output & "Status: " & $objItem.Status & "~|:<|>:|~"
      $Output = $Output & "TerminationDate: " & WMIDateStringToDate($objItem.TerminationDate) & "~|:<|>:|~"
      $Output = $Output & "ThreadCount: " & $objItem.ThreadCount & "~|:<|>:|~"
      $Output = $Output & "UserModeTime: " & $objItem.UserModeTime & "~|:<|>:|~"
      $Output = $Output & "VirtualSize: " & $objItem.VirtualSize & "~|:<|>:|~"
      $Output = $Output & "WindowsVersion: " & $objItem.WindowsVersion & "~|:<|>:|~"
      $Output = $Output & "WorkingSetSize: " & $objItem.WorkingSetSize & "~|:<|>:|~"
      $Output = $Output & "WriteOperationCount: " & $objItem.WriteOperationCount & "~|:<|>:|~"
      $Output = $Output & "WriteTransferCount: " & $objItem.WriteTransferCount & @CRLF
   Next
   ;ConsoleWrite($Output)
   FileWrite(@TempDir & "\Win32_Process.TXT", $Output)
   ; Run(@Comspec & " /c start " & @TempDir & "\Win32_Process.TXT" )
    Local $aRecords
    If Not _FileReadToArray(@TempDir & "\Win32_Process.TXT", $aRecords, $FRTA_NOCOUNT + $FRTA_ENTIRESPLIT, "~|:<|>:|~") Then
    MsgBox(4096, "Error", " Error reading file to Array: " & @error)
    Exit
    EndIf
    _ArrayDisplay ($aRecords, "ARecords")
Else
   Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_Process" )
Endif



Func WMIDateStringToDate($dtmDate)

    Return (StringMid($dtmDate, 5, 2) & "/" & _
    StringMid($dtmDate, 7, 2) & "/" & StringLeft($dtmDate, 4) _
    & " " & StringMid($dtmDate, 9, 2) & ":" & StringMid($dtmDate, 11, 2) & ":" & StringMid($dtmDate,13, 2))
EndFunc
Edited by souldjer777

"Maybe I'm on a road that ain't been paved yet. And maybe I see a sign that ain't been made yet"
Song Title: I guess you could say
Artist: Middle Class Rut

Share this post


Link to post
Share on other sites

The latest production version of AutoIt allows to set the column width.

 

$iMax_Colwidth: Max width to which a ListView column will expand to show content. Default = 350 pixels.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

Your example takes all data returned by WMI, writes it to a file using custom delimiter and then reads the file again to populate an array and display it.

Is there a reason why you need to write the data to a file?


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#11 ·  Posted (edited)

If you are doing this on Windows 7 and below, I believe it would still use WMI, even if invoked by powershell.

#include <AutoItConstants.au3>

$sCommands = 'powershell -Command Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE"'
$iPID = Run(@ComSpec & " /c " & $sCommands, "", @SW_SHOW , $stdout_child)

$sOutput = ""

 While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then 
            ExitLoop
        EndIf
    WEnd

 $fOut = @ScriptDir & "NetAdapter_" & @MON & @MDAY & @Year & "_" & @HOUR & @MIN & ".txt"

$fLog = FileOpen($fOut , 10)
FileWrite($fLog , $sOutput)
FileClose($fLog)

shellexecute($fOut)

and some of my other examples:

'?do=embed' frameborder='0' data-embedContent>>

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

You are right, it's WMI still - but Powershell gives you options to sort the data right, delimiter, more exports.

Any idea how I would format something like this...

@{Name='IpSubnet';Expression={$_.IpSubnet -join '; '}},

...in AutoIT without things blowing up?

It's the ; and the ' that are screwing things up for me.

Script Take From...

http://stackoverflow.com/questions/7712900/how-to-deal-with-system-string

Get-WmiObject Win32_NetworkAdapterConfiguration|
Select-Object Description, DHCPServer,
@{Name='IpAddress';Expression={$_.IpAddress -join '; '}},
@{Name='IpSubnet';Expression={$_.IpSubnet -join '; '}},
@{Name='DefaultIPgateway';Expression={$_.DefaultIPgateway -join '; '}},
@{Name='DNSServerSearchOrder';Expression={$_.DNSServerSearchOrder -join '; '}},
WinsPrimaryServer, WINSSecindaryServer|
ConvertTo-Html > .temp.htm

Thank you again everyone for your help and steering me in the right direction!

Uh, I'm going to try it anyway - maybe it's just color coding the code incorrectly... 

Nope, it's hosed... google ;) here I come!

Edited by souldjer777

"Maybe I'm on a road that ain't been paved yet. And maybe I see a sign that ain't been made yet"
Song Title: I guess you could say
Artist: Middle Class Rut

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

Use -Property, then format the output prior to exporting.  The items you had issue with come back in braces.

like so:

#include <AutoItConstants.au3>
#include <Array.au3>

$sCommands = "powershell -Command Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -Property IPAddress,Description,IPSubnet,DHCPServer,DefaultIPGateway,DNSServerSearchOrder,WinsPrimaryServer,WinsSecondaryServer"
$iPID = Run(@ComSpec & " /c " & $sCommands, "", @SW_SHOW , $stdout_child)

$sOutput = ""

 While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then ; Exit the loop if the process closes or StderrRead returns an error.
            ExitLoop
        EndIf
    WEnd

$aOutput = stringsplit($sOutput , @CR , 3)

For $i = ubound($aOutput) - 1 to 0 step - 1
If stringleft(stringstripws($aOutput[$i], 1) , 1) = "" OR stringleft(stringstripws($aOutput[$i], 1) , 1) = "_" Then _ArrayDelete($aOutput, $i)
Next


_ArrayDisplay($aOutput)

*posted this in my PS thread as it was a useful exercise

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

This may help...

#include <array.au3>

Local $ret = _WMI('select IPAddress,Description,IPSubnet,DHCPServer,DefaultIPGateway,DNSServerSearchOrder,WinsPrimaryServer,WinsSecondaryServer from ' & _
'Win32_NetworkAdapterConfiguration where ipenabled=true',0)

If @error Then Exit (ConsoleWrite(@LF & '!> @ERROR    = ' & @error & @LF & '!> @EXTENDED = ' & @extended & @LF & '!> $RET      = ' & $ret & @LF & @LF))
If IsArray($ret) Then _ArrayDisplay($ret)
If IsString($ret) Then ConsoleWrite($ret & @CRLF)

; #FUNCTION# ====================================================================================================================
; Name...........: _WMI
; Description ...: Returns formatted output from a query against any class of the CIMV2 namespace using WMI.
; Syntax.........: _WMI($sWQL, $bReturnType, $sDelimiter, $sTargetPC)
; Parameters ....: $sWQL            - Any class in the WMI CIMV2 namespace (e.g. Win32_Process, Win32_BIOS, Win32_Desktop, etc.)
;                                     or any WQL 'Select' query.  If only the class is specified then all columns
;                                     for all items are returned.
;                  $bReturnType     - Indicates return format.  $bReturnType can be a string or integer.
;                                   |0 - Return a 2D array with item names in col 0 (on the left).
;                                   |1 - Return a 2D array with item names in row 0 (on top).      (DEFAULT)
;                                   |2 - Return a @CRLF delimited string of item names (row #1) followed by items.  Each value is
;                                        delimited by $sDelimiter.
;                  $sDelimiter      - The delimiter used to seperate values/property names within an item.  The default is
;                                     '`' because other common delimiter characters (e.g. '|', ',', '=', ':', '~' etc. appear
;                                     in some values returned by various WQL queries.  This can be a string of characters (e.g. '//').
;                  $sTargetPC       - Name of the PC to run the query on.
; Return values .: Success          - A 2D array or string depending on $bReturnType.
;                  Failure          - Sets @ERROR and returns a value as follows:
;                                   |1 - $sWQL is blank                     Return value - None
;                                   |2 - $bReturnType invalid               Return value - The parm supplied
;                                   |3 - $sDelimiter not specified          Return value - None
;                                   |4 - WMI ObjGet failure                 Return value - None
;                                   |5 - ExecQuery failure                  Return value - $sWQL
;                                   |6 - No items returned                  Return value - $sWQL
;
; Author ........: kylomas
; Modified.......: 02/02/2015 V01R01M01 initial release
; Remarks .......:
; Related .......: WMI is required
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================

Func _WMI($sWQL, $bReturnType = 1, $sDelimiter = '`', $sTargetPC = @ComputerName)

    ; flush parms
    Switch $bReturnType
        Case 0, 1, 2, '0', '1', '2'
        Case -1, Default
            $bReturnType = 1
        Case Else
            Return SetError(2, 0, $bReturnType)
    EndSwitch

    Switch True
        Case $sDelimiter = -1 Or $sDelimiter = Default
            $sDelimiter = '`'
        Case StringLen($sDelimiter) > 0
        Case Else
            Return SetError(3, 0, $sDelimiter)
    EndSwitch

    If StringLen($sWQL) = 0 Then Return SetError(1)
    If StringInStr($sWQL, 'select') = 0 Then $sWQL = 'select * from ' & $sWQL

    Local $oWMI = '', $oItem = '', $oItems = '', $P = ''

    ; Get WMI instance
    ; Do NOT use $wbemFlagReturnImmediately or $wbeForwardOnly as this disables the "Count" property
    $oWMI = ObjGet("winmgmts:{impersonationLevel=impersonate}!\\" & $sTargetPC & "\root\CIMV2")
    If Not IsObj($oWMI) Then Return SetError(4)

    ; Run query
    $oItems = $oWMI.ExecQuery($sWQL)
    If Not IsObj($oItems) Then Return SetError(5, 0, $sWQL)
    If $oItems.count = 0 Then Return SetError(6, 0, $sWQL)

    Local $str = ''

    ; format header / use this method as opposed to the "itemindex" method for XP compatibility
    For $oItem In $oItems
        For $P In $oItem.Properties_()
            $str &= '<' & $P.Name & '>' & $sDelimiter
        Next
        $str = StringTrimRight($str, StringLen($sDelimiter)) & @CRLF
        ExitLoop
    Next

    ; format each detail item
    For $oItem In $oItems
        For $P In $oItem.Properties_()
            Switch True
                Case $P.isarray
                    $aTmp1 = $P.Value
                    $str &= _ArrayToString($aTmp1, '') & $sDelimiter
                Case $P.CIMTYPE = 101
                    $str &= CNVTDate($P.Value) & $sDelimiter
                Case Else
                    $str &= $P.Value & $sDelimiter
            EndSwitch
        Next
        $str = StringTrimRight($str, StringLen($sDelimiter)) & @CRLF
    Next
    $str = StringTrimRight($str, 2)

    Switch $bReturnType
        Case '1', 1, -1, Default
            ; return 2D array / column names are at top (row 0)
            Local $aTmp1 = StringSplit($str, @CRLF, 3), $aTmp2
            Local $aRet[UBound($aTmp1)][UBound(StringSplit($aTmp1[0], $sDelimiter, 3))]
            For $1 = 0 To UBound($aTmp1) - 1
                $aTmp2 = StringSplit($aTmp1[$1], $sDelimiter, 3)
                For $2 = 0 To UBound($aTmp2) - 1
                    $aRet[$1][$2] = $aTmp2[$2]
                Next
            Next
            Return $aRet
        Case '0', 0
            ; return 2D array / column names are to the left (col 0)
            Local $aTmp1 = StringSplit($str, @CRLF, 3), $aTmp2
            Local $aRet[UBound(StringSplit($aTmp1[0], $sDelimiter, 3))][UBound($aTmp1)]
            For $1 = 0 To UBound($aTmp1) - 1
                $aTmp2 = StringSplit($aTmp1[$1], $sDelimiter, 3)
                For $2 = 0 To UBound($aTmp2) - 1
                    $aRet[$2][$1] = $aTmp2[$2]
                Next
            Next
            Return $aRet
        Case '2', 2
            ; return string
            Return $str
        Case Else
            Return SetError(7, 0, $bReturnType)
    EndSwitch

EndFunc   ;==>_WMI

Func CNVTDate($dtmDate)
    ; reformat date to mm/dd/yyyy hh:mm:ss and zero fill single digit values
    Return StringRegExpReplace(StringRegExpReplace($dtmDate, '(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}).*', '$2/$3/$1 $4:$5:$6'), '(?<!\d)(\d/)', '0$1')
EndFunc   ;==>CNVTDate

This solves the delimiter problem and  you can sort the data in the array if desired.  See the function header for ways to return the data. 

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

For Dog's sake, stop writing AutoIT.

It isn't IT (eye tee)

It is It ... as in digit

You are automating something ... It

AutoIt AutoIt AutoIt AutoIt is not AutoIT ... say after me

N.B. Please excuse my little rant, but it was irritating me ... it seems you fail to recognize all the many examples right in your face, where plainly it is lowercase 't' ..... nowhere does it show uppercase 'T'.

P.S. I didn't eat my cereal today .... or surreal either.

P.S.S. A good soldier, whether they are 7, 77, 777 or 7777 etc needs to do the right thing and pay proper attention.

Edited by TheSaint

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

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

  • Similar Content

    • hemichallenger
      By hemichallenger
      Not sure if this is possible or if someone has already tackled this. Is it possible to embed PowerShell into a GUI? Autoit is great for quick function but sometime I need to run a command thru PowerShell. It be great to have PowerShell console embedded into the gui.
    • BigDaddyO
      By BigDaddyO
      After much searching I finally found a method to get eMails from an Exchange eMail account inbox.  I was hoping for AutoIT or vbscript but I couldn't find any that would read the inbox messages without using Outlook.
      I needed this because I'm testing a web-form that generates an eMail sent to a shared mailbox "not what my current outlook is configured for".  so, I needed to connect to a different account, then get the inbox messages, and see if the auto-generated eMail message body contains what I submitted in the form.
       
      I found a PowerShell script that was close and modified it to do just what I want, but I'd still like it to run in AutoIT but I'm not sure how to use the Microsoft.Exchange.WebServices.dll
      Anybody have some ideas? 
      #To Launch! # C:\Windows\System32> powershell -ExecutionPolicy ByPass #This launches PowerShell and allows execution of .ps1 files # PS C:\Windows\System32> . "C:\Temp\eMail\getInbox.ps1" #The period . in front of the .ps1 file forces PS to display results on-screen # Where is the EWS .DLL file that you are using # Get the installer from https://www.microsoft.com/en-us/download/details.aspx?id=42022 # We only need 2 dll's from the install and they can be stored anywhere: "Microsoft.Exchange.WebServices.Auth.dll" & "Microsoft.Exchange.WebServices.dll" $EWSdll = "C:\Temp\eMail\Microsoft.Exchange.WebServices.dll" # Where do you want the output text file to be saved $Output = "C:\Temp\eMails.txt" # replace with your email address $email = "MyemailAddress@work.net" # only need to populate these if you're impersonating... $username = "myemail" $password = "Sup3rS3cre+" $domain = "ad.work.net" # load the assembly : point to the dll in the location you have the .dll file [void] [Reflection.Assembly]::LoadFile($EWSdll) # set ref to exchange, first references 2007, 2nd is 2010 (default) #$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1) $s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService # use first option if you want to impersonate, otherwise, grab your own credentials with the 3rd one. not sure what the 2nd one is for $s.Credentials = New-Object Net.NetworkCredential($username, $password, $domain) ##$s.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials #$s.UseDefaultCredentials = $true # discover the url from your email address $s.AutodiscoverUrl($email) # get a handle to the inbox $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) #create a property set (to let us access the body & other details not available from the FindItems call) $psPropertySet = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties) $psPropertySet.RequestedBodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::Text; # If you have a set number of items you want to get, use this and insert the # in the () # $items = $inbox.FindItems(5) # If you want to retrieve all items (Server limit is usually at 1000) then use this line # Details on the max returned by server: https://blogs.msdn.microsoft.com/exchangedev/2010/03/12/throttling-policies-and-the-ewsfindcountlimit/ $items = $inbox.FindItems($inbox.TotalCount) # Put some counts at the top of the output Write-host "Total Inbox count: $($inbox.TotalCount)" Write-host "Unread count: $($inbox.UnreadCount)" #These two lines, write the output to the specified text file Add-Content $Output "Total Inbox count: $($inbox.TotalCount)" Add-Content $Output "Unread count: $($inbox.UnreadCount)" foreach ($item in $items.Items) { # load the property set to allow us to get to the body $item.load($psPropertySet) # Get the Body text as-is $bod = $item.Body.Text #if you only want a short summary of the Body, then comment the above line and un-comment these 4 lines # $bod = $item.Body.Text -replace '\s+', ' ' # $bodCutOff = (100,$bod.Length | Measure-Object -Minimum).Minimum # $bod = $bod.Substring(0,$bodCutOff) # $bod = "$bod..." # output the results - first of all the From, Subject, References and Message ID write-host "====================================================================" Write-host "From: $($item.From.Name)" Write-host "Subject: $($item.Subject)" Write-host "Body: $($bod)" write-host "====================================================================" "" # Output the results to the specified Text file Add-Content $Output "" Add-Content $Output "====================================================================" Add-Content $Output "From: $($item.From.Name)" Add-Content $Output "Subject: $($item.Subject)" Add-Content $Output "Body:",$($bod) Add-Content $Output "====================================================================" Add-Content $Output "" } #see these URLs for more info # EWS Stuff # folder members: https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.folder_members%28v=exchg.80%29.aspx # exporting headers: https://www.allabout365.com/2010/10/export-email-headers-exchange-powershell/ # read emails with EWS: https://social.technet.microsoft.com/Forums/en-US/3fbf8348-2945-43aa-a0bc-f3b1d34da27c/read-emails-with-ews?forum=exchangesvrdevelopment  
      Thanks,
      Mike
    • Jibberish
      By Jibberish
      Hi all,
      I need to read a log file into an array, but the log file is encoded as $FO_UTF16_BE_NOBOM (2048) = Use Unicode UTF16 Big Endian (without BOM) per FileGetEncoding (it returns 2048).
      I have searched how to convert these log files to UTF-8 and finally found a Powershell command. Since then I have been racking my brain trying to get the function to work. The command itself works from a Powerscript prompt:
      C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content C:\Logs\Myplayer_10-10-17-02-31.log | Set-Content -Encoding utf8 C:\Logs\Myplayer1.log This is my sandbox;
      #include <array.au3> #include <File.au3> Local $aArrayLogFile Local $sLogDir = "C:\Logs\" Local $sLogFile = "Myplayer_10-10-17-02-31.log" Local $sConvertedLog = "ConvertedLog.log" Local $sLogDirFile = $sLogDir&$sLogFile RunWait("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content "&$sLogDirFile&" | Set-Content -Encoding utf8 "&$sConvertedLog,$sLogDir) _FileReadToArray($sLogDirFile, $aArrayLogFile) _ArrayDisplay($aArrayLogFile) Also tried
      RunWait("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content "&$sLogDirFile&" | Set-Content -Encoding utf8 "&$sConvertedLog,$sLogDir) and
      ShellExecuteWait("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"," -Command Get-Content "&$sLogDirFile&" | Set-Content -Encoding utf8 "&$sConvertedLog,$sLogDir) Tried without -Command and a bunch of other parameters that were sprinkled throughout the internet from people trying to get this to work.
      Thanks
      Jibs
    • ur
      By ur
      I am maintaining all the reusable code in a separate file as library.au3.
      In that file I have referenced some dependent files using fileinstall, so that they will be extracted when necessary.
       
      Problem is, if I use a function in the library.au3 in another script which doesn't require this dependent file, as I am including the whole file using include tag, it is embedding that file also.
      Is there any way to exclude that.
       
    • david1337
      By david1337
      Hi guys,
      I need a little help here
      I have this simple Powershell script, that is able to set "sig.htm" as signature in OWA for the mail account specified.
      First part of the script just loads the Exchange snapin, since this is needed for the Get-Mailbox command.
      #Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session if (!(Get-PSSnapin | where {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) { try { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP } catch { #Snapin was not loaded Write-Warning $_.Exception.Message EXIT } . $env:ExchangeInstallPath\bin\RemoteExchange.ps1 Connect-ExchangeServer -auto -AllowClobber } $mailboxes = Get-Mailbox -Identity user@domain.com $mailboxes| foreach {$file= "sig.htm"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml "$(Get-Content -Path $file -ReadCount 0)"} What I want is for AutoIt to use Powershell.exe to run the script somehow. This way I would be able to use AutoIt variables and arrays together with the PS script.
       I guess the solution would be to run Powershell.exe with command line arguments?
      If that is not possible, maybe have the script stored as a "ps1" file, and interact with it that way? (not preferred)