如何使用VB.Net运行PowerShell脚本文件



我有一个桌面应用程序。我正在检查所需的文本文件是否存在。如果它不存在,那么我想运行一个PowerShell脚本来创建所需的文本文件。

这是我正在尝试的代码:

Dim userInfoPath As String = "C:tempUserInfo.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:DesktopPowershellScript.ps1")
End If
End If

PowerShell文件放置在C:DesktopPowershellScript。Ps1包含用于创建新文件并向其中添加文本的脚本:

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

当我运行最上面的代码并单击"Yes"按钮时,我得到一个错误,说对象引用未设置为对象的实例。

错误信息链接

我做错了什么?

还有别的方法来运行一个PowerShell脚本文件吗?

我用的是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:DesktopPowershellScript.ps1"
objShell.Run("powershell.exe -noprofile -noexit -ExecutionPolicy Bypass "+sps1+" ‘"+sArg+"’")

最新更新