Powershell Tutorial – Create COM object


Powershell is becoming more and more popular especially in the field of Windows Administrative Tasks. The syntax to create COM object in Powershell is intuitive and easy. See following code example:

<#
    Example: Create COM object in PowerShell
    https://HelloACM.com
#>

# create COM object WScript.Shell
$WSH = New-Object -ComObject "WScript.Shell"
$WSH.Popup("Hello from PowerShell!")

The one-line comment starts with the sharp symbol and the multiple-line comment is wrapped by <# .. #>. It is not possible to do a multi-line comment in batch and VBScript.

Creating COM object greatly enhances the scripting functionality and thus Powershell is easier and more powerful than VBScript/JScript in the terms of administrative tasks. In the simple batch (*.bat), it is not possible to create COM objects without the external command (e.g. running VBScript via cscript.exe interpreter). The Powershell will thus replace batch for advanced server administrative tasks.

You can wrap above into a simple function with 1 parameter in Powershell, and the variable (parameter) can be included using double quotes (similar to PHP).

<#
    Example: Create COM object in PowerShell
    https://HelloACM.com
#>

function sayHello($msg) {
    $WSH = New-Object -ComObject "WScript.Shell"
    $WSH.Popup("Hello $msg")
}

sayHello("justyy!")

If it is single quote, the string is as it is without further interpreting the sub-string starting with dollar sign (variables). You can also use the Plus sign to concatenate strings just like other programming languages.

function sayHello($msg) {
    $WSH = New-Object -ComObject "WScript.Shell"
    $WSH.Popup("Hello " + $msg)  # single quote is also ok here.
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
307 words
Last Post: Create a ShortCut/BookMark in Chrome to the Links Shortener using Javascript
Next Post: Using Resharper - Turning to LINQ

The Permanent URL is: Powershell Tutorial – Create COM object

Leave a Reply