Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Execute a cmdlet or PS1 script from Visual Basic

2009-08-10

The cmdlets in PowerShell can easily be executed from within Visual Basic. I have done this in a few Visual Basic 8 projects, and the code for doing this from Visual Basic 8 can be somewhat ugly, but in Visual Basic 9 (and .NET Framework 3.5) it is very straight forward. You will need a reference to System.Management.Automation. If you don’t have it, you will get it when you install the Windows SDK for Windows Server 2008 and .NET Framework 3.5 from here. System.Management.Automation.dll installs to C:\Program\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0.

The Runspace object will host the Pipeline object, and the Pipeline object is used to execute cmdlets or PS1 scripts.

Some preparations: I have activated script execution and I have created a script file (C:\script.ps1) that contains one simple line: Write-Output 10+2

'Create the runspace.
Using R As System.Management.Automation.Runspaces.Runspace = _
System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()

   'Create the pipeline
   Using P As System.Management.Automation.Runspaces.Pipeline = R.CreatePipeline()

      'Open the runspace.
      R.Open()

      'Create each command (in this case just one)...
      Dim Cmd As New System.Management.Automation.Runspaces.Command("C:\script.ps1", True)

      '...and add it to the pipeline.
      P.Commands.Add(Cmd)

      'Execute the commands and get the response.
      Dim Result As System.Collections.ObjectModel.Collection(Of _
      System.Management.Automation.PSObject) = P.Invoke()

      'Close the runspace.
      R.Close()

      'Display the result in the console window.
      For Each O As System.Management.Automation.PSObject In Result
         Console.WriteLine(O.ToString())
      Next

   End Using
End Using

Output: 12

Categories: PowerShell, Visual Basic 9

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips