Embed VBS Functions Within PowerShell


06-27-2009

Downloads: 414
File size: 323 B
Views: 1,737

Embed
Embed VBS Functions Within PowerShell
  1. function Load-VbsCode
  2.  
  3.     param
  4.         $Code = $(throw "No VBS code specified."
  5.     
  6.  
  7.     # Convert an array of multiple text lines to a string 
  8.     $vbsCode = [string]::Join("`n", $Code
  9.  
  10.     $vbs = New-Object -ComObject 'MSScriptControl.ScriptControl' 
  11.     $vbs.Language = "VBScript" 
  12.     $vbs.AddCode($vbsCode
  13.     $vbs.CodeObject 
You can reuse VBS code inside your PowerShell scripts. The key is the MSScriptControl COM object that is designed to act as a script host. Within a PowerShell script, you can use this object to embed VBS code, e.g. load VBS code, call a function from it, pass arguments to it, and get its return values. Sounds cool? It is! And it's not that difficult as well.
The attached function - Load-VbsCode - passes VBS code to MSScriptControl and returns a code object with methods that represent the functions defined within the VBS code.
Let's say you have a VBS file ConvertFunctions.vbs that, among others, contains this function:
Function Celsius(GradF)
   Celsius = (GradF - 32) * 5 / 9
End Function
The following example shows how to use the Load-VbsCode function in order to embed the above vbs code:
# pass the entire vbs file to Load-VbsCode
$vbs = Load-VbsCode $(Get-Content .\ConvertFunctions.vbs)
# Ready to use the Celsius function...
$f = 70
$c = $vbs.Celsius($f)
Write-Host "$f Fahrenheit are $c Celsius."
Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.