Recently I came across a situation where I wanted a variable to be available in both the C# context and the PowerShell runspace. This was important because it would make the solution much simpler.
I used three things to make this possible:
- Global variables from PowerShell
- Static classes in .NET
- Compiling .NET code at runtime in PowerShell and using the compiled type directly, or putting it in a DLL and loading it
I can’t share the original code because it’s confidential, so the samples below are small examples of the same methods.
Sharing a variable
A static class holds one object, and a PowerShell global variable points to that same object. The static class gives the object one home for the life of the process. The global variable lets every function and script in the runspace reach it easily.
Because both sides use the same object, a change on one side shows up on the other. Nothing has to be copied or passed between them.
Add-Type -TypeDefinition @'
namespace Automation
{
public class RunContext
{
public string Status { get; set; }
public int ItemsProcessed { get; set; }
}
public static class SharedState
{
private static readonly RunContext context = new RunContext();
public static RunContext Context
{
get { return context; }
}
}
public class Worker
{
public void Process(string item)
{
RunContext context = SharedState.Context;
context.ItemsProcessed++;
context.Status = "Processed " + item;
}
}
}
'@
# Point a global variable at the object held by the static class
$global:RunContext = [Automation.SharedState]::Context
function Set-RunStatus {
param([string]$Status)
# This updates the same object that C# sees
$global:RunContext.Status = $Status
}
Set-RunStatus 'Starting'
[Automation.SharedState]::Context.Status # Starting
$worker = New-Object Automation.Worker
$worker.Process('server01')
$global:RunContext.Status # Processed server01
$global:RunContext.ItemsProcessed # 1
Running the script prints this:
Starting
Processed server01
1
There are two things to keep in mind:
- Change properties, not the variable. Assigning something new to
$global:RunContextonly repoints the PowerShell variable. C# keeps using the original object. - Know who shares what. A static class belongs to the process, while a global variable belongs to one runspace. A second runspace in the same process sees the same static object but needs its own global variable.
Start-Jobruns in a separate process, so it doesn’t share the object at all.
Compiling C# at runtime
The third point gave us scriptable C# code that we could change just by opening the PS1 file. PowerShell took care of the compilation at runtime, so we had almost no build issues.
It can sometimes be tricky to debug issues this way. We avoided this by having many unit tests to check for bugs and inconsistencies in the code.
If the C# rarely changes, the same code can go in a DLL, and loading it takes one line:
Add-Type -Path .\Automation.dll
There are two limits to compiling inside a script:
- A changed type needs a new session. .NET can’t unload a type, so changing the C# and rerunning it in the same session fails with
Cannot add type. The type name 'Automation.SharedState' already exists.Rerunning unchanged code is fine. - Windows PowerShell only supports C# 5 by default. Its built-in compiler rejects newer syntax such as
$"..."strings, so the samples here stick to C# 5.
Building the UI in a DLL
The other problem I faced was the UI. The solution required a complex WinForms UI, so I created the WinForms code in a DLL, loaded the DLL into the PowerShell runspace, and used the object to create the UI. The UI logic was in C#, while the automation logic was in PowerShell.
I exposed the event handlers and data variables as properties in the WinForms code, so no plumbing was required in the PowerShell code. Creating the event handlers in PowerShell gave me complete control of the WinForms UI in the most abstract way.
Here’s a small version of that setup. WinForms only runs on Windows, and this sample targets Windows PowerShell.
1. Create the form in C#
Save this as AutomationUI.cs. Target is a data property, and RunHandler is an event handler property that the script fills in.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace AutomationUI
{
public class RunnerForm : Form
{
private readonly TextBox targetBox = new TextBox();
private readonly Button runButton = new Button();
private readonly ListBox logBox = new ListBox();
// Data that the script can read and write
public string Target
{
get { return targetBox.Text; }
set { targetBox.Text = value; }
}
// Handler that the script supplies
public EventHandler RunHandler { get; set; }
public RunnerForm()
{
Text = "Automation Runner";
ClientSize = new Size(420, 260);
targetBox.SetBounds(12, 12, 300, 24);
runButton.SetBounds(320, 11, 88, 26);
runButton.Text = "Run";
logBox.SetBounds(12, 48, 396, 200);
runButton.Click += (sender, e) =>
{
if (RunHandler != null)
{
RunHandler(this, EventArgs.Empty);
}
};
Controls.Add(targetBox);
Controls.Add(runButton);
Controls.Add(logBox);
}
public void WriteLog(string message)
{
logBox.Items.Add(message);
logBox.TopIndex = logBox.Items.Count - 1;
}
}
}
2. Compile it into a DLL
Run this from the folder that holds AutomationUI.cs:
& "$env:WINDIR\Microsoft.NET\Framework64\v4.0.30319\csc.exe" /nologo /target:library `
/r:System.Windows.Forms.dll /r:System.Drawing.dll `
/out:AutomationUI.dll AutomationUI.cs
A Class Library project in Visual Studio works too, and it lets you lay out a complex form in the designer.
3. Use it from PowerShell
Save this next to the DLL as Run-Automation.ps1:
Add-Type -Path (Join-Path $PSScriptRoot 'AutomationUI.dll')
$form = New-Object AutomationUI.RunnerForm
$form.Target = $env:COMPUTERNAME
$form.RunHandler = {
param($ui)
if ([string]::IsNullOrWhiteSpace($ui.Target)) {
$ui.WriteLog('Enter a target first.')
return
}
$ui.WriteLog("Checking $($ui.Target)...")
$isOnline = Test-Connection -ComputerName $ui.Target -Count 1 -Quiet
$ui.WriteLog("Online: $isOnline")
}
[void]$form.ShowDialog()
$form.Dispose()
PowerShell converts the script block to an EventHandler delegate automatically, and $ui receives the form. The script never touches a button or a list, so all of the UI detail stays in the DLL.
With localhost as the target, clicking Run adds these lines to the log:
Checking localhost...
Online: True
Test results
| Test | Result |
|---|---|
Run SharedState.ps1 |
Printed the output shown above |
Assign a new value to $global:RunContext |
The static object still held Processed server01 |
| Read the state from a second runspace | Static object available, $global:RunContext not defined |
| Write the state from a second runspace | The main runspace saw the new value |
Read the state from Start-Job |
Type not found |
Rerun Add-Type with identical C# |
No error |
Rerun Add-Type with changed C# |
Cannot add type. The type name 'Automation.SharedState' already exists. |
| Click Run on the compiled form | Handler ran once, received the form, and added two log lines |
| Click Run with no handler set | No error |
Run Run-Automation.ps1 with an empty target |
Logged Enter a target first. |
| Increment a plain variable, an object property, and a global variable in a handler | 0, 1, and 1 after the handler returned |
| Call a handler from a background thread | Failed with the runspace error shown below |
csc.exe and Windows PowerShell 5.1 weren’t tested. The notes below on UI freezes, Control.Invoke, and locked DLLs come from how WinForms and Windows work, not from these tests.
What to watch for
Most of the issues with this setup come from how handlers run:
- Handlers have their own scope. A plain
$count++inside a handler is lost when the handler returns. Update a global variable or a property on a shared object instead. - Handlers block the UI. The form runs on the script’s thread, so it freezes until the handler returns. Keep handlers short, or move long work to a second runspace and report progress through the shared object.
- Handlers need a runspace. If C# calls a PowerShell handler from a background thread, it fails with
There is no Runspace available to run scripts in this thread. UseSystem.Windows.Forms.Timerrather than a background timer, or call the handler throughControl.Invoke. - Loaded DLLs stay locked. Close the PowerShell session before rebuilding the DLL.
For a simple dialog, building the form directly in PowerShell is easier. This approach pays off when the UI is complex and the automation changes often.