Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2010-12-18
Through the .NET Framework, Visual Basic can talk to PowerShell. If PowerShell is installed, you can add a reference to an assembly named System.Management.Automation. You will have to browse for it, and you will find it here:
C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
Also, scripting needs to be activated in PowerShell.
A RunSpace is a context where PowerShell scripts run. Any variables that are set in one runspace, can be read from that same runspace, but not any other runspace. Before the opening Using, I will create a variable (Result) that will hold the response from PowerShell.
Dim Result As _ System.Collections.ObjectModel.Collection(Of System.Management.Automation.PSObject) Using R As System.Management.Automation.Runspaces.Runspace = _ System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()
Next, you open the runspace and create a pipeline.
R.Open() Dim P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()
The pipeline has a Commands collection where you add your commands or complete scripts. These two lines will create two output objects.
P.Commands.Add("C:\test.ps1")
When you’re done, you can execute the script using the Invoke function of the pipeline object, and close your runspace. The response is saved in the Result variable I created earlier.
Result = P.Invoke() R.Close() End Using For Each Res As System.Management.Automation.PSObject In Result MessageBox.Show(Res.ToString()) Next
The content of my script file, test.ps1, is:
Write-Output "Hello!" $x = 10 + 3 Write-Output $x
The output of course will be one message box saying Hello! and another saying 13.
Categories: PowerShell
Tags: PowerShell
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply