Home > Net >  How to run a PowerShell script file using VB.Net
How to run a PowerShell script file using VB.Net

Time:07-04

I have a desktop application. I am checking if the required text file exists. If it does not exist then I want to run a PowerShell script which will create the required text file.

Here's the code I am trying:

     Dim userInfoPath As String = "C:\temp\UserInfo.txt"
     If (IO.File.Exists(userInfoPath) = True) Then
          MsgBox("The file exists !")
     Else
          Dim result As String
          result = MsgBox("UserInfo.txt file does not exist. Click 'Yes' to create the required file.", vbYesNo)
          If (result = vbYes) Then
               Process.Start("powershell", "-File C:\Desktop\PowershellScript.ps1")
          End If
     End If

The PowerShell file placed at C:\Desktop\PowershellScript.ps1 contains the script to create a new file and add text to it:

mkdir C:\temp\
New-Item C:\temp\UserInfo.txt
Set-Content C:\temp\UserInfo.txt 'blah blah blah blah blah'

When I run the top most code and click on 'Yes' button, I get an error saying object reference not set to an instance of an object.

Error message link

What I am doing wrong?

And is there another way to run a PowerShell script file?

CodePudding user response:

I'm using objShell.Run

Set wshArguments = WScript.Arguments
Set objShell = CreateObject("WScript.Shell")
sArg = wshArguments(0)
If wshArguments.Count > 1 Then
     sArg = sArg & " " & wshArguments(1)
End If
sps1= "C:\Desktop\PowershellScript.ps1"
objShell.Run("powershell.exe -noprofile -noexit -ExecutionPolicy Bypass " sps1 " ‘" sArg "’")

CodePudding user response:

The error message was because of MsgBox(ex.Message) written somewhere else in the code. This error was not because of the code asked in the question.

I wanted to run a PowerShell script only to create txt file. Since my text was small I have just skipped this drama of Process.Start altogether. Rather, I am generating the required txt file using StringBuilder in my main VB.net program.

  • Related