logo
down
shadow

Invoke PowerShell script from c# in runspace and get line number where error occured


Invoke PowerShell script from c# in runspace and get line number where error occured

By : user3864673
Date : January 10 2021, 01:47 PM
Hope that helps I have some PowerShell hosts in C# from where I execute PowerShell script code. The code below is from a host in an Add0In for Visual Studio. Problem is that if an error occurs in the PowerShell script code that I don't know the file and line number of the PowerShell script file where the error occured. , This should get you in the right place:
code :


Share : facebook icon twitter icon
Running same powershell script multiple asynchronous times with separate runspace

Running same powershell script multiple asynchronous times with separate runspace


By : Josh
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have absolutely no clue what you're trying to do, and to be honest, I don't even understand the question. However, if you're trying to run several instances of the same script asynchronously in different runspaces (for reasons only you know best, sorry) then I can point you to a script I wrote some time ago. This is for v2 ctp3 but works fine in v2 RTM (which is current):
http://www.nivot.org/2009/01/22/CTP3TheRunspaceFactoryAndPowerShellAccelerators.aspx
Using Dispatcher Invoke with a Runspace in Powershell

Using Dispatcher Invoke with a Runspace in Powershell


By : Jaydeep
Date : March 29 2020, 07:55 AM
wish help you to fix your issue There are a couple of problems with your code that are probably causing the erratic error. Firstly, are you running the code from the Powershell_ISE or from the powershell console? Also, are you running the script in two parts with the dispatcher calls being made from the console after the window is open or as a single script including the dispatcher calls? If you are running the code as as single script then the problem is that the "BeginInvoke" runs the script within its own runspace in a separate thread. Before the window is properly created by this thread the main thread is already trying to set the value of title and the textbox.
If you were to split the code in two parts, ie call everything up to begininvoke in one script and then make the dispatcher calls in the main script the code will also have problems as you need to make the hashtable global.
code :
$Global:uiHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"          
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("uiHash",$Global:uiHash)



$psCmd = [PowerShell]::Create().AddScript({   
    $Global:uiHash.Error = $Error
    Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase
    $xaml = @"
    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
        Width = "650" Height = "800" ShowInTaskbar = "True">
        <Grid>
        <TextBox x:Name = "textbox" Height = "400" Width = "600" TextWrapping="Wrap"/>
        </Grid>
    </Window>
"@
   # $reader=(New-Object System.Xml.XmlNodeReader $xaml)
    $Global:uiHash.Window=[Windows.Markup.XamlReader]::Parse($xaml )
    $Global:uiHash.TextBox = $Global:uiHash.window.FindName("textbox")
    $Global:uiHash.TextBox.Text = "Window Creation Thread Id: $([System.Threading.Thread]::CurrentThread.ManagedThreadId.ToString()) Time: $([System.Diagnostics.Stopwatch]::GetTimestamp()) `r`n" 
    $Global:uiHash.Window.ShowDialog() | out-null
})
$psCmd.Runspace = $newRunspace
$time1 = " Time before beginInvoke: $([System.Diagnostics.Stopwatch]::GetTimestamp()) `r`n"
$handle = $psCmd.BeginInvoke()

#-----------------------------------------
$time2 = " Time after beginInvoke: $([System.Diagnostics.Stopwatch]::GetTimestamp()) `r`n"
#Using the Dispatcher to send data from another thread to UI thread
Start-Sleep -Milliseconds 100
#Update-Window -Title ("Services on {0}" -f $Env:Computername)
$threadId = " Dispatcher Call Thread Id: $([System.Threading.Thread]::CurrentThread.ManagedThreadId.ToString())  Time: $([System.Diagnostics.Stopwatch]::GetTimestamp())`r`n "

$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.TextBox.AppendText($time1)},"Normal")
$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.TextBox.AppendText($time2)},"Normal")
$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.TextBox.AppendText($threadId)},"Normal")
$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.Window.Title = "$($env:ComputerName)"},"Normal")
Multi-Runspace PowerShell/XAML script crashing on button click

Multi-Runspace PowerShell/XAML script crashing on button click


By : Sergi C
Date : March 29 2020, 07:55 AM
To fix the issue you can do I was never able to completely figure this out, but I did find a good workaround for me. I put the main chunk of my script in a Do-Until loop, and made the button click change a global variable I created. That broke it out of the loop, closed the window, and let all the finishing tasks run without crashing.
code :
#$Global:uihash is my synchronized hashtable.

#Create synchronized hash table variable
$Global:uiHash.Add(“End”,$false)

 #Create Click Event 
$Global:uihash.Button.add_click({if([System.Windows.Forms.MessageBox]::Show 
("Yes or No?", "Question",[System.Windows.Forms.MessageBoxButtons]::OKCancel) -eq "OK")
{$Global:uiHash.End = $true}

Do {A whole bunch of stuff}
Until ($global:uiHash.end -eq $true)

#Close the window
$Global:uiHash.Window.Dispatcher.Invoke([action]{$Global:uiHash.Window.close() },"Normal")
#Then process the rest of the script
Powershell invoke script in new process and within the same runspace

Powershell invoke script in new process and within the same runspace


By : Clint Ast
Date : March 29 2020, 07:55 AM
this will help What you describe is impossible - a single runspace cannot span multiple processes.
Allow me to demonstrate the relevant hierarchical relationships with this state of the art graphic I whipped up in mspaint:
How does a C# runspace/pipeline execute a powershell script?

How does a C# runspace/pipeline execute a powershell script?


By : Ramesh Dandu
Date : March 29 2020, 07:55 AM
wish help you to fix your issue It's not a complete explanation of how the runspace works, but I've written a blog post covering the main bits.
Also a snippet from one of the msdn pages on how powershell works:
Related Posts Related Posts :
  • Looking for a .Net ORM
  • Cost of SortedDictionary.Count
  • All possible combinations of n items selected randomly from a set of x items (algorithm)
  • Displaying process percentage on DOS screen
  • C# Importing Large Volume of Data from CSV to Database
  • c# control location precision
  • Printing to Zebra printer gives faint and blurry images
  • How to avoid stepping into dll code file?
  • Programmaticaly prevent Vista desktop search (WDS) from indexing pst files placed on mapped network drives
  • Is there anyway to reduce IsolatedStorage capacity in Silverlight?
  • C#: How to print a unicode string to console?
  • Frequency Table with Random Values
  • My Visual Studio 2008 web application keeps throwing a .Net error when I first run it, but refreshing fixes it
  • TCP Connection Creation and Closing Event Hooking
  • Find changed properties of a class
  • C#: Object with custom marshaller not containing data after PInvoke call
  • Version Control System with API. Need to get metrics
  • Performance comparison of Dictionaries
  • How to get process name and title of the top window on Windows / C#
  • How to save the ListView contents to a text file?
  • Why not .NET-style delegates rather than closures in Java?
  • Get CLSID by PIA interface Type
  • Visual Studio 2008 C# - Recover solution from application manifest possible?
  • Is a good practice to initialize private data members from within ctor by calling the associated properties instead of t
  • Inserting into a bitstream
  • How do you write byte[] array using log4.net
  • Clickonce + .NET client profile 4 framework + offline
  • Show form that showDialog from mainForm won't block it, but closing mainForm will close it
  • Developing a GPS car tracking system
  • dynamic log4net appender name?
  • Visual studio formatting issue
  • IndexOutOfRangeException when a stream is a multiple of the buffer size
  • How to deal with calculated values with Dependency Properties on a custom WPF control
  • counting from textbox,asp.net
  • Threading best practice when using SFTP in C#
  • how to load PDF file in website page using C#
  • Parent child class relationship design pattern
  • MessageQueue.BeginReceive() null ref error - c#
  • A C# collection, which behaves like C++ set or priority_queue?
  • Animating WPF buttons from inside a style
  • WPF Grid : GridSplitter event
  • Server 2008 Task Scheduler Mapped Drive Access C#
  • Cast problem with LINQ
  • Combo box Item source = ObservableCollection & I need a '-None-' dummy entry at the top
  • Which GUI control is suitable for this purpose?
  • Trying to access App.config file for mail settings but fails to work
  • How to show html contents with a RichTextBox?
  • FTP monitoring and downloading of new files
  • MEF + Plug-In not updating
  • Efficient handling of super wide, but not so tall, bitmap?
  • .NET 3.0 Unit Testing getting System.MethodAccessException calling .NET 2.0
  • Web Services vs Persistent Sockets
  • How do I dynamically reference incremented properties in C#?
  • Windows Installer (C#) error code 2869
  • Exception "The operation is not valid for the state of the transaction" using TransactionScope
  • Tools for listing database accesses from .NET code
  • Excel VSTO set selection
  • Creating a subscription based website in ASP.NET
  • Merging Resources Dictionaries
  • How to launch a .bat file in a C# windows Service project
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk