Home > Blockchain >  Trying to use PowerShell to create a URL shortcut on desktop using a variable for the URL
Trying to use PowerShell to create a URL shortcut on desktop using a variable for the URL

Time:09-01

I work in higher ed and we need the computers in each of our 100 classrooms to have a URL shortcut on the desktop to the room camera's IP address. I am trying to automate this using a PowerShell script. I have created a script that has a table, looks up the computer name, looks it up in the table to find the associated IP address, and creates a URL shortcut on the desktop. Unfortunately, I get an error any time I try to pass the $IP variable to $urlShortcut.TargetPath. I'm hoping this is an easy fix? Thanks in advance!

Here is a genericized version of my script. If I replace $urlShortcut.TargetPath = $IP with $urlShortcut.TargetPath = "https://www.google.com", for example, it creates the shortcut to Google.

#Create table
$table = @{}
$table.Add('Room 1,'1.1.1.1')
$table.Add('Room 2','1.1.1.2')

#Determine computer name
$CPUName = $env:computername

#Determine IP address based on room
$IP = $table[$CPUName]

#Display IP Address
write-output $IP

#Create shortcut on desktop
$wshShell = New-Object -ComObject "WScript.Shell"
$urlShortcut = $wshShell.CreateShortcut(
  (Join-Path $wshShell.SpecialFolders.Item("AllUsersDesktop") "Camera Control.url")
)
$urlShortcut.TargetPath = $IP
$urlShortcut.Save()

CodePudding user response:

Mathias R. Jessen has provided the crucial pointer:

  • Use "http://$IP/" instead of just $IP when assigning to $urlShortcut.TargetPath, given that you want to open a URL.

The command forms that shortcut files support in their .TargetPath property are those recognized by the ShellExecuteEx WinAPI function, which both PowerShell's Start-Process cmdlet and cmd.exe's internal start command wrap.

Thus, you can test commands for shortcut files using Start-Process; e.g.:

# !! WRONG 
# Without a protocol specifier such as http:, the URL isn't recognized.
Start-Process example.org

# OK
Start-Process https://example.org

However, what Start-Process does not do[1] - unlike shortcut files and cmd.exe's start command - is to expand cmd.exe-style environment variable references such as %windir%.

Thus, a complete emulation of what a shortcut-file command line will do, from PowerShell, requires calling cmd.exe's internal start command via cmd /c; e.g., to test command line notepad.exe %windir%\win.ini:

cmd /c 'start "" notepad.exe %windir%\win.ini'

Note: The "" argument preceding the command line binds to start's argument for specifying a window title for the new process (which only applies to calling console applications). Binding this argument allows you to use "..."-enclosed executable paths as part of the command line to test.


[1] Owing to the behavior of the .NET API it builds on, System.Diagnostics.Process.

  • Related