Sign in to follow this  
Followers 0
blckpythn

StdoutRead a Powershell window.

25 posts in this topic

I have a script that executes powershell commands to interact with Office 365(Microsoft hosted Exchange service).

I want to hide the powershell window and interpret the output silently, so that non-savvy users can reset passwords and such without having to learn powershell or understand its errors.

However, when I use:

Func RunCommand($commandtorun)
    $output = ""
    If WinExists("Administrator:") Then WinActivate("Administrator:")
    Send($commandtorun & "{ENTER}")
    While 1
        $output &= StdoutRead($pwshell)
        If @error Then ExitLoop
    WEnd
    MsgBox(0, "stdoutread", $output)
EndFunc   ;==>RunCommand

It doesn't exit the loop until I close the powershell window.(by design I believe)

Is there another way to return just a particular command's output?

Also, if I use $Stdin_child, the powershell window doesn't display its prompt for a command until I close my script.

Is that by design also?

Share this post


Link to post
Share on other sites



How are you starting the powershell command window? The Run command allows you to read the StdIO streams, have you tried that?


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

How are you starting the powershell command window? The Run command allows you to read the StdIO streams, have you tried that?

 

I'm starting it with the following and having trouble with the stdoutread command.

$pwshell = Run(@SystemDir & '\WindowsPowerShell\v1.0\powershell.exe  -NoExit -Command "Import-Module MSOnline"', "", @SW_SHOW, $STDERR_CHILD + $STDOUT_CHILD)

The issue with powershell not showing the prompt is when I add

+ $stdin_child

after

$stderr_child + $stdout_child

I have not tried anything else.

Edited by blckpythn

Share this post


Link to post
Share on other sites

To keep PowerShell hidden maybe the >COM interface helps.


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

To keep PowerShell hidden maybe the >COM interface helps.

Keeping it hidden isn't the issue, I haven't even gotten to that yet.

I'm just trying to read the output so that when I do hide it, I can see if there was an error with the command and let the end-user know.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Little update: Even though it doesn't show the prompt when using $STDIN_CHILD, I can successfully use the StdinWrite() command.

However, StdoutRead still isn't getting any data or exiting its loop.

Edited by blckpythn

Share this post


Link to post
Share on other sites

>The post here has an example of running a powershell command in AutoIt.

Share this post


Link to post
Share on other sites

I have a working example I will post on Monday.


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

That's the way I grab the PS output:

$sCMD = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command . " & _
            "'D:\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Enable-Mailbox -Identity " & _
            $Kurzzeichen & " -Alias " & $Kurzzeichen & " -Database " & $sEXDatabase & $sSMTPAddress
    $pid = Run($sCMD, @SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD + $STDERR_CHILD)
    StdinWrite($pid, @CRLF)
    StdinWrite($pid)
    ; Ausgabe von STDOUT
    $sSTDOUT = ""
    While 1
        $sOutput = StdoutRead($pid)
        If @error Then ExitLoop
        If $sOutput <> "" Then $sSTDOUT = $sSTDOUT & @CRLF & $sOutput
    WEnd
    ; Ausgabe von STDERR
    $sSTDERR = ""
    While 1
        $sOutput = StderrRead($pid)
        If @error Then ExitLoop
        If $sOutput <> "" Then $sSTDERR = $sSTDERR & @CRLF & $sOutput
    WEnd

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

Both of your examples require powershell to exit in order to return the stream, is there a way to return it without exiting powershell?

Share this post


Link to post
Share on other sites

What I posted is only one example and it should grab StdOut and StdErr as soon as Run returned. Try this:

$sCMD = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command . " & _
            "'D:\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Enable-Mailbox -Identity " & _
            $Kurzzeichen & " -Alias " & $Kurzzeichen & " -Database " & $sEXDatabase & $sSMTPAddress
    $pid = Run($sCMD, @SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD + $STDERR_CHILD)
    StdinWrite($pid, @CRLF)
    StdinWrite($pid)
    ; Ausgabe von STDOUT
    $sSTDOUT = ""
    While 1
        $sOutput = StdoutRead($pid)
        If @error Then ExitLoop
        If $sOutput <> "" Then 
          $sSTDOUT = $sSTDOUT & @CRLF & $sOutput
          ConsoleWrite($sOutput & @CRLF)
        EndIf
    WEnd
    ; Ausgabe von STDERR
    $sSTDERR = ""
    While 1
        $sOutput = StderrRead($pid)
        If @error Then ExitLoop
        If $sOutput <> "" Then 
            $sSTDERR = $sSTDERR & @CRLF & $sOutput
            ConsoleWrite($sOutput & @CRLF)
        EndIf
    WEnd

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

 

What I posted is only one example and it should grab StdOut and StdErr as soon as Run returned. Try this:...

The thing is, I'm running powershell with -NoExit because I'm having to authenticate with O365 and that involves running a few commands sequentially.

Then I have to leave that session open to let the user pass commands to. So the proccess doesn't send an @error to StderrRead. Therefor, it doesn't return anything until after the session is ended.

This doesn't help me because I need the errors DURING the session.

I have to run

$LiveCred = Get-Credential <--they need to provide their credentials or I will have them input it earlier and automate it.

Then $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic –AllowRedirection

Then Import-PSSession $Session

Then Connect-MsolService <--again, credentials needed.

After all that, they can start resetting passwords and whatnot, but I want to monitor for errors WHILE powershell is still open.

 

Am I not making sense or doing it stupidly?

Share this post


Link to post
Share on other sites

Makes sense.

In this case I would have a look at the PS COM interface as I have posted before. Seems to allow to send command by command and return the result in a buffer.


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

Makes sense.

In this case I would have a look at the PS COM interface as I have posted before. Seems to allow to send command by command and return the result in a buffer.

I followed the link in that post but cannot find the ActiveXPoSH download.

Share this post


Link to post
Share on other sites

Did you register an account as described >here?


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

#16 ·  Posted (edited)

Did you register an account as described >here?

Sure did. From the post it looks like it is part of PrimalScript 2012, but that is not free. I'm downloading the "Try It" or trial... we'll see.

Edited by blckpythn

Share this post


Link to post
Share on other sites

Then I suggest to PM ptrex because he is the author of the OP.


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

#18 ·  Posted (edited)

Found it by itself here, account still required.

I also update the original post since it was so hard to find. Sorry if that counts as necro-posting.

ActiveXPosh.zip  <- only one that worked for me on Win7_x86

ActivexPoshx86.exe

ActiveXPoshx64.exe

Edited by blckpythn

Share this post


Link to post
Share on other sites

Don't think it counts as recro-posting. It is just helpful for others :)


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

Got it!

Using ActiveXPosh, the example of:

Func ExecuteCMD($sPSCmd)
 Dim $outtext
 ; Set the $OUTPUT mode to $BUFFER
 $ActiveXPosh.OutputMode = $OUTPUT_BUFFER
 $ActiveXPosh.Execute($sPSCmd)

 ; Get the $OUTPUT line by line and add it to a variable
 For $str In $ActiveXPosh.OUTPUT()
   $outtext =  $outtext & $str
  $outtext =  $outtext & @CRLF
 Next

 ; Alternatively you can get the $OUTPUT as a single String
; $outtext = $ActiveXPosh.OutputString
 ConsoleWrite ($outtext & @CR)

 $ActiveXPosh.ClearOutput() ; Empty the $OUTPUT $BUFFER
EndFunc

Works perfectly for getting the return of individual commands without "exiting" the session.

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

  • Similar Content

    • 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.
       
    • OGA
      By OGA
      Hi, I'm new.
      Anyways, I'm using the RunBinary.au3 script by trancexx and I want to re-direct the STDOUT of the "child process" back to the autoit script that launches it. I'm attempting to do so using named pipes. If its possible to use StdoutRead instead of namedpipes please let me know. I'm just unsure of how to provide a handle of the childs STDOUT stream to that function. Though DllCall("kernel32.dll", "ptr", "GetStdHandle", "dword", "STD_OUTPUT_HANDLE") seems to get the handle?
      Please excuse any foolish mistakes because I'm new to STDOUT, runbinary and namedpipes. Here's the parts of the code I'm trying to use that are relevent:
      ;~~~Firstly I think I need to make a pipe that's inheritable.. which I may have done wrong Local $_SECURITY_ATTRIBUTES = DllStructCreate("dword Length;" & _ "int lpSecurityDescriptor;" & _ "bool InheritHandle;") ;***Not positive if bool works correctly here? DLLStructSetData($_SECURITY_ATTRIBUTES, "Length", DllStructGetSize($_SECURITY_ATTRIBUTES)) DLLStructSetData($_SECURITY_ATTRIBUTES, "lpSecurityDescriptor", 0) ;***This sets default state; "If the value of this member is NULL, the object is assigned the default security descriptor associated with the access token of the calling process." but I'm unsure if this is what I should use DLLStructSetData($_SECURITY_ATTRIBUTES, "InheritHandle", true);***True = Inheritable(but again I'm not positive the bool works correctly?) Global $hNamedPipe = _NamedPipes_CreateNamedPipe("\\.\pipe\poopp", _;Name 2, _;Direction: 2=both ;I only need 1 direction but I'm just using this for testing 1, _;Flags: 1=no extra instances of pipe are allowed to run 0, _;Security: No ACL Security 0, _;Type: 0=byte 0, _;ReadType: 0=byte 1, _;Wait: 0=Block(wait) 1=No block(no wait) 1, _;Max Instances of pipe allowed 4096, _;out size 4096, _;in size 9000, _;timeout DllStructGetPtr($_SECURITY_ATTRIBUTES));Default=0 which wouldn't make the handle inheritable ;~~~Next I would need to set the STARTUPINFO of the process ;code used by trancexx for the _STARTUPINFO Global $tSTARTUPINFO = DllStructCreate("dword cbSize;" & _ "ptr Reserved;" & _ "ptr Desktop;" & _ "ptr Title;" & _ "dword X;" & _ "dword Y;" & _ "dword XSize;" & _ "dword YSize;" & _ "dword XCountChars;" & _ "dword YCountChars;" & _ "dword FillAttribute;" & _ "dword Flags;" & _ "word ShowWindow;" & _ "word Reserved2;" & _ "ptr Reserved2;" & _ "ptr hStdInput;" & _ "ptr hStdOutput;" & _ "ptr hStdError") ;Attempting to set the values for namedpipe redirection DllStructSetData($tSTARTUPINFO, "Flags", 0x00000100) ;***Flag = STARTF_USESTDHANDLES (I think I set it correctly?) DllStructSetData($tSTARTUPINFO, "hStdOutput", $hNamedPipe) ;***Currently setting the output handle to the SERVER end of the NamePipe I'm creating (which I'm pretty sure is wrong but idk how to use the Client End) ;~~~code used by trancexx for CreateProcess Global $aCall = DllCall("kernel32.dll", "bool", "CreateProcessW", _ "wstr", $sExeModule, _ "wstr", $sCommandLine, _ "ptr", 0, _ "ptr", 0, _ "bool", true, _ ;***changed to inherit handles (not positive I did so correctly) was int 0 before "dword", 4, _ ; CREATE_SUSPENDED ; <- this is essential "ptr", 0, _ "ptr", 0, _ "ptr", DllStructGetPtr($tSTARTUPINFO), _ "ptr", DllStructGetPtr($tPROCESS_INFORMATION)) ;~~~~~Code used in a loop to try to see if anything is being written into the pipe If _IsPressed(35, $hDLL) Then Local $pipeData = _NamedPipes_PeekNamedPipe($hNamedPipe) If @Error Then MsgBox(1,"PipeData Error",@Error & " | " & $pipeData) Else Local $r = _ArrayDisplay($pipeData) If @Error Then MsgBox(1,"Array Error",@Error & " | " & $pipeData) EndIf EndIf  
      I'm not using this exact code cause I changed it around some for the post. I'm mainly wondering how to correctly use the client end of the name pipe? I also had some values I wasn't sure if I set correctly because I don't have experience with com objects. And It seems the process launched needs to be the child?.. Can the process started through the autoitscript can be considered the child process and the script the parent process?
       
      Guides I'm using for this:
      https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
      https://support.microsoft.com/en-us/help/190351/how-to-spawn-console-processes-with-redirected-standard-handles
    • 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)
    • tcox8
      By tcox8
      Hello,
      Currently I am running a script that calls a powershell script. To read the results of that I am reading StdOut. I am parsing things accordingly but unfortunately it doesn't parse correctly all the time and I end up missing parts of the string or other problems. My question then is, what is the best results for reading what is returned when running a powershell script or something similar?
    • WoodGrain
      By WoodGrain
      Hi guys,
      This is probably an obvious one, but I really don't use this command at all so am hoping you can spot my mistake.
      I'm running a powershell script on a schedule with the following script in a function, the function is being called in a loop, but the console process is not closing in the background and I end up with a bunch of console windows running in the background:
      Run(@comspec & ' /k PowerShell.exe -STA -NonInteractive -ExecutionPolicy ByPass -Command "& ''Z:\Powershell\365\GetNextDetails.ps1'' "', "", @SW_HIDE) Thanks!