如何使用vb.net运行powershell脚本文件

发布于 2025-02-12 03:33:42 字数 953 浏览 0 评论 0原文

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

这是我尝试的代码:

     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

放置在C:\ desktop \ powershellscript.ps1的PowerShell文件包含脚本以创建新文件并将文本添加到它

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

:获取错误,说对象引用未设置为对象的实例。

错误消息链接

我在做什么错?

还有另一种运行PowerShell脚本文件的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗心人 2025-02-19 03:33:42

我正在使用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+"’")

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+"’")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文