Richard
Richard

Reputation: 85

Using %USERPROFILE% to Run External Script

I am running an external script from a button on a VB.Net created GUI, which I can do but only when using the full path name to said script ("C:\Users\username\To scripts\myscript.vbs") but would like to use the %USERPROFILE% variable.

I've tried a number of things [which I've left in the script below], but unfortunately with no success, path errors etc, and therefore would be grateful for any assistance.

Many thanks

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim proc As New System.Diagnostics.Process()

        System.Environment.ExpandEnvironmentVariables(
            "%USERPROFILE%")
        proc = Process.Start("%USERPROFILE%\To scripts\myscript.vbs", "")
    End Sub
End Class

Upvotes: 0

Views: 123

Answers (1)

Waescher
Waescher

Reputation: 5737

You can use GetFolderPath() and the SpecialFolder enumeration to find that file. To run a vbs file, you should call cscript.exe with given arguments.

Dim userProfile As String = System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim scriptFile As String = System.IO.Path.Combine(userProfile, "To scripts", "myscript.vbs")
Process.Start("cscript", $"//Nologo ""{scriptFile}""")

There is also an option like //B to run the script in batch mode (without UI).


Note that the double and triple quotes look fancy in the last code line but they are required if the scriptFile variable contains spaces. See (and run) this interactive .NET Fiddle

Upvotes: 1

Related Questions