在Visual Basic中执行CMD文件

时间:2015-12-31 21:26:47

标签: vb.net windows cmd

我写了一个确定机器Windows版本的.cmd文件,并将任何静态IP重置为运行相应的" netsh"操作系统的命令。我还有一个可视化的基本程序,可以在我们所有用户的机器上执行我们软件中的不同选项。我想在我们的程序中添加一个按钮,这样如果我们无法远程访问计算机,用户就可以运行此脚本。这些用户的计算机上不存在此.cmd文件。有没有办法将.cmd保存在我的visual basic程序中并从中执行?我知道我可以在VB中运行命令行,但是这个脚本比简单的字符串行处理起来要复杂得多,而不会变得一团糟。

Pic of CMD File code

::Checks Windows Version to know which script to run
@ECHO OFF
FOR /f "tokens=3" %%a in ('ver') do (
IF %%a==XP (goto :dhcpXP) else (goto :dhcpW7)
)
Exit /B

::Resets DHCP for IP and DNS on XP/POSReady2009
:dhcpXP
For /f "tokens=3*" %%a In ('netsh interface ip show config') Do (
Call :UseNetworkAdapter %%a "%%b"
)
Exit /B

:UseNetworkAdapter (
netsh interface ip set address name=%2 source=dhcp
netsh interface ip set dns name=%2 source=dhcp
)
Exit /B

::Resets DHCP for IP and DNS on Windows 7
:dhcpW7
SETLOCAL EnableDelayedExpansion

SET adapterName=

FOR /F "tokens=* delims=:" %%a IN ('IPCONFIG ^| FIND /I "ETHERNET ADAPTER"')     DO (
SET adapterName=%%a

REM Removes "Ethernet adapter" from the front of the adapter name
SET adapterName=!adapterName:~17!

REM Removes the colon from the end of the adapter name
SET adapterName=!adapterName:~0,-1!

netsh interface ipv4 set address name="!adapterName!" dhcp
netsh interface ipv4 set dns name="!adapterName!" dhcp
)
Exit /B

1 个答案:

答案 0 :(得分:0)

首先将批处理文件添加到项目中作为资源。

转到项目属性>资源。

Adding resources to VB.NET windows application project

从链接

中查找工作示例项目

使用VB.NET运行批处理文件(bat,cmd)或文本脚本 Project.zip

或代码在这里

向Windows窗体添加命令按钮。

Imports System.IO

Public Class Form1
Dim program As String = "myprogram"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim output As String
    output = My.Resources.myprogram
    Dim programPath As String = Path.GetTempPath & “\” & program & ".cmd"
    Using sw As StreamWriter = New StreamWriter(programPath)
        sw.Write(output)
    End Using
    If (My.Computer.FileSystem.FileExists(programPath)) Then
        Dim procStartInfo As New ProcessStartInfo
        Dim procExecuting As New Process

        With procStartInfo
            .UseShellExecute = True
            .FileName = programPath
            .WindowStyle = ProcessWindowStyle.Normal    'use .hide to hide the process window
            .Verb = "runas"                             'run as admin
        End With
        MsgBox("Please press Yes when system ask permissions", MsgBoxStyle.Information, "myProgram")
        procExecuting = Process.Start(procStartInfo)

    End If
End Sub
End Class