0

PFB the code. I have tried to capture the output directly, but no luck. Then I tried to put the output into a log file and later capture the text from log file. That also didn't work. could you please tell me what is wrong in this.

[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

$Form = New-Object System.Windows.Forms.Form
$Form.width = 600
$Form.height = 600
$Form.Text = "Form Title"

$Form.startposition = "centerscreen"

$Form.FormBorderStyle= [System.Windows.Forms.FormBorderStyle]::Fixed3D

Function ShowProcess(){
    $Textbox1 = New-Object System.Windows.Forms.RichTextBox
    #$text = Get-Process | Out-String
    $Textbox1.Size = New-Object System.Drawing.Size(550, 400)
    $Textbox1.Multiline = $true
    $Textbox1.Font ="Lucida Console"
    $Textbox1.WordWrap = $false

    Start-Transcript -Path C:\Mywork\log.txt
    &C:\Mywork\Script\test.bat
    Stop-Transcript           

    $Textbox1.Text = Get-Content C:\Mywork\log.txt
    $Form.Controls.Add($Textbox1)
}

$button1 = New-Object System.Windows.Forms.Button
$button1.Location = New-Object System.Drawing.Point(350, 450)
$button1.Size = New-Object System.Drawing.Size(120, 100)
$button1.Text = "Press"
$button1.FlatAppearance.BorderSize=0
$Form.Controls.Add($button1)
$button1.Add_Click({ShowProcess})

$Form.ShowDialog()

Below is the content of test.bat:

PS C:\Users\sghosh> Get-Content C:\Mywork\Script\test.bat
tree
pause
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Suman Ghosh
  • 1,317
  • 3
  • 12
  • 18
  • `start-process cmd -argumentlist "/c C:\Mywork\Script\test.bat"`? Optionally toss in `-RedirectStandardOutput` to save to a file. – 4c74356b41 Nov 29 '16 at 09:34

1 Answers1

1

Remove pause from your batch file. It prompts the user for confirmation, but since you're running the script non-interactively from your PowerShell code it causes the batch script to hang. Thus no batch output ever gets to the form.

Change test.bat to this:

@echo off
tree

and change these lines in your PowerShell script

Start-Transcript -Path C:\Mywork\log.txt
&C:\Mywork\Script\test.bat
Stop-Transcript           

$Textbox1.Text = Get-Content C:\Mywork\log.txt

to this:

$Textbox1.Text = & C:\Mywork\Script\test.bat *>&1 | Out-String
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • is there any way to display the output dynamically? suppose if I put below command to batch file, first it will run then at the end it is displaying complete output. cd / dir /s I want to display output while it is running. please let me know if there is anyway to do it. – Suman Ghosh Nov 30 '16 at 02:19
  • You could run the external command as a job and periodically update the textbox with output from that job. See [here](http://stackoverflow.com/a/39641450/1630171). – Ansgar Wiechers Nov 30 '16 at 10:15