How to Use VBScript to Run a PowerShell Script

How to Use VBScript to Run a PowerShell Script

  • Comments 12
  • Likes

Summary: Microsoft Scripting Guy, Ed Wilson, shows you that it's easier than you think to use VBScript to run a Windows PowerShell script.

Microsoft Scripting Guy, Ed Wilson, is here. Things are really heating up around here—and I am not just talking about the hot, humid weather down in Charlotte, North Carolina in the United States. First, I am busily getting ready for my trip to Seattle, Washington next week. I will be speaking about using Windows PowerShell 3.0 to manage the remote Windows 8 desktop to a bunch of Microsoft people from all over the world. The event (called TechReady 15) is like TechEd, only it is only for Microsoft employees. Nevertheless, in every other fashion, including the size and scope of the event, it is like TechEd. I really look forward to speaking at this event, because it is an honor to get to speak to so many smart people, and it is a great chance to see my friends from all over the world.

The second thing that is exciting are Windows 8 (which I have been running on my production machine for some time) and Office 15 (which I have just installed on my production machine). It is sooo cool, and is powerful, simple to use, and fun. Often powerful and simple do not go together in the computing world. This time, I think we did it right. The Scripting Wife is absolutely chomping at the bit to get a new slate device. I agreed to get her one for the holidays, but she wants it NOW!

The third thing that is super exciting is Windows PowerShell Saturday on September 15 at the Charlotte Microsoft office. We have just about finalized the schedule, and we have all the speakers lined up. It will be a super cool event. Keep watching, because we will be opening registration very soon, and expect it to sell out within days. We have to limit the attendance to 200 people, so you will want to ensure that you are watching for the announcement. The announcement of the opening of registration will take place on Twitter, then on Facebook on the Scripting Guys Facebook site, and then on the Scripting Guys blog, and finally on the Learn PowerShell page. So this would be a good time to get a twitter account and start following @ScriptingWife and @ScriptingGuys. By the way, I love the Rowi app on Windows 8.

Creating a VBScript to run Windows PowerShell

When creating a permanent WMI event consumer that uses the ActiveScriptEventConsumer WMI class, you need to use VBScript as the script type. This is because ActiveScriptEventConsumer does not know how to run a Windows PowerShell script. This is not a huge problem, however, because writing a VBScript script to launch a Windows PowerShell script is very easy when you know the secrets.

Note   This is the third blog in a five part series about monitoring a folder for the creation of files that have leading spaces in the file names. On Monday, I wrote Use PowerShell to Detect and Fix Files with Leading Spaces, and the scripts from that blog will be used today and again on Friday. On Tuesday, I wrote Use PowerShell to Monitor for the Creation of New Files. This blog talks about creating a temporary WMI event to monitor for the creation of files in a particular folder. This query is crucial to Friday’s blog.

There are two methods available from the WshShell Object to launch other programs. These methods are the Exec method and the Run method. For my purpose, I use the Run method. It takes two lines of VBscript code; therefore, I use Notepad to create the script. Remember to save it as a .vbs file. The script is shown here.

LaunchPowerShell.VBS

Set objShell = CreateObject("Wscript.shell")

objShell.run("powershell -noexit -file c:\fso\CleanupFiles.ps1")

The first line of code creates the WshShell object, and it stores the returned object in the objShell variable. This line is shown here.

Set objShell = CreateObject("Wscript.shell")

The second line of code runs the command. The syntax of this command is critical. It is a good idea to use the Start / Run command to practice the syntax before embedding it in the VBScript script. Here is an example of using the Run command to practice the syntax.

Image of command

If you need to bypass the execution policy, you would add that switch to the command as well. The syntax to bypass the execution policy is shown here.

powershell -executionpolicy bypass -noexit -file c:\fso\helloworld.ps1

It is also possible to run a specific Windows PowerShell command or series of commands from the VBScript script. This technique is shown here.

objShell.run("powershell -noexit -command ""&{0..15 | % {Write-Host -foreground $_ 'Hello World' }}""")

Note   Keep in mind that you are writing in VBScript. Therefore, you need to escape the quotation marks with another pair of quotation marks. Also, remember that you use REM to comment out a line, and not the pound sign character (#) that is used in Windows PowerShell.

The CleanupFiles.ps1 script referenced in the VBScript script is the Get-FilesWithLeadingSpaces function from Monday’s blog, Use PowerShell to Detect and Fix Files with Leading Spaces. I removed it from the function and placed it in a file to make it easier to call from within the VBScript script. The CleanupFiles.ps1 file is shown here.

CleanupFiles.ps1

Param(

       [string]$path = "c:\test",

       [switch]$rename = $true

       )

 Get-ChildItem -Path $path -Recurse |

 foreach-object -Begin {$count = 0} -process {

   if($_.name.length -ne $_.name.trim().length)

    {

     if($rename)

      {

        Rename-Item -Path $_.fullname -NewName ("{0}{1}{2}" -f `

         $_.basename.trim(),$count,$_.extension)

        $count++

        }

     else

      {"$($_.basename) contains a leading space"}} }

By using the New-FilesWithLeadingSpaces function from Monday, I create 10 new files with leading spaces in the names in a folder named test. These newly created folders are shown here.

Image of menu

Now, I want to try out my VBScript script to see if I can run it, and cause it to launch the Windows PowerShell script to clean up the folder. I open a command prompt, and drag the VBScript script to the command line. The command prompt is shown here.

Image of command output

When I run the script, a Windows PowerShell console appears, but it does not look like it really did anything. Here is the newly appearing Windows PowerShell console.

Image of command output

But when I go to the c:\test folder, I see that all the files are fixed. This is shown here.

Image of menu

That is all there is to using VBScript to run a Windows PowerShell script. WMI Event Monitoring Week will continue tomorrow when I will talk about using the WMI admin tools to monitor for newly arriving events.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Why the "noexit" switch out of curiousity for this example?

  • @Fred the only reason I added the -noexit switch to the example is so that you would see the Windows PowerShell console open and have a more visual indication that the script was working. In addition, if you wanted to run things like Get-Process or Get-Service and see the output then you would NEED the -noexit switch. If you are planning on using this technique to start some automation then you would NOT want the Windows PowerShell staying open. To do this you would want to use the -windowstyle hidden switch. This appears here.

    powershell -executionpolicy bypass -windowstyle hidden -command "&{get-process}"

  • I've found that using the ASCII code for quotation marks, CHR(34), instead of trying to ensure that I have the correct number of quotation marks makes for easier readability when I have to do this technique.  Using your example:

    objShell.run("powershell -noexit -command ""&{0..15 | % {Write-Host -foreground $_ 'Hello World' }}""")

    would actually look like this:

    objShell.run("powershell -noexit -command " & CHR(34) & "&{0..15 | % {Write-Host -foreground $_ 'Hello World' }}" & CHR(34) )

  • @ChrisK You are absolutely right, you can substitute chr(34) and a lot of people do find it easier to read. Personally, I do not do that (I have in the past) simply because it is a lot more typing. In addition, if you have a dedicated script editor, it will generally pick up when I have the correct number of quotation marks. But for extremely complicated examples, it DOES make things stand out a bit more, and it DOES make it easier to read. Thank you for your comment.

  • Don't forget:

    vbCr, vbLf, vbCrLf, vbTab

    All of the above are predefined in all VB langauges along with amny more:

    support.microsoft.com/.../211774

  • Is there a way to run a powershell script with elevated permissions?   Right now I have to open up PowerShell As Administrator and then run the script.  It would be nice to just click on a startup file and have it prompt for elevation and after entering credentials it would run.

  • @JRV you are absolutely correct. No, we do not want to forget about vbcrlf and the other oldie but goodies.

  • @Craig B From your VBScript launcher, call the runas utility. It will then elevate and prompt for credentials. The better way to do these things is in PowerShell 3.0 where you can set RUNAS in a constrained end point ... WAY cool stuff, and it solves the credential problem as well.

  • @Craig - Set advanced properties of teh shortcut to run as an admnistrator.  On an admin account it will just tell you it is going to run elevated and on a user account it will prompt for credentials.

    The 'RunAs' commandline utility will let you save an encrypted password. I do this on my normal 'limitied user' session as I almost never log in as an administrator.  If I need admin credentials I just start Explorer with a saved password (just double-click) or I run PosH or CMD.  Both Posh and CMD let me launch any utilities at the commandline as an elevated process.  I have been doing this since way before Vista.

  • @JRV that is a cool technique. Thanks for sharing it. Yes, I like RUNAS ... it is very flexible.

  • Hi Ed,

    this is the easy way to allow for powershell scripts even if other scripting languages are required!

    This workaround is quite OK, but it's a pity that we have still to do this!

    Klaus.

  • @K_Schulte yes it is a pity we have to still do this, but the good thing is that we CAN still do this :-) It opens up a lot of possibilities for using Windows PowerShell in areas where we might not have thought it was possible. A lot of automation products allow for the use of a VBScript file in an action item, but do not permit PowerShell. Using this technique, quite often a simple VBScript will suffice to launch the more powerful PowerShell script.