VB Script

37K

Solutions

20K

Contributors

VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.

Share tech news, updates, or what's on your mind.

Sign up to Post

Add-printer command on Powershell Version 2


I am trying to run add-printer powershell command   but I m getting error.
add-printer -name "MyTest Printer" -drivername "Canon MX920 series Printer"

Thank you

PS C:\Users\administrator> add-printer -name "MyTest Printer" -drivername "Canon MX920 series Printer"
The term 'add-printer' is not recognized as the name of a cmdlet, function, script file, or operable p
 spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:12
+ add-printer <<<<  -name "MyTest Printer" -drivername "Canon MX920 series Printer" -port "Envy"
    + CategoryInfo          : ObjectNotFound: (add-printer:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\administrator>

Open in new window


the remote computer is running Version 2 of Powershell

PS C:\Users\administrator> $psversiontable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5420
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


PS C:\Users\administrator>

Open in new window

0
JavaScript Best Practices
LVL 19
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

Hello,

I have got a vbscript which renames the file in a folder the requirement is to loop in a folder and all its subfolders to see the files and rename them.
It works great on a file level but, need to loop in the folders and subfolders as well.
Please find the vbscript attched.
Option Explicit

RenameFiles "C:\test"

Function CanRename(AFileName)

  On Error Resume Next

  Dim Dummy

  Err.Clear
  Dummy = Right(FileNameWithoutExtension(AFileName), 10)
  Dummy = DateSerial(Mid(Dummy, 7, 4), Mid(Dummy, 4, 2), Mid(Dummy, 1, 2))
  CanRename = (Err.Number = 0)
  Err.Clear

End Function

Function FileExtension(AFileName)

  Dim Count
  Dim Result

  Result = ""
  Count = InStrRev(AFileName, ".")
  If Count > 0 Then
    Result = Mid(AFileName, Count, 1024)
  End If

  FileExtension = Result

End Function

Function FileNameWithoutExtension(AFileName)

  Dim Count
  Dim Result

  Result = AFileName
  Count = InStrRev(AFileName, ".")
  If Count > 0 Then
    Result = Mid(AFileName, 1, Count - 1)
  End If

  FileNameWithoutExtension = Result

End Function

Function RenameFileName(AFileName)

  Dim DATE_DELIMITER
  DATE_DELIMITER = "-"

  Dim LITERAL_DELIMITER
  LITERAL_DELIMITER = "_"

  Dim FileName
  Dim DateText

  FileName = FileNameWithoutExtension(AFileName)
  DateText = Right(FileName, 10)
  RenameFileName = _
    Mid(DateText, 7, 4) & DATE_DELIMITER &  Mid(DateText, 4, 2) & DATE_DELIMITER &  Mid(DateText, 1, 2) & LITERAL_DELIMITER & _
    Left(FileName, 

Open in new window

0
Hi,
Any suggestion for a vbscript to rename a file.
FilenameDD.MM.YYYY

Result expected:

YYYY.MM.DDFilename

Thanks
0
I would like to check a column called Part Rcvd if the row in the column matches Rcvd (this will be an exact match as I hope it will be hard coded in by the end user) then color the matching cell and adjacent cells in column N and column O to grey.
As an example
column N                       column O                         column P
12/3/2019                       12/10/2019                       Rcvd
Finds match in column P for string Rcvd then greys out column N, column O, and column P . Loops thru for each row within that column until it reaches the end. Thanks in advance. Would it be better to code this in VB or use a formula manager in excel to create? Not sure which is more efficent. There currently are no formulas or vb code running on this sheet. More informational so process time is short
0
I have a code on vbscript, I am trying to debug it by tracing with Visual Studio. I start it with a command
cscript //D myscript.vbs

Open in new window

When a stop command is executed or an error happened I attach the VS.
The problem here that it only allows me to put a breakpoint to certain lines of the code (always to the one where the stop was, and some else, I did not get the rules), making the debugging process to be very frustrating.
When I'm trying to do the "Set the next statement" command to move the execution pointer (I press Ctrl+Shift+F10) to a line where it previously did not let me to put a breakpont, I got a message box, saying "Unable to set the next statement. There is no execution code at this location in the source code."

Is that a normal behaviour or something is misconfigured?
0
Is there a way to check the current date (on the computer - maybe system date - so it grabs the current date) and then compares to a date on an excel spreadsheet like a parts ordered date in the format 11/20/2019. Not sure if I can use excel formulas or if vb code would need to be used??? thanks in advance
0
replace a string on a text file on a remote computer

Currently, I have to type in \\RemotecomputerName\c$ I will be prompted to type  in RemotecomputerName\administrator  and password.
then open a text file (it has extension of CMD). the file has few lines on it , but the string  I want to replace is called username and comes after -username (notice the dash before username).

example:
aaaaaa bbbbbbbb ccccccccc dddddddddd -username username
then Save the file.

I need this operation to be done by a script

Thank you
0
Greeting Experts,

Can somebody help me create a PowerShell script to clear cached passwords in a Windows Operating System (7/10)....
0
Greeting Experts -

Need help setting up a PowerShell script to install a piece of client software (WindowsSensor.exe) on the list of computers. Can somebody help me write a script that will prompt me for my Admin Credentials, copy the software from a file directory (source file) to folder on the local computer, and then start the install from the command line using these install arguments

software:  WindowsSensor.exe
CLI Install arguments:  WindowsSensor.exe /install /quiet /norestart CID=InstallToken
0
Script was working on another PC. I moved a surveillance system to a new PC and I want to schedule a script to delete files older than 20 days to maintain disk space.

The system stores video in E:\Record. There are 4 subfolders called Cam01, Cam02 etc..


This is the script:

' Specify base folder to purge, and age in days of files to keep
Const strDir = "E:\Record"
Const intAge = 20

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files recursively
RemoveOldFiles objFSO.GetFolder(strDir)

Sub RemoveOldFiles(objFolder)
    On Error Resume Next

    ' If no files of subfolders exist on first check, leave it alone
    If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
        Exit Sub
    End If

    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        intFileAge = DateDiff("d", objFile.DateLastModified, Now)
        If intFileAge > intAge Then
            Wscript.Echo "Deleted file: """ & objFile.Path & """ Age: " & intFileAge & """."
            objFile.Delete
        End If
    Next

    ' See if we were able to access this folder, if not don't recurse into it
    If Err.Number = 0 Then
        ' Remove all older files in any subfolders of this one
        For Each objSubFolder In objFolder.Subfolders
            RemoveOldFiles objSubFolder
        Next

    Else
        ' Report error if anable to access a folder
        

Open in new window

0
Rowby Goren Makes an Impact on Screen and Online
LVL 19
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

I have a shell script that I've been using for Windows 7. It sets the theme for my system desktop. It no longer works now that I've moved to Windows 10.
With WScript.CreateObject("WScript.Shell")
    WScript.echo "Open Theme dialog and select theme and then close"

    .Run "rundll32.exe %SystemRoot%\system32\shell32.dll,Control_RunDLL %SystemRoot%\system32\desk.cpl desk,@Themes /Action:OpenTheme /file:""%UserProfile%\AppData\Local\Microsoft\Windows\Themes\MyPersonal.theme"""
    For i = 1 To 10
            WScript.Sleep 5000
        If .AppActivate("Personalization") Then
           .Sendkeys "%FC"
           .Sendkeys "{F4}"
           Exit For
        End If
    Next
End With

Open in new window

I know I can open the Themes dialog using the run command and
ms-settings:themes

Open in new window

But how would I this as well as select the theme and close the dialog in a shell script on Windows 10?
0
Hello,

I would like some help to rewrite a text file based on two entries..

Example

Heading 1, Heading 2
Liverpool Men, Liverpool Ladies
Everton Men, Everton Ladies
Arsenal Men, Arsenal Ladies

So I would like the text file to be rearranged by moving the headings..

New Text File

Heading 2,  Heading 1
Liverpool Ladies, Liverpool Men
Everton Ladies, Everton Men
Arsenal Ladies, Arsenal Men

Thanks
0
Trying to create a VB script that will prompt a user to put input data, this data then will populate into parts of a url so that it goes to the correct page.

Managed to get a prompt box for user data to appear but i can get this data to populate in the middle of a URL. i'm sure the code is wrong and needs to be change or is there an easy way around this?
Code below, basically where the strAnswer is in the url i need the data to populate.  Any suggestions would be nice :)

strAnswer = InputBox _
        ("Enter your Data here","This is your Case Number")

Set objExplorer = CreateObject _
    ("InternetExplorer.Application")

strURL = "http://MYIPADDRESS/servlet?key=number=&strAnswer&outgoing_uri=SOMETHINGAWESOME"
objExplorer.Navigate strURL
objExplorer.ToolBar = 0
objExplorer.StatusBar = 0
objExplorer.Width = 800
objExplorer.Height = 800
objExplorer.Visible = 1
0
Running Outlook 2007 on a Windows 7 32-bit platform, I have a button on the toolbar which activates a VB script to add a suffix to recipients Email address.  The button's default condition is OFF, until it is pressed. and it resets to OFF when Outlook is first launched.  I wonder if there is a way to set the default condition to ON?
Here is the code.  Please be aware that I am not the author of this code and I'll need specific instructions if it is to be amended...

 
Sub ToggleAddSuffix()
    bolAddSuffix = Not bolAddSuffix
    MsgBox "AddSuffix is now " & IIf(bolAddSuffix, "ON", "OFF"), vbInformation + vbOKOnly, "Toggle Add Suffix"
End Sub

Open in new window

0
I would like a script that I can modify to be able to the following:

Use Office365 smtp
Port 587
TLS
to accept username and password
have a pdf attachment to it called 1.pdf
Send to a distribution list from. EmailList.txt
0
Is there any way to determine what the current error handling is in vb6?

Default error handling crashes the program displaying the error message.

If you use:
ON ERROR GOTO Label

Open in new window

The program goes to the point in the code with the label and continues executing (presumably, you have defined what to do here to mitigate the error)

If you use:
ON ERROR RESUME NEXT

Open in new window

The program will continue ignoring errors until it either can't run at all, you handle the errors, or you disable the resume next option.  I often (but not always) use ON ERROR RESUME NEXT to allow the program to continue and then I explicitly check for an error number and handle the error there.  For example:
ON ERROR RESUME NEXT
X = 5
IF X = "bob" THEN X = "Bob"
IF ERR.NUMBER <> 0 THEN
   'Handle the error
END IF 

Open in new window


And to disable graceful error handling, you use
ON ERROR GOTO 0

Open in new window


But is there any way to tell if graceful error handling is on?  Any way to tell that the last time an ON ERROR statement executed it was set to go to a label, resume next, or goto 0?
0
Hello All,

I’m having problems installing a Local printer port via script. For years I’ve used scripts like below.
Creates Port:
cscript %windir%\system32\printing_admin_scripts\en-us\prnport.vbs -a -r "IP_1.1.1.1" -h "1.1.1.1" -o raw

Open in new window

Installs Printer to above specified port:
rundll32.exe printui.dll,PrintUIEntry /if /b "Printer Name" /f “Printer Driver Path\file.inf" /r "IP_1.1.1.1" /m "Printer XXX"

Open in new window

I’ve used this successfully for decades, it keeps everything exactly the same and saves tons of time.

My problem:
I need to make a nul printer, which I can do manually no problem, but I’ll be damned if I can figure out how to make a local nul port with a script.
This works fine if I manually make the Nul Printer through the gui:
rundll32.exe printui.dll,PrintUIEntry /if /b "NullPrinter" /f "%windir%\inf\ntprint.inf" /r "nul:" /m "Printer XXX"

Open in new window

but I would rather not have to create the NUL: port manually on 300 systems if possible.

The problem I’m sure is the” –h” switch,  which tells it there is an IP address. If I run it like:
cscript %windir%\system32\printing_admin_scripts\en-us\prnport.vbs -a -r "nul:" -h "nul:" -o raw

Open in new window

It does create the port, but it creates it as a Standard TCP/IP port which of course is not what I need and does not function as a NUL port. I’ve tried every variation of syntax I can come up with and none seem to work. I’ve looked for the last couple of hours on the internet and everything always references creating an IP port not a Local Port like NUL.

Any help would be great.
Thanks
1
I have a vb.net program and I don't want the form to be visible.  I tried using both Me.Hide and Me.Visible = false in the Form Load sub, but the form still shows. I thought there was a setting in the properties of the form in Visual Studio that could be set to hidden, but I can't find such a setting.

The only way I could get it to be hidden was to set the Opacity to 0%, but I thought there was a setting in Visual Studio or vb code that would accomplish this.
0
Good Morning,

I want to be able to attach all PDF's that are located in a folder to an email.

I was going to use something like this

.AddAttachment "D:\folder\*.pdf"

Any ideas/
0
PMI ACP® Project Management
LVL 19
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Hello experts,

I am looking for a procedure that covers the following requirement:
Þ      Loop the various files located in a directory (drill down not needed)
Þ      Get the number of lines of each file
Þ      Output file name of each file located in the directory;Count Lines in a csv file.
Þ      Csv file should be composed as following Count-files_YYYYMMDD_HHMMSS.csv
Þ      Directory will be composed exclusively of txt, csv, xls, xlsx files. If get count of xls, xlsx is complicated, I will manage just txt and csv files
Þ      Powershell, Windows Batch, VB Script are more than welcome.

If you have questions, please contact me.
1
Hello experts,

The following script allows me to copy folder from one folder to another:

' Text file I/O constants
Const cForReading = 1
Const cForWriting = 2
Const cForAppending = 8
Const cTristateTrue = -1
Const cTristateFalse = 0
Const cTristateUseDefault = -2

Dim errMsg , strFile , msg1 , strPath
Dim workingDir , strBaseDir , strLog1 , objLog
Dim arrFolders
Dim objFSO, objOrgDict

' Define variables, folders and files you want to work it
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOrgDict = CreateObject("Scripting.Dictionary")
objOrgDict.CompareMode = vbTextCompare
workingDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strLog = workingDir & "\log-copy.txt"
arrFolders = Array("Daily")
strBaseDir1 = "\\Server\Daily"
strBaseDir2 = workingDir


dtmStartTime = Timer * 100

' Define log variable
Set objLog = objFSO.OpenTextFile(strLog, cForAppending, True)

CopyArrayFolders arrFolders, strBaseDir1,strBaseDir2

dtmEndTime = Timer * 100
lngElaps = dtmEndTime - dtmStartTime
objLog.WriteLine Now & " INFO: " & WScript.ScriptName & " completed with elapsed time: " & FormatElapsedTime(lngElaps)
MsgBox WScript.ScriptName & " completed with elapsed time: " & FormatElapsedTime(lngElaps)

objLog.Close
WScript.Quit

'----------------------------------------------------------------------------
' Copy Files based on an Array
'----------------------------------------------------------------------------
Sub CopyArrayFolders(darrFolder, dInputDir, 

Open in new window

0
Hello experts,

The following VB Script allows me to remove & delete files based on multiple parameters.

I would like to add the following improvements:
-Be able to report multiple extensions related to files to remove example: .csv;.pdf;.log
-Be able to generate a log as following: DateStamp_log-file.log. Date stamp defined as following: YYYYMMDD_HHMMSS.

If you notice additional adjustments, please let me know.

Thank you very much for your help.

' Set processing mode flags
Const UseCreatedDate = "C"
Const UseModifiedDate = "M"
Const UseAccessedDate = "A"

' Text file I/O constants
Const ForAppending = 8


' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Define Script Dir folder and log folder
WorkingDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strLogFile = WorkingDir & "\" & WScript.ScriptName & "-log.txt"

' Open log file for appending
Set objLog = objFSO.OpenTextFile(strLogFile, ForAppending, True)

'Root folder that contains the subfolders to purge

PurgeFolder= strWorkingDir &"\Archive"
PurgeExtensions = ""  'Blank for all extensions
' Make sure base archive folder exists, exit if not
FolderExist PurgeFolder
' Parms are: Base folder, days to keep files, file date to use for age check, process subfolders flag, remove empty folders flag, initial level (always 0), extensions to purge
RemoveOldFiles objFSO.GetFolder(PurgeFolder), 0, UseModifiedDate, True, True, 0, PurgeExtensions

 ' Wrap 

Open in new window

0
Good Morning Experts,
I  have just discovered that I can no longer use Outlook's code behind the form that uses vb-script as the underlying programming environment. I have been building custom forms for various people,small offices, and Healthcare companies since code behind the form with vb-script began in 1997. I have been out of the loop for a few years because  of various disabilities. The last time I created forms for an entity was in Outlook 2013. Fast forward six years and I've discovered that even-though the choose/design developer form is still available,it  wont fire off the Item_Open function which is where my vb-script code goes. However I suspect that even if I put code outside of the Item_Open function it still wouldn't work. To prove this, I tried the following code snippet: (I have submitted screen shots of the process)

DevloperTab_Choose_Or_Design_A_ Form
PersonalFormsLibrary - TestDataBase
DesignViewForm
ScriptEditorViewCode
RanTheFormAndItShouldHaveEchoedaHelloInsidepopup
The Result should have been a simple message that said "helloinside"

You will notice that I kept it simple. I took out the actual code that was supposed to run to test my theory about the Item_Open function simply not firing. Here are some helpful (hopefully) articles that I have researched on the internet ,that speak to the Item_Open Function:


Outlook custom form: Item_Open event not getting fired

KB3203467 KB3191938 KB3191932 stopping the VB script in Outlook Custom Form in 2010/2013/2016/O365
0
I am looking for a solution that searches folders and sub folders for CSV files. Then merged all the files into one main file
0
Hello experts,

The following procedure allows me to split csv files into a DateStamp folder:

' ==============================================================================
' C O N S T A N T S   &   V A R I A B L E S
' ==============================================================================

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const TriStateUseDefault = -2



' Specify path to folder of files to process and log file

WorkingDir = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
strLogFile = WorkingDir & "\log-file.txt"
strStamp = TimeStamp(Now)

' ==============================================================================
' I N I T I A L I Z A T I O N
' ==============================================================================

' Create filesystem object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Open log file (append)
Set objLogFile = objFSO.OpenTextFile(strLogFile, ForAppending, True)

' ==============================================================================
' M A I N   L O G I C
' ==============================================================================

Split_CSV "ImportCC_20180424-1624.csv","ImportCC_20180424-1624",20

' ==============================================================================
' W R A P U P
' ==============================================================================

' Done, cleanup and exit
objLogFile.Close
'objInputFile.Close

Open in new window

0

VB Script

37K

Solutions

20K

Contributors

VBScript (Visual Basic Scripting Edition) is an interpreted scripting language developed by Microsoft that is modeled on Visual Basic, but with some important differences. VBScript is commonly used for automating administrative and other tasks in Windows operating systems (by means of the Windows Script Host) and for server-side scripting in ASP web applications. It is also used for client-side scripting in Internet Explorer, specifically in intranet web applications.