Tuesday, 17. February 2009 0:39
There’s a lot of useful, proven VBScript functions and libraries out there and it is virtually impossible and maybe foolish to rewrite all that good stuff in Windows PowerShell.
They key to use VBS code in PowerShell is the COM object MSScriptControl that is designed to act as a script host. Within a PowerShell script, you can use this object to embed VBScript, e.g. load VBS code, call a function from it, pass arguments to it, and get its return values. Sounds cool? Yes, it is!
The function below – Load-VbsCode – passes VBS code to MSScriptControl and returns a code object with methods that represent the functions defined within the VBS code:
function Load-VbsCode
{
param($vbsCode = $(throw "No VBS code specified."))
$vbs = New-Object -ComObject MSScriptControl.ScriptControl
$vbs.Language = "VBScript"
$vbs.AddCode([string]::Join("`n", $vbsCode))
$vbs.CodeObject
}
The AddCode() method expects a string. In order to prevent that an array of multiple text lines will be passed to the method, the data in $vbsCode will be converted to a string using Join.)
Let’s say that you have a VBS file called 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:
# get contents of the vbs file
$vbsCode = Get-Content .\ConvertFunctions.vbs
# pass the vbs code to Load-VbsCode
$vbs = Load-VbsCode($vbsCode)
# Ready to use the Celsius function...
$f = 70
$c = $vbs.Celsius($f)
Write-Host "$f Fahrenheit are $c Celsius."