I had some fun this week by reading lots and lots of code. Saturday I set out to make myself a gitconsole for Visual studio 2010. I want this because powerconsole is not Async and the nugetconsole has to much nuget bits hanging on to it.
Since nuget is opensource I set out to get the powerconsole out of the nuget source. Alas, after spending a few hours with the code I was thinking that nuget is bit to tightly coupled with is console for me to get it out and change it the way I want it. In other words it might be easier to start from scratch. So I did some more reading and found that embedding powershell in your application is pretty easy.
Here are two excellent articles on how to do it.
- How to run PowerShell scripts from C#
- Asynchronously Execute PowerShell Scripts from C#
- How to Embed PowerShell Within a C# Application And look what I made in a few minutes.
And here is all the code I needed to make that work. It was more work finding where they hid the System.Management.Automation.dll but nothing Google can’t handle.
```vbnet Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim p = InvokeCommand(Me.TextBox1.Text) For Each p1 In p Me.TextBox2.AppendText(p1) Next End Sub
Public Function InvokeCommand(ByVal command As String) As IEnumerable(Of String)
Try
Return PowerShell.Create.AddScript(command).AddCommand("out-String").Invoke(Of String)()
Catch ex As Exception
Return New List(Of String) From {ex.Message}
End Try
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.TextBox2.Text = ""
End Sub```
Now I just have add this to my toolwindow in my VS extension and I’m done 😉 easy as pie.