-
Notifications
You must be signed in to change notification settings - Fork 163
RunSpaces In PowerShell
The concept of Runspaces is built upon the .NET threading model, which allows PowerShell to execute multiple scripts or commands in parallel. This is achieved by creating separate instances of the PowerShell engine, each running in its own thread, thus not interfering with the primary PowerShell session or other Runspaces.
Utilizing Runspaces effectively requires an understanding of threading and synchronization, as data sharing between threads must be handled carefully to avoid race conditions and ensure thread safety. The synchronized hashtable, as demonstrated in the provided script, is a prime example of a thread-safe data structure that facilitates communication between Runspaces.
# Display the number of the runspaces before operation
(Get-Runspace).count
# Create a synchronized hashtable for inter-runspace communication
$SyncHash = [System.Collections.Hashtable]::Synchronized(@{})
# Create a new runspace
$GUIRunSpace = [System.Management.Automation.RunSpaces.RunSpaceFactory]::CreateRunSpace()
$GUIRunSpace.ApartmentState = 'STA'
$GUIRunSpace.ThreadOptions = 'ReuseThread'
# Create a new PowerShell object
$GUIPowerShell = [System.Management.Automation.PowerShell]::Create()
# Assign the runspace to the PowerShell object's Runspace property
$GUIPowerShell.RunSpace = $GUIRunSpace
# Open the runspace
$GUIRunSpace.Open()
# Make the synchronized hashtable available in the runspace
$GUIRunSpace.SessionStateProxy.SetVariable('SyncHash', $SyncHash)
# Add a script to the PowerShell object so that it can run inside the runspace
[System.Void]$GUIPowerShell.AddScript({
Write-Output -InputObject '1st output'
})
# Invoke the PowerShell object asynchronously and store the resulting handle in a variable
$GUIAsyncObject = $GUIPowerShell.BeginInvoke()
# End the asynchronous operation and display the output
$GUIPowerShell.EndInvoke($GUIAsyncObject)
# Add another script to the PowerShell object to run, replacing the previous script added to the object.
# The runspace is still open
[System.Void]$GUIPowerShell.AddScript({
Write-Output -InputObject '2nd output'
})
# Again invoke the PowerShell object asynchronously and store the resulting handle in a variable
$GUIAsyncObject = $GUIPowerShell.BeginInvoke()
# End the asynchronous operation and display the output
$GUIPowerShell.EndInvoke($GUIAsyncObject)
# Close and dispose of the runspace and PowerShell object
$GUIPowerShell.Dispose()
$GUIRunSpace.Close()
$GUIRunSpace.Dispose()
# Display the number of the runspaces after operation
(Get-Runspace).count
This example demonstrates how to create a runspace that runs a GUI thread asynchronously and based on the events happening in the GUI thread, different actions are taken in the parent thread. The parent thread is responsible for handling the events generated by the GUI thread, such as button clicks, window closures, and errors. At the end of the operation, the runspace is closed and disposed of, ensuring no leftover runspaces or jobs.
# Get the count of the RunSpaces before the operation to compare it with the count after the operation
(Get-Runspace).count
# Creating a synchronized hashtable to store shared data between the two runspaces
$SyncedHashtable = [System.Collections.Hashtable]::Synchronized(@{})
# Define the XAML code for WPF GUI
$SyncedHashtable.XAML = [System.Xml.XmlDocument]@'
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MaxWidth="600" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight">
<Button Name="Button1" Content="Press Me"/>
</Window>
'@
# Assigning the parent runspace's host to the $SyncedHashtable.Host property.
# It will be used to detect or rather, refer back to the parent runspace from inside of the GUI runspace.
# This is crucial for the event communication between the two runspaces.
$SyncedHashtable.Host = $Host
$RunSpace = [System.Management.Automation.RunSpaces.RunSpaceFactory]::CreateRunspace()
$RunSpace.ApartmentState = 'STA'
$RunSpace.ThreadOptions = 'ReuseThread'
$RunSpace.Open()
$RunSpace.SessionStateProxy.SetVariable('SyncedHashtable', $SyncedHashtable)
$PowerShell = [System.Management.Automation.PowerShell]::Create()
$PowerShell.Runspace = $RunSpace
[System.Void]$PowerShell.AddScript({
try {
# Add the required assembly for WPF
Add-Type -AssemblyName PresentationFramework
$Reader = New-Object -TypeName 'System.Xml.XmlNodeReader' -ArgumentList $SyncedHashtable.XAML
$SyncedHashtable.Window = [System.Windows.Markup.XamlReader]::Load( $Reader )
# Find the button object in the XAML
[System.Windows.Controls.Button]$SyncedHashtable.Button1 = $SyncedHashtable.Window.FindName('Button1')
# Add a click event to the button
$SyncedHashtable.Button1.Add_Click({
$SyncedHashtable.Host.Runspace.Events.GenerateEvent('Button1Clicked', $null, 'Button Click Event', $null)
})
# Add a closed event to the window
$SyncedHashtable.Window.Add_Closed({
$SyncedHashtable.Host.Runspace.Events.GenerateEvent('WindowClosed', $null, 'Sender', $null)
})
# Throw a dummy error to test the async error handling
# throw 'Test Error'
# Show the GUI
$SyncedHashtable.Window.ShowDialog()
}
catch {
$SyncedHashtable.ErrorMessage = $_.Exception.Message
$SyncedHashtable.Host.Runspace.Events.GenerateEvent('ErrorsOccurred', $null, $null, $null)
}
})
# Start the GUI PowerShell instance asynchronously
$AsyncHandle = $PowerShell.BeginInvoke()
# You can inspect the events that the 'Register-EngineEvent' cmdlet receives here
# $Button1ClickedEvent = Get-Event -SourceIdentifier 'Button1Clicked'
# $WindowClosedEvent = Get-Event -SourceIdentifier 'WindowClosed'
# $ErrorsOccurredEvent = Get-Event -SourceIdentifier 'ErrorsOccurred'
# Register an event for the button click
$Button1ClickedSub = Register-EngineEvent -SourceIdentifier 'Button1Clicked' -Action {
param (
$Sender
)
Write-Host -Object $Sender
}
# Register an event for the window closure
$WindowClosedSub = Register-EngineEvent -SourceIdentifier 'WindowClosed' -Action {
param (
$Sender
)
Write-Host -Object 'The GUI has been closed.'
# Remove the event subscription and the job for the button click event since the GUI Windows was closed
Unregister-Event -SubscriptionId $Button1ClickedSub.Id
Remove-Job -InstanceId $Button1ClickedSub.InstanceId
# Remove the event subscription and the job for the errors occurred event since the GUI Windows was closed
Unregister-Event -SubscriptionId $ErrorsOccurredSub.Id
Remove-Job -InstanceId $ErrorsOccurredSub.InstanceId
# Close the runspace and dispose of it
$RunSpace.Close()
$RunSpace.dispose()
# Remove the event subscription and the job of the current event subscription
Unregister-Event -SubscriptionId $WindowClosedSub.Id
Remove-Job -InstanceId $WindowClosedSub.InstanceId
}
# Register an event for the errors occurred in the GUI RunSpace
$ErrorsOccurredSub = Register-EngineEvent -SourceIdentifier 'ErrorsOccurred' -Action {
Write-Host -Object "Errors Occurred: $($SyncedHashtable.errorMessage)"
}
# Get the count of the runspaces after the operation to see there is no leftover runspace
(Get-Runspace).count
# There won't be any leftover jobs or event subscriptions once the GUI window is closed
# Get-EventSubscriber
# Get-Job
- Create AppControl Policy
- Create Supplemental Policy
- System Information
- Configure Policy Rule Options
- Simulation
- Allow New Apps
- Build New Certificate
- Create Policy From Event Logs
- Create Policy From MDE Advanced Hunting
- Create Deny Policy
- Merge App Control Policies
- Deploy App Control Policy
- Get Code Integrity Hashes
- Get Secure Policy Settings
- Update
- Sidebar
- Introduction
- App Control for Lightly Managed Devices
- App Control for Fully managed device - Variant 1
- App Control for Fully managed device - Variant 2
- App Control for Fully managed device - Variant 3
- App Control for Fully managed device - Variant 4
- App Control Notes
- How to Create and Deploy a Signed App Control Policy
- Fast and Automatic Microsoft Recommended Driver Block Rules updates
- App Control policy for BYOVD Kernel mode only protection
- EKUs in App Control for Business Policies
- App Control Rule Levels Comparison and Guide
- Script Enforcement and PowerShell Constrained Language Mode in App Control Policies
- How to Use Microsoft Defender for Endpoint Advanced Hunting With App Control
- App Control Frequently Asked Questions (FAQs)
- Create Bootable USB flash drive with no 3rd party tools
- Event Viewer
- Group Policy
- How to compact your OS and free up extra space
- Hyper V
- Overrides for Microsoft Security Baseline
- Git GitHub Desktop and Mandatory ASLR
- Signed and Verified commits with GitHub desktop
- About TLS, DNS, Encryption and OPSEC concepts
- Things to do when clean installing Windows
- Comparison of security benchmarks
- BitLocker, TPM and Pluton | What Are They and How Do They Work
- How to Detect Changes in User and Local Machine Certificate Stores in Real Time Using PowerShell
- Cloning Personal and Enterprise Repositories Using GitHub Desktop
- Only a Small Portion of The Windows OS Security Apparatus
- Rethinking Trust: Advanced Security Measures for High‐Stakes Systems
- Clean Source principle, Azure and Privileged Access Workstations
- How to Securely Connect to Azure VMs and Use RDP
- Basic PowerShell tricks and notes
- Basic PowerShell tricks and notes Part 2
- Basic PowerShell tricks and notes Part 3
- Basic PowerShell tricks and notes Part 4
- Basic PowerShell tricks and notes Part 5
- How To Access All Stream Outputs From Thread Jobs In PowerShell In Real Time
- PowerShell Best Practices To Follow When Coding
- How To Asynchronously Access All Stream Outputs From Background Jobs In PowerShell
- Powershell Dynamic Parameters and How to Add Them to the Get‐Help Syntax
- RunSpaces In PowerShell
- How To Use Reflection And Prevent Using Internal & Private C# Methods in PowerShell