Friday, January 9, 2009

Script Code: “Pepsi” is the Same in Most Languages

It’s true.  If you go to almost any place on Earth and say “Pepsi” they will know what you’re talking about.  Sometimes this applies to programming languages and scripting languages (an ambiguous, arguable distinction in my opinion).  By the way, technically, officially: when is a script a script and not a program?

Anyhow, one of the most common tasks do perform with a script is creating a shortcut.  In most cases, you will want to make a function to handle this so that you can reuse it and simply pass in parameters/arguments to modify the desired properties for a given purpose.  The code looks remarkably the same in KiXtart, VBscript and PowerShell.  Check it out.  See if you guess which chunk is in what language:

Example 1

Function NewShortcut ($Source, $Target, $Args, $Desc, $Icon, $Working, $Window, $Hotkey)
    $objShell = CreateObject("Wscript.Shell")
    $objLink = $objShell.CreateShortcut($Target)
    $objLink.TargetPath = $Source
    If $Args <> ""
        $objLink.Arguments = $Args
    EndIf
    If $Desc <> ""
        $objLink.Description = $Desc
    EndIf
    If
$Icon <> ""
        $objLink.IconLocation = $Icon
    EndIf
    If
$Working <> ""
        $objLink.WorkingDirectory = $Working
    EndIf
    If
$Window > 0 And $Window < 4
        $objLink.WindowStyle = $Window
    EndIf
    If
$Hotkey <> ""
        $objLink.Hotkey = $Hotkey
    EndIf
    $objShell = 0
EndFunction

Example 2

Sub NewShortcut (sSource, sTarget, sArgs, sDesc, sIcon, sWorking, iWindow, sHotkey)
    Set objShell = CreateObject("Wscript.Shell")
    Set objLink = objShell.CreateShortcut(sTarget)
    objLink.TargetPath = sSource
    If sArgs <> "" Then
        objLink.Arguments = sArgs
    End If
    If
sDesc <> "" Then
        objLink.Description = sDesc
    End If
    If
sIcon <> "" Then
        objLink.IconLocation = sIcon
    End If
    If
sWorking <> "" Then
        objLink.WorkingDirectory = sWorking
    End If
    If
iWindow > 0 And iWindow < 4 Then
        objLink.WindowStyle = iWindow
    End If
    If
sHotkey <> "" Then
        objLink.Hotkey = sHotkey
    End If
    Set
objShell = Nothing
End Sub

Example 3

Param
(
    [string]$Source
    [string]$Target = $Source + ".lnk",
    [string]$Arguments$null,
    [string]$Description$null,
    [string]$IconLocation$null,
    [string]$WorkingDirectory$null,
    [int]$WindowStyle$null,
    [string]$Hotkey = $null
)
$WshShell = New-Object -ComObject WScript.Shell
$link = $WshShell.CreateShortcut($Target);
$link.TargetPath = $Source;

if ($Arguments) {$link.Arguments = $Arguments;}
if ($Description) {$link.Description = $Description;}
if ($IconLocation) {$link.IconLocation = $IconLocation;}
if ($WorkingDirectory) {$link.WorkingDirectory = $WorkingDirectory;}
if ($WindowStyle) {$link.WindowStyle = $WindowStyle;}
if ($Hotkey) {$link.Hotkey = $Hotkey;}
$link.Save();

No comments: