Creating a Start Menu Shortcut with Powershell and Python

[UPDATE 2008-05-13] Updated this post to use syntax Powershell 1.0 syntax instead of the original Monad syntax.

A simple example that shows you how to create Start Menu shortcut.

This example illustrates how to

  • get the location of a windows "Special Folder"
  • create and call methods on a COM object
  • call methods on a .NET Framework Object
  • create and check for the existence of a directory

Things to notice

  • Why does the Powershell script use a different way of finding the folder? I can't get the most obvious solution: $p = $sh.SpecialFolders("AllUsersPrograms") to work. I think this is because SpecialFolders is not a method but an indexed property and I don't know the correct syntax for using it.
  • I miss Python's "assert" command in Powershell. I had to simulate it by throwing an exception.

Powershell Example



$shortcut_group_name = "My Start Menu Shortcuts"
$shortcut_name = "Visit Microsoft's website"
$shortcut_target = ""

$sh = new-object -com "WScript.Shell" 
$p = $sh.SpecialFolders.item("AllUsersPrograms")
if ( -not ( test-path $p ) )
 throw "Folder does not exist"
$p= join-path $p $shortcut_group_name
if ( -not ( test-path $p ) )
 new-item $p -type directory
$lnk = $sh.CreateShortcut( (join-path $p $shortcut_name) + ".lnk" )  
$lnk.TargetPath = $shortcut_target



Python Example



import os
import sys
import win32com.client

shortcut_group_name = "My Start Menu Shortcuts"
shortcut_name = "Visit Microsoft's website"
shortcut_target = ""

sh = win32com.client.Dispatch( "WScript.Shell" )
p = sh.SpecialFolders("AllUsersPrograms")
assert( os.path.isdir(p) )
p= os.path.join( p, shortcut_group_name)
if ( not os.path.isdir(p) ) :
lnk = sh.CreateShortcut( os.path.join( p, shortcut_name + ".lnk" ))
lnk.TargetPath = shortcut_target


Comments (1)

  1. Alan Lilly says:

    How in python would you remove a program shortcut from a given program group?

Skip to main content