Jump to content
Jibsbrown

powershell to array

Recommended Posts

Hello,

Having a headache get powershell get-printer to store in an array. tried a few different ways but either get a black array or error. the following I at least get a value in array but not getting the printer list.

any ideas to get the results to show in to an array?

;#RequireAdmin

#include <Constants.au3>
#include <Array.au3>



$aPntList = Run("powershell.exe get-printer" , @SystemDir , @SW_HIDE)

$PrtList = StringSplit ($aPntList, @CRLF, 2)

_ArrayDisplay ($PrtList)

image.thumb.png.02e893c628ddf2e598caa2b1d0d8f4c5.png

Share this post


Link to post
Share on other sites

I would highly recommend that you use Win32_Printer Class.  It is working in all Windows versions and you can get all the info that you need and much more...

But if you insist of using PS, you could use this :

$iPID = Run("powershell.exe get-printer" , @SystemDir , @SW_SHOW, $STDERR_MERGED)
ProcessWaitClose ($iPID)
$sPrtList = StdoutRead ($iPID)
ConsoleWrite ($sPrtList & @CRLF)

I will leave you the fun of splitting the different columns into an array ;)

Share this post


Link to post
Share on other sites

I use the following function to retrieve data from Powershell in the AD UDF:

; #FUNCTION#====================================================================================================================
; Name...........: _AD_CreateMailboxPS
; Description ...: Creates a mailbox for a user using PowerShell
; Syntax.........: _AD_CreateMailboxPS($sUser, $sURI[, $sSessionParam = Default[, $sMailboxParam = Default[, $iRunShowFlag = Default]])
; Parameters ....: $sUser         - User account (SamAccountName or FQDN) for which you want to create the mailbox
;                  $sURI          - Specifies a URI that defines the connection endpoint for the session. The URI must be fully qualified.
;                                   Example: http://YourExchangeServerNameGoesHere.CompanyName.com
;                  $sSessionParam - [optional] One or multiple additional parameters for the PowerShell "Session" command e.g. " -Authentication Kerberos"
;                  $sMailboxParam - [optional] One or multiple additional parameters for the PowerShell "Enable-Mailbox" command (see parameter $sSessionParam)
;                  $iRunShowFlag  - [optional] Sets the show-flag parameter of the Run command. Default = Default keyword
; Return values .: Success - Zero based one-dimensional array holding the StdOut messages written by PowerShell
;                  Failure - "", sets @error to:
;                  |1 - $sUser does not exist
;                  |2 - $sUser already has a mailbox
;                  |3 - $sUser is invalid (empty)
;                  |4 - $sURI is invalid (empty)
;                  |5 - Run returned an error (PowerShell could not be started). @extended is set to the @error returned by Run
;                  |6 - Writing to StdIn returned an error. @extended is set to the @error returned by StdinWrite
;                  Failure - Zero based one-dimensional array holding the StdErr messages written by PowerShell, sets error to:
;                  |7 - PowerShell has written some error messages to StdErr.
; Author ........: water
; Modified.......:
; Remarks .......: The mailbox is created using PowerShell. No additional tools need to be installed on the local mchine.
; Related .......:
; Link ..........:
; Example .......: Yes
; ===============================================================================================================================
Func _AD_CreateMailboxPS($sUser, $sURI, $sSessionParam = Default, $sMailboxParam = Default, $iRunShowFlag = Default)

    Local $aResult, $sProperty, $oRecordSet, $sLDAPEntry, $oUser, $iPID, $sCMD = "Powershell -Command -", $sSTDOUT = "", $sSTDERR = "", $sOutput = "", $bError = False
    If StringStripWS($sUser, $STR_STRIPALL) = "" Then Return SetError(3, 0, "")
    If StringStripWS($sURI, $STR_STRIPALL) = "" Then Return SetError(4, 0, "")
    If $sSessionParam = Default Then $sSessionParam = ""
    If $sMailboxParam = Default Then $sMailboxParam = ""
    If Not _AD_ObjectExists($sUser) Then Return SetError(1, 0, "")
    $sProperty = "sAMAccountName"
    If StringMid($sUser, 3, 1) = "=" Then $sProperty = "distinguishedName" ; FQDN provided
    $__oAD_Command.CommandText = "<LDAP://" & $sAD_HostServer & "/" & $sAD_DNSDomain & ">;(" & $sProperty & "=" & $sUser & ");ADsPath;subtree"
    $oRecordSet = $__oAD_Command.Execute ; Retrieve the ADsPath for the object
    $sLDAPEntry = $oRecordSet.fields(0).Value
    $oUser = __AD_ObjGet($sLDAPEntry) ; Retrieve the COM Object for the object
    If $oUser.HomeMDB <> "" Then Return SetError(2, 0, "")
    $iPID = Run($sCMD, @SystemDir, $iRunShowFlag, $STDIN_CHILD + $STDOUT_CHILD + $STDERR_CHILD)
    If $iPID = 0 Or @error Then Return SetError(5, @error, "")
    $sCMD = "$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri " & $sURI & " " & $sSessionParam & _
            ";Import-PSSession $Session" & _
            ";Enable-Mailbox -Identity " & $sUser & " " & $sMailboxParam & _
            ";Remove-PSSession $Session"
    StdinWrite($iPID, $sCMD)
    If @error Then Return SetError(6, @error, "")
    StdinWrite($iPID)
    ; Process STDOUT
    While 1
        $sOutput = StdoutRead($iPID)
        If @error Then ExitLoop
        If $sOutput <> "" Then $sSTDOUT = $sSTDOUT & $sOutput
    WEnd
    ; Process STDERR
    While 1
        $sOutput = StderrRead($iPID)
        If @error Then ExitLoop
        If $sOutput <> "" Then $sSTDERR = $sSTDERR & $sOutput
        $bError = True
    WEnd
    If $bError Then
        $aResult = StringSplit($sSTDERR, @CRLF, $STR_ENTIRESPLIT + $STR_NOCOUNT)
        Return SetError(7, 0, $aResult)
    Else
        $aResult = StringSplit($sSTDOUT, @CRLF, $STR_ENTIRESPLIT + $STR_NOCOUNT)
        Return $aResult
    EndIf
EndFunc   ;==>_AD_CreateMailboxPS

 


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2020-09-05 - Version 1.5.1.1) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2020-06-27 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (NEW 2020-06-27 - Version 1.3.2.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Share this post


Link to post
Share on other sites
Posted (edited)

You could use Scriptomatic to create the code you need to adjust the data from WMI to your needs.

Example:

Spoiler
; 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_Printer", "WQL", _
                                          $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

If IsObj($colItems) then
   For $objItem In $colItems
      $Output = $Output & "Attributes: " & $objItem.Attributes & @CRLF
      $Output = $Output & "Availability: " & $objItem.Availability & @CRLF
      $strAvailableJobSheets = $objItem.AvailableJobSheets(0)
      $Output = $Output & "AvailableJobSheets: " & $strAvailableJobSheets & @CRLF
      $Output = $Output & "AveragePagesPerMinute: " & $objItem.AveragePagesPerMinute & @CRLF
      $strCapabilities = $objItem.Capabilities(0)
      $Output = $Output & "Capabilities: " & $strCapabilities & @CRLF
      $strCapabilityDescriptions = $objItem.CapabilityDescriptions(0)
      $Output = $Output & "CapabilityDescriptions: " & $strCapabilityDescriptions & @CRLF
      $Output = $Output & "Caption: " & $objItem.Caption & @CRLF
      $strCharSetsSupported = $objItem.CharSetsSupported(0)
      $Output = $Output & "CharSetsSupported: " & $strCharSetsSupported & @CRLF
      $Output = $Output & "Comment: " & $objItem.Comment & @CRLF
      $Output = $Output & "ConfigManagerErrorCode: " & $objItem.ConfigManagerErrorCode & @CRLF
      $Output = $Output & "ConfigManagerUserConfig: " & $objItem.ConfigManagerUserConfig & @CRLF
      $Output = $Output & "CreationClassName: " & $objItem.CreationClassName & @CRLF
      $strCurrentCapabilities = $objItem.CurrentCapabilities(0)
      $Output = $Output & "CurrentCapabilities: " & $strCurrentCapabilities & @CRLF
      $Output = $Output & "CurrentCharSet: " & $objItem.CurrentCharSet & @CRLF
      $Output = $Output & "CurrentLanguage: " & $objItem.CurrentLanguage & @CRLF
      $Output = $Output & "CurrentMimeType: " & $objItem.CurrentMimeType & @CRLF
      $Output = $Output & "CurrentNaturalLanguage: " & $objItem.CurrentNaturalLanguage & @CRLF
      $Output = $Output & "CurrentPaperType: " & $objItem.CurrentPaperType & @CRLF
      $Output = $Output & "Default: " & $objItem.Default & @CRLF
      $strDefaultCapabilities = $objItem.DefaultCapabilities(0)
      $Output = $Output & "DefaultCapabilities: " & $strDefaultCapabilities & @CRLF
      $Output = $Output & "DefaultCopies: " & $objItem.DefaultCopies & @CRLF
      $Output = $Output & "DefaultLanguage: " & $objItem.DefaultLanguage & @CRLF
      $Output = $Output & "DefaultMimeType: " & $objItem.DefaultMimeType & @CRLF
      $Output = $Output & "DefaultNumberUp: " & $objItem.DefaultNumberUp & @CRLF
      $Output = $Output & "DefaultPaperType: " & $objItem.DefaultPaperType & @CRLF
      $Output = $Output & "DefaultPriority: " & $objItem.DefaultPriority & @CRLF
      $Output = $Output & "Description: " & $objItem.Description & @CRLF
      $Output = $Output & "DetectedErrorState: " & $objItem.DetectedErrorState & @CRLF
      $Output = $Output & "DeviceID: " & $objItem.DeviceID & @CRLF
      $Output = $Output & "Direct: " & $objItem.Direct & @CRLF
      $Output = $Output & "DoCompleteFirst: " & $objItem.DoCompleteFirst & @CRLF
      $Output = $Output & "DriverName: " & $objItem.DriverName & @CRLF
      $Output = $Output & "EnableBIDI: " & $objItem.EnableBIDI & @CRLF
      $Output = $Output & "EnableDevQueryPrint: " & $objItem.EnableDevQueryPrint & @CRLF
      $Output = $Output & "ErrorCleared: " & $objItem.ErrorCleared & @CRLF
      $Output = $Output & "ErrorDescription: " & $objItem.ErrorDescription & @CRLF
      $strErrorInformation = $objItem.ErrorInformation(0)
      $Output = $Output & "ErrorInformation: " & $strErrorInformation & @CRLF
      $Output = $Output & "ExtendedDetectedErrorState: " & $objItem.ExtendedDetectedErrorState & @CRLF
      $Output = $Output & "ExtendedPrinterStatus: " & $objItem.ExtendedPrinterStatus & @CRLF
      $Output = $Output & "Hidden: " & $objItem.Hidden & @CRLF
      $Output = $Output & "HorizontalResolution: " & $objItem.HorizontalResolution & @CRLF
      $Output = $Output & "InstallDate: " & WMIDateStringToDate($objItem.InstallDate) & @CRLF
      $Output = $Output & "JobCountSinceLastReset: " & $objItem.JobCountSinceLastReset & @CRLF
      $Output = $Output & "KeepPrintedJobs: " & $objItem.KeepPrintedJobs & @CRLF
      $strLanguagesSupported = $objItem.LanguagesSupported(0)
      $Output = $Output & "LanguagesSupported: " & $strLanguagesSupported & @CRLF
      $Output = $Output & "LastErrorCode: " & $objItem.LastErrorCode & @CRLF
      $Output = $Output & "Local: " & $objItem.Local & @CRLF
      $Output = $Output & "Location: " & $objItem.Location & @CRLF
      $Output = $Output & "MarkingTechnology: " & $objItem.MarkingTechnology & @CRLF
      $Output = $Output & "MaxCopies: " & $objItem.MaxCopies & @CRLF
      $Output = $Output & "MaxNumberUp: " & $objItem.MaxNumberUp & @CRLF
      $Output = $Output & "MaxSizeSupported: " & $objItem.MaxSizeSupported & @CRLF
      $strMimeTypesSupported = $objItem.MimeTypesSupported(0)
      $Output = $Output & "MimeTypesSupported: " & $strMimeTypesSupported & @CRLF
      $Output = $Output & "Name: " & $objItem.Name & @CRLF
      $strNaturalLanguagesSupported = $objItem.NaturalLanguagesSupported(0)
      $Output = $Output & "NaturalLanguagesSupported: " & $strNaturalLanguagesSupported & @CRLF
      $Output = $Output & "Network: " & $objItem.Network & @CRLF
      $strPaperSizesSupported = $objItem.PaperSizesSupported(0)
      $Output = $Output & "PaperSizesSupported: " & $strPaperSizesSupported & @CRLF
      $strPaperTypesAvailable = $objItem.PaperTypesAvailable(0)
      $Output = $Output & "PaperTypesAvailable: " & $strPaperTypesAvailable & @CRLF
      $Output = $Output & "Parameters: " & $objItem.Parameters & @CRLF
      $Output = $Output & "PNPDeviceID: " & $objItem.PNPDeviceID & @CRLF
      $Output = $Output & "PortName: " & $objItem.PortName & @CRLF
      $strPowerManagementCapabilities = $objItem.PowerManagementCapabilities(0)
      $Output = $Output & "PowerManagementCapabilities: " & $strPowerManagementCapabilities & @CRLF
      $Output = $Output & "PowerManagementSupported: " & $objItem.PowerManagementSupported & @CRLF
      $strPrinterPaperNames = $objItem.PrinterPaperNames(0)
      $Output = $Output & "PrinterPaperNames: " & $strPrinterPaperNames & @CRLF
      $Output = $Output & "PrinterState: " & $objItem.PrinterState & @CRLF
      $Output = $Output & "PrinterStatus: " & $objItem.PrinterStatus & @CRLF
      $Output = $Output & "PrintJobDataType: " & $objItem.PrintJobDataType & @CRLF
      $Output = $Output & "PrintProcessor: " & $objItem.PrintProcessor & @CRLF
      $Output = $Output & "Priority: " & $objItem.Priority & @CRLF
      $Output = $Output & "Published: " & $objItem.Published & @CRLF
      $Output = $Output & "Queued: " & $objItem.Queued & @CRLF
      $Output = $Output & "RawOnly: " & $objItem.RawOnly & @CRLF
      $Output = $Output & "SeparatorFile: " & $objItem.SeparatorFile & @CRLF
      $Output = $Output & "ServerName: " & $objItem.ServerName & @CRLF
      $Output = $Output & "Shared: " & $objItem.Shared & @CRLF
      $Output = $Output & "ShareName: " & $objItem.ShareName & @CRLF
      $Output = $Output & "SpoolEnabled: " & $objItem.SpoolEnabled & @CRLF
      $Output = $Output & "StartTime: " & WMIDateStringToDate($objItem.StartTime) & @CRLF
      $Output = $Output & "Status: " & $objItem.Status & @CRLF
      $Output = $Output & "StatusInfo: " & $objItem.StatusInfo & @CRLF
      $Output = $Output & "SystemCreationClassName: " & $objItem.SystemCreationClassName & @CRLF
      $Output = $Output & "SystemName: " & $objItem.SystemName & @CRLF
      $Output = $Output & "TimeOfLastReset: " & WMIDateStringToDate($objItem.TimeOfLastReset) & @CRLF
      $Output = $Output & "UntilTime: " & WMIDateStringToDate($objItem.UntilTime) & @CRLF
      $Output = $Output & "VerticalResolution: " & $objItem.VerticalResolution & @CRLF
      $Output = $Output & "WorkOffline: " & $objItem.WorkOffline & @CRLF
   Next
   ConsoleWrite($Output)
   FileWrite(@TempDir & "\Win32_Printer.TXT", $Output )
   Run(@Comspec & " /c start " & @TempDir & "\Win32_Printer.TXT" )
Else
   Msgbox(0,"WMI Output","No WMI Objects Found for class: " & "Win32_Printer" )
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 water

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2020-09-05 - Version 1.5.1.1) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2020-06-27 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (NEW 2020-06-27 - Version 1.3.2.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
Task Scheduler (2019-12-03 - Version 1.5.1.0) - Download - General Help & Support - Wiki

Tutorials:
ADO - Wiki, WebDriver - Wiki

 

Share this post


Link to post
Share on other sites
Posted (edited)

In addition to all of the optimization suggestions, you have fundamental issues, the return from the run command is the PID not the STDOUT.   You can then use the PID to read the output of the command.  But WMI is already slow without asking powershell to ask WMI.

;#RequireAdmin

#include <Constants.au3>
#include <Array.au3>

$pidPrintlist = Run("powershell.exe get-printer" , @SystemDir , @SW_HIDE, $STDOUT_CHILD)
ProcessWaitClose($pidPrintlist)
$out = StdoutRead($pidPrintlist)

_ArrayDisplay(stringsplit($out , @CR , 2))

 

yeah, pretty much what @Deye said at the same time he said it :)

Edited by iamtheky

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

Share this post


Link to post
Share on other sites

WMI streamlines the process, don't you think ?

#include <Array.au3>

Local $aList = GetPrinterList()
_ArrayDisplay($aList)

Func GetPrinterList()
  Local $objWMIService = ObjGet("winmgmts:\\" & @ComputerName & "\root\CIMV2")
  Local $colItems = $objWMIService.ExecQuery('SELECT * FROM Win32_Printer')
  If Not IsObj($colItems) Then Exit MsgBox(0, "", "Not an object")
  If Not $colItems.count Then Return 0 ; No Printer found
  Local $aPrinter[$colItems.count][10], $i = 0
  For $oItem In $colItems
    $aPrinter[$i][0] = $oItem.Name
    $aPrinter[$i][1] = $oItem.DriverName
    $aPrinter[$i][2] = $oItem.PortName
    $aPrinter[$i][3] = $oItem.Shared
    $aPrinter[$i][4] = $oItem.ShareName
    $aPrinter[$i][5] = $oItem.Published
    $aPrinter[$i][6] = $oItem.Local
    $aPrinter[$i][7] = $oItem.Location
    $aPrinter[$i][8] = $oItem.DeviceID
    $aPrinter[$i][9] = $oItem.DriverName
    $i += 1
  Next
  Return $aPrinter
EndFunc   ;==>GetPrinterList

You can add as many informations to the array as needed and it works with almost all OS versions.

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

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...