I want to test if a specific named argument has been provided before validating that argument, so I can provide meaningful error codes for missing and invalid conditions.
I have this now
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colArgs = WScript.Arguments.Named
If colArgs.Item("Script") Then
If not objFSO.FileExists(colArgs.Item("Script")) Then
intReturn = 1805
End If
Else
intReturn = 1639
End If
If Not intReturn Then
msgBox colArgs.Item("Script"), 0, "Script"
Else
msgBox intReturn, 0, "Error"
End If
And my expectation would be that if I don't provide an argument called Script at all, I would get the Error msgBox with the 1639 value. Instead I get the good msgBox, with a blank for Script.
I also tried
If Not colArgs.Item("Script") = "" Then
EDIT: Per #Tomalak, I now have this
Option Explicit
Dim objShell, objFSO, colArgs, intReturn
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set colArgs = WScript.Arguments.Named
If Not IsEmpty(colArgs.Item("Script")) Then
If Not objFSO.FileExists(colArgs.Item("Script")) Then
intReturn = 1805
End If
Else
intReturn = 1639
End If
If IsEmpty(intReturn) Then
msgBox colArgs.Item("Script"), 0, "Script"
Else
msgBox intReturn, 0, "Error"
End If
And for what it is worth, I am calling the VBScript from PowerShell like this
$script = "\\Mac\iCloud Drive\Px Tools\Dev 4.0\#Spikes\Helper\Helper Target.ps1"
$arguments ="`"\\Mac\iCloud Drive\Px Tools\Dev 4.0\#Spikes\Helper\PxHelper.vbs`" //nologo /script:`"$script`" /wait:1"
Start-Process -filePath:Wscript.exe -argumentList:$arguments
And now I get the error condition even when the script IS provided. Grrr, Mondays.
If a named argument is not given on the command line
WScript.Arguments.Named.Exists("argname") will return False
WScript.Arguments.Named("argname") will return an empty value
If a named argument is given but not assigned a value on the command line (/argname)
WScript.Arguments.Named.Exists("argname") will return True
WScript.Arguments.Named("argname") will return an empty value
If a named argument is given with an empty string on the command line (/argname:)
WScript.Arguments.Named.Exists("argname") will return True
WScript.Arguments.Named("argname") will return an empty string
If a named argument is given with a value on the command line (/argname:value)
WScript.Arguments.Named.Exists("argname") will return True
WScript.Arguments.Named("argname") will return a string with that value
Empty values are different from empty strings: They are uninitialized, whereas the empty string is a is regular string of zero length.
You can check for empty values with the IsEmpty() function.
If Not WScript.Arguments.Named.Exists("foo") Then
' show message / end script / use default
End If
If IsEmpty(WScript.Arguments.Named("foo")) Then
' show message / end script / use default
End If
Related
I'm trying to write a VBScript that will check whether a file exists in a folder or not based on a partial number. If anything in the folder has this number in the string it can continue, if not an error needs to display saying it's not in the system. I've gotten a code that lets me know that the file DOES exist, but I can't get a NOT version to work. Any ideas?
Dim FSO, str1, fileName
str1 = "001234"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\Users\GDoe\Desktop\FolderA\")
For Each objFile In objFolder.Files
fileName = objFile.Name
If InStr(fileName, str1) Then
MsgBox("Proceed")
Exit For
End If
Next
Unfortunately the FileSystemObject's FileExists method does not support wildcards, so the straightforward approach is not possible here.
The code you posted in your question is basically how one would check for the existence of a file with a partial name with VBScript and the FileSystemObject. You can modify that code into a check for the absence of a file with some minor changes. Define a variable before the loop and set it to False, then instead of displaying a message box set that vriable to True when you find a matching file:
fileFound = False
For Each objFile In objFolder.Files
fileName = objFile.Name
If InStr(fileName, str1) Then
fileFound = True
Exit For
End If
Next
If fileFound Then
MsgBox("Proceed")
Else
MsgBox("File doesn't exist.")
End If
Alternatively, you could shell out and check the exit code of the dir command:
Function FileExists(path, namepart)
Set sh = CreateObject("WScript.Shell")
rc = sh.Run("cmd /c dir ""*" & path & "\" & namepart & "*""", 0, True)
FileExists = Not CBool(rc)
End Function
dir returns 0 if it finds matching file(s) and 1 if it doesn't. CBool() converts the integer return code into a boolean value (0 → False, 1 → True). The negation then corrects the logic from "false if found" to "true if found".
Of course you could also name the function FileMissing and remove the negation, so that the function returns True if no matching file is found. That's just a matter of what logic works best in your code.
Note that you need to run the command with cmd /c, because dir is a cmd.exe builtin command, not an executable.
I actually just found a way to answer my own question but if there's a better way I'd also love to know.
Dim FSO, str1, fileName
str1 = "-001239"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\Users\GDoe\Desktop\FolderA\")
For Each objFile In objFolder.Files
fileName=objFile.Name
If InStr(fileName, str1) Then
MsgBox("Proceed")
Exit For
End If
Next
If InStr(fileName, str1) = 0 Then
MsgBox("File doesn't Exist")
End If
I took the rule that if string2 is not found in an InStr command it returns 0. Setting the result = 0 shows if I don't have the file.
I am trying to convert string to double in UFT but It shows the output without decimal point. below is the code for reference.
vStr = "1000000.589765"
msgbox Typename(vStr)
strV1=CDBL(formatNumber(vStr,4))
msgbox Typename(strV1)
print strV1
Output: 1000000589765
Note that without formatNumber, its not working.
Yet another implementation using DotNetFactory. Just an another thought. I am not denying to use CDbl. But worth to give a shot.
'Test Code
Dim strConvertedCode
strConvertedCode = ConvertDataType("1000000.589765","Double")
If strConvertedCode <> null Then
Msgbox strConvertedCode
End If
Public Function ConvertDataType(ByVal SourceData,ByVal ConversionDataType)
'Initialization of variables
Dim objDotNetFactory
Dim strConvertedData : strConvertedData = null
Dim strSystemNamespace
'Determine the destination data type
Select Case UCase(ConversionDataType)
Case "DOUBLE"
strSystemNamespace = "System.Double"
'Implement further for your data types
'Reference https://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx
Case Default
Set objDotNetFactory = DotNetFactory.CreateInstance("System.Int32")
End Select
Set objDotNetFactory = DotNetFactory.CreateInstance(strSystemNamespace)
'Check the dot net factory instance is successful
If Not IsObject(objDotNetFactory) Then
Reporter.ReportEvent micWarning,"Data type convertor","Conversion from String to " & ConversionDataType & " failed, Since DotNetFactory instance was not created."
ConvertDataType = strConvertedData
Exit Function
End If
strConvertedData = objDotNetFactory.Parse(SourceData)
ConvertDataType = strConvertedData
End Function
Being I'm a novice at VBS, I'm have a hard time determining why this short script is not returning a column count of 193, One time I'll get the correct count and others I get 0.
Thank you in advance for any and all suggestions.
OldCityCat
Sub VerifyOrders
Dim Results
Dim objFSO, objTextFile, objReadFile, Contents, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\TestFileWith_194_characters.csv")
Set objTextFile = objFSO.OpenTextFile("C:\TestFileWith_194_characters.csv")
Set objReadFile = objFSO.OpenTextFile("C:\TestFileWith_194_characters.csv",1)
objReadFile.ReadAll
Contents = objReadFile.Column -1
WScript.Echo Contents
If Contents < 194 Then
Results = "No Orders"
Else
Results = "Has Orders"
End if
objReadFile.Close
If Results = "No Orders" Then
Call NoOrders
Else
Call OpenAccess
End If
End Sub
'/ If no orders the send email end script. Else If orders process them
Sub NoOrders
If Results = "No Orders" Then
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
objMail.Display
objMail.Recipients.Add ("gchichester#wilk.us.com")
objMail.Subject = "No Sales Orders to Process"
objMail.Body = "Respect didn't receive any orders for Pine Castle"
objMail.Send
objOutlook.Quit
Set objMail = Nothing
Set objOutlook = Nothing
End If
End Sub
Sub OpenAccess
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Exec("C:\Program Files (x86)\Microsoft Office\Office14\MSACCESS.EXE "&" C:\DropBox\Inflow\DrugSales.accdb /x OnOpen")
WScript.Sleep 60000
WshShell.SendKeys "%{F4}"
End Sub
You are getting 0 when the contents of the text file you're reading from has written a newline character, but nothing else.
From the Microsoft documentation:
After a newline character has been written, but before any other character is written, Column is equal to 1.
Throughly examine the contents of the text file before you attempt to read it in as a text stream.
Of note but not relevant to my answer above: you do not need to declare or set objFile or objTextFile since you are using objReadFile. Suggest removing both the declaration and set operations for both of those variables.
I need to start a vbs script by an argument and related to the passed argument see a pop up.
Example :
Dim Arg, var1, var2
Set Arg = WScript.Arguments
'Parameter1, begin with index0
var1 = Arg(0)
if (instr(WScript.Arguments.Name,"Printer")> 0 then
wscript.echo "Printer type..."
end if
if (instr(WScript.Arguments.Name,"help")> 0 then
wscript.echo "help..."
end if
Thanks in advance
'Clear the objects at the end of your script.
set Arg = Nothing
call you script like so
myscript.vbs /help
and access args like so
'setup the named argument collection
set argNamedCollection = WScript.Arguments.Named
'get the arguments passed in
argHelp = argNamedCollection.Item("help")
argPrinter = argNamedCollection.Item("printer")
'or check directly
'check for help arguments
if argNamedCollection.Exists("help") then
'do somthing
end if
I need to go through a text file and check whether the start of each line begins with "Attribute". How should I do this in VB6?
Use a Regex. You will have to include the VBScript Regular Expressions library in your references.
Dim reg As new Scripting.Regex().
reg.Pattern = "^Attribute"
If reg.Match(line) Then
' Do Something
End If
Dim sInput As String, check as Boolean
check = true
Open "myfile" For INPUT As #txtFile
While Not EOF(txtFile)
Input #txtFile, sInput
If Not Mid(sInput,1,9) = "ATTRIBUTE" Then
check = false
End if
sInput = ""
Wend
Close #txtFile
If check = true at the end, all lines start with "ATTRIBUTE", otherwise they do not.
You could try something like this (code not tested) -
Dim ParseDate, AllLinesStartWithAttribute, fso, fs
AllLinesStartWithAttribute = False
Set fso = CreateObject("Scripting.FileSystemObject")
Set fs = fso.OpenTextFile("c:\yourfile", 1, True)
Do Until fs.AtEndOfStream
If Left(fs.ReadLine, 9) <> "Attribute" Then
AllLinesStartWithAttribute = False
Exit Do
End If
Loop
fs.Close
Set fs = Nothing
Once the code is run if the AllLinesStartWithAttribute value is set to true then all lines in your file begin with 'Attribute'. Please note that this code is case sensitive.
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim str As String
Set ts = fso.OpenTextFile(MyFile)
Do While Not ts.AtEndOfStream
str = ts.ReadLine
If InStr(str, "Attribute") = 1 Then
' do stuff
End If
Loop