Process.Start("powershell", "-noexit -file 'c:\Temp\myScript.ps1'")
Process.Start("powershell", "-noexit -ExecutionPolicy Bypass -file 'c:\Temp\myScript.ps1'")
Add-Type -TypeDefinition @"
Imports System
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Public Class PS
Dim host As PowerShell = PowerShell.Create(InitialSessionState.CreateDefault())
Public Function RunScript(path As String) As object
Try
Dim value As Object = host.AddScript(path).Invoke()
If host.HadErrors Then
For Each errorRecord as ErrorRecord in host.Streams.Error
Console.WriteLine(errorRecord.Exception.Message)
Next
Else
Return value
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Return Nothing
End Function
End Class
"@ -ReferencedAssemblies ([PowerShell].Assembly.Location) -Language VisualBasic
[PowerShell].Assembly.Location
That gets it the assembly associated with PowerShell 5.1 not PowerShell 2.0.
"Add-Type -TypeDefinition @" and "@ -ReferencedAssemblies ([PowerShell].Assembly.Location) -Language VisualBasic"
surrounding the class code causes the entire class code to display as quoted-text and red-marks the whole thing with a "Statement cannot appear outside of a method body" error.PowerShell.Create(InitialSessionState.CreateDefault())
Is this static method:Dim host As PowerShell = PowerShell.Create(InitialSessionState.CreateDefault())
wasn't liked by VS so I changed it to this:Dim host As PowerShell
and followed that up with the "Create" static method used in a constructor (Sub New) which it didn't like either (saying that a "declaration is expected").
A mini-class with a PS wrapper :)
Open in new window
Once it's created, the method can be invoked after you instantiate the class.Open in new window
The advantage of this approach is that you can get detailed error information. Runtime errors (terminating errors) will throw as exceptions when Invoke is called. Non-terminating errors are written to host.Streams.Error.