I know this is easy. I am an administrator, not a FT programmer. I am trying to pass the prjFilename and emailFilename arguments to a Batch file. To ensure the values are correct, I am popping a MsgBox in the Else branch. Everything is fine there. The problem is that when I attempt to use the variable in the Batch file, that variable string is cut off at the very first space in the filename path.
So when I echo %1% to test it, I get a truncated path. Any help is appreciated.
If prjFilename = "" Then
MsgBox("Please select a GSA Project File to process")
ElseIf emailFilename = "" Then
MsgBox("Please select a list of emails to process")
Else
Dim DosRun As Process = New Process
Dim strArgs As String
MsgBox(prjFilename)
MsgBox(emailFilename)
strArgs = prjFilename & " " & emailFilename
MsgBox(strArgs)
DosRun.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
DosRun.StartInfo.FileName = "C:\Users\Eric\Desktop\KRUSH\krush.cmd"
DosRun.StartInfo.Arguments = prjFilename & " " & emailFilename
DosRun.Start()
If either of prjFilename or emailFilename contain spaces, then you need to place double quotation characters around them when passing them to the batch file. A double quotation character literal in VBA is """" (I kid you not).
strArgs = """" & prjFilename & """" & " " & """" & emailFilename & """"
I normally define Public Const vbQuote as String = """" at the top of a module and use that.
Related
Hi the below code was my code in creating csv file. The creation of csv is alright but when the csv convert to text file they sey it should have quotation mark between the beginning and in the end of the value. EX: in CSV File the value was: Jham, and in the textfile it should be : "Jham" - how can i manage it? can someone help?
listofValue = ZipFileStr & "," & Img1Val & "," & Img2Val & "," & RExVal & "," & BundleNo & "," & BundleNo & "," & URNVal & "," & PromocodeVal & "," & ZipFileStore & "," & SNumVal & "," & DpackVal & "," & ArrivalDate & "," & CompleteDateTwo & "," & KidPCVal & "," & MDBName
Dim PathX As String = TempPath & "\"
If Not IO.Directory.Exists(PathX) Then
MkDir(PathX)
End If
Dim sampleX As String = PathX & ZipFileStr & "P.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(sampleX, True)
outFile.WriteLine(listofValue)
outFile.Close()
Firstly, when posting code snippets, please format them for readability. I have fixed that for you.
Secondly, there's no such thing as "converting" between a CSV file and a text file. A CSV is just plain text. If the text contains record and field delimiters then it is a CSV file, otherwise it's not. It's plain text either way.
As for the question, I would suggest writing a CSV with quoted values something like this:
Dim line = String.Format("""{0}"",""{1}"",""{2}""",
firstValue,
secondValue,
thirdValue)
The use of String.Format or, in VB 2015, string interpolation makes the code far more readable. As for putting a double-quote in a literal string, you simply escape it with another double-quote. You might also use the ControlChars.Quote field:
Dim line = String.Format("{0}{1}{0},{0}{2}{0},{0}{3}{0}",
ControlChars.Quote,
firstValue,
secondValue,
thirdValue)
Note that it is generally only text values that get quoted, not numbers and dates and the like. That's because the main reason for the quoting is to allow a value to contain delimiters, i.e. commas or line breaks. If none of your values do contain delimiters then you can safely omit the quotes altogether.
EDIT: As an example, here's how I might write a DataTable to a CSV file where the first and fourth columns contain String values, the second column contains numbers and the third column contains Date values.
Private Sub WriteToCsv(table As DataTable, path As String)
Dim lines As New List(Of String)
For Each row As DataRow In table.Rows
lines.Add(String.Format("""{0}"",{1},{2:yyyy-MM-dd},""{3}""",
row(0),
row(1),
row(2),
row(3)))
Next
IO.File.WriteAllLines(path, lines)
End Sub
I have a piece of code that calls MSTEST with multiple arguments defining a specific set of tests to run and an environment to run it in. Currently the code looks like this (a bit messy but it works):
Process.Start(Environment.GetEnvironmentVariable("VS110COMNTOOLS")
& "..\Ide\MSTEST.EXE", "/Testsettings:""" & rwSettings & """"
& " /Testcontainer:""" & rwContainer & """" & " /Resultsfile:"""
& rwResults & """")
With the various variables defined previously. I had to use the GetEnvironmentVariable("VS110COMNTOOLS") call because I can't guarantee an install location for Visual Studio and need access to the MSTEST executable. "..\Ide\MSTEST.EXE" is because the environment variable will only get me to the right area and I'll need to have the system navigate to IDE before it finds MSTEST.
I want to clean this up because it's not very elegant or readable, and also because I want to be able to raise events running this process. However, I'm not seeing documentation on how the Process class handles arguments. How can I have the Process object I create handle the multiple arguments (that might have spaces in the name)?
You may try this:
Dim Testsettings As String = "/Testsettings:"""
Dim Testcontainer As String = " /Testcontainer:"""
Dim Resultsfile As String = " /Resultsfile:"""
Dim Quote As String = """"
Dim p As New Process()
p.StartInfo.FileName = Environment.GetEnvironmentVariable("VS110COMNTOOLS")
& "..\Ide\MSTEST.EXE"
p.StartInfo.Arguments = Testsettings & rwSettings & Quote & Testcontainer
& rwContainer & Quote & Resultsfile & rwResults & Quote
p.Start()
I've two VB Scripts. Say First.vbs and Second.vbs.
Frist.vbs calls Second.vbs each time some action/event happens.
I am trying to send two parameters from Frist.vbs to Second.vbs using the following code:
Contents of First.vbs:
Set objShell = Wscript.CreateObject("WScript.Shell")
param1 = "Welcome"
param2 = "Gokul Nath"
objShell.Run "Second.vbs" & " " & param1 & " " & param2
Set objShell = Nothing
Contents of Second.vbs:
param1= Wscript.Arguments.Item(0)
param2 = Wscript.Arguments.Item(1)
WScript.Echo(param1)
WScript.Echo(param2)
I'm getting the following Echo messages:
Welcome - Which is correct, since I've passed "Welcome" from First.vbs
Gokul - Which is WRONG, since I've passed "Gokul Nath" from First.vbs
This issue occurs, since each space is considered as end of a parameter.
I am new to scripting, can anyone give some suggestion/reference.
The value of param2 contains a space and you didn't put the parameter between double quotes. Because of that your Run command-line effectively has 3 arguments:
Welcome
Gokul
Nath
To avoid that add double quotes around your second argument:
objShell.Run "Second.vbs" & " " & param1 & " """ & param2 & """"
Better yet, quote all arguments and use a quoting function so you don't drown in double quotes:
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
objShell.Run "Second.vbs" & " " & qq(param1) & " " & qq(param2)
In my application I have created I need it to write a visual basic script to change the ip address
The script is as follows...
Dim strIPAddress
Dim strSubnetMask
Dim strGateway
Dim intGatewayMetric
Dim strDns1
Dim strDns2
strIPAddress = "192.168.1.211"
strSubnetMask = "255.255.255.0"
strGateway = "192.168.0.11"
intGatewayMetric = 1
strDns1 = "8.8.8.8"
strDns2 = "4.4.4.4"
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.Run "netsh interface ip set address name=""Local Area Connection"" static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=""Local Area Connection"" static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=""Local Area Connection"" addr="& strDns2, 0, True
Set objShell = Nothing
WScript.Quit
The way I am trying to write this is like the following..
Directory.CreateDirectory("C:\SpecMee\IPChanger\")
Dim objwriter As New System.IO.StreamWriter("C:\SpecMee\IPChanger\IpChanger.vbs")
objwriter.WriteLine("Dim strIPAddress" & Environment.NewLine & "Dim strSubnetMask" & Environment.NewLine & "Dim strGateWay" & Environment.NewLine & "Dim intGatewayMetric" & Environment.NewLine & "Dim strDns1" & Environment.NewLine & "Dim strDns2" & Environment.NewLine & "strIPAddress = """ & Environment.NewLine & TB_IPAddress & Environment.NewLine &)
objwriter.Close()
MessageBox.Show("Created")
The problem I am having is one, it is taking ages and two, how would i include the "" in the script.
I dont mind spending time on this, I just dont know if im going about this the right way.
any help would be appreciated.
Thanks
Chris
Add the script as a text file resource to your project. Replace all instances of the IP Address in the script with some known value, then use string.replace:
Const ipPlaceHolder As String = "##IP##"
Dim scriptContent As String = My.Resources.script.Replace(ipPlaceHolder, myTextBox.Text)
IO.File.WriteAllText("C:\SpecMee\IPChanger\IpChanger.vbs", scriptContent)
Where myTextBox contains user input and the text file resource is named "Script"
Two quotation marks in a row makes one in the output.
"And he said ""Thar she blows!"""
( You have two questions in one. That is not considered good customs on Stackoverflow. )
I'm trying to adapt a VBscript that runs the QWINSTA command against a text file I've defined as an array and displays the results in a text file.
after looking at numerous examples on Stack and other sites this is my latest iteration, that displays everything except the STDOUT, which is really what I'm after, not sure if it's an issue with how I'm calling the command piping the output or what. I'm also passing two variables as arguments to complicate matters :)
The Text file that stdout is piped to is empty after the FOR Loop completes
I may be going the long way about this, most of my past experience with this is in BATCH
For Each server In RemotePC
'The Query is launched
Dim Query As New ProcessStartInfo
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(Query)
'Call Shell("QWINSTA /SERVER:" & server & " " & profile & " >C:\Windows\Temp\SFOUT.txt", vbHidden, Timeout:=5000)
Dim SFOUT As New IO.StreamReader("C:\windows\temp\SFOUT.txt")
'Results are Echoed to TextboxResults
TextBoxResults.Text &= "__________________________________________________________" & ControlChars.CrLf
TextBoxResults.Text &= server & ControlChars.CrLf
TextBoxResults.Text &= SFOUT.ReadToEnd & ControlChars.CrLf
SFOUT.Close()
Next
Here is what the working code in VBscript looks like
For Each server In RemotePC
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set StrDir = "QWINSTA /SERVER:" & server & " " & profile
'The Query is launched
Set oExec = WshShell.Exec(StrDir)
'We wait for the end of process
Do While oExec.Status = 0
WScript.Sleep 500
Loop
'We scan and only display the command output of commands without NULL output
Do While oExec.StdOut.AtEndOfStream <> True
Results.WriteLine("__________________________________________________________")
Results.WriteLine(server)
Results.WriteLine oExec.StdOut.ReadLine
Loop
NEXT
Any help is appreciated
#Nilpo
this is what I get back
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console Matt 1 Active
I've built something similar to this using QWINSTA and piping the output in batch and it works flawlessly, just having issues adapting this.
here's the last thing I tried I tried to simplify things by calling something as basic as notepad.exe, and even trying to define the environment variable thinking it's not reading %PATH%, in reply to #Nilpo
Dim Query As New Process
Query.StartInfo.FileName = "notepad.exe"
'Query.StartInfo.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.StartInfo.UseShellExecute = False
Query.StartInfo.RedirectStandardOutput = True
Query.StartInfo.WindowStyle = ProcessWindowStyle.Normal
Environment.SetEnvironmentVariable("PATH", "%PATH%;" & "C:\Windows\System32\notepad.exe")
Query.Start()
You should have a space after the output redirection.
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Should be
Query.Arguments = server & " " & profile & " > C:\Windows\Temp\SFOUT.txt"
That being said, the only thing I can see that may not work is here.
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(Query)
I'm not sure that you can use arguments in this fashion. Your output redirection is being read as a literal argument when it's really not. In a command line environment it's interpreted as a separate command, not an argument to the first command. It's very similar to piping in that manner. Supplying this as an argument in your code probably won't work as expected. You may want to go back to the Call Shell method. That will execute the command as if it were on the command line.
[Edit]
I was correct. Here is the proper way to do this using your method.
Query.WorkingDirectory = "c:\"
Query.Arguments = server & " " & profile & " >C:\Windows\Temp\SFOUT.txt"
Query.FileName = "QWINSTA"
Query.WindowStyle = ProcessWindowStyle.Hidden
'Redirect output
Query.UseShellExecute = False
Query.RedirectStandardOutput = True
Process.Start(Query)
'Read the output
Dim output As String = Process.StandardOutput.ReadToEnd
' wait for the process to terminate
Process.WaitForExit