I need to delete a desktop shortcut if one reg key is present. I tried with the following:
$regPath = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\37efc56c15cbf10bt"
$shortcutPath = "c:\Users\Public\Desktop\notepad.lnk"
# Check if the registry key exists
if (Test-Path -Path $regPath) {
Remove-Item -Path $shortcutPath -force
}
To make PowerShell recognize your path as a registry path, you have two options:
Prepend registry::
, i.e. a provider prefix, to a native registry path:
$regPath = 'registry::HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\37efc56c15cbf10bt'
Or - assuming that the native registry path has an equivalent PowerShell drive - such as, in this case, HKCU:
to refer to the HKEY_CURRENT_USER
registry hive:
$regPath = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\37efc56c15cbf10bt'
In the absence of either approach, a path such as HKEY_CURRENT_USER\...
is interpreted as a relative path in the context of the provider underlying the current location, which is typically a file-system location (i.e. one provided by the FileSystem
provider).
By contrast, a path such as c:\Users\Public\Desktop\notepad.lnk
, due to starting with a drive specification, is unambiguous, because the specified drive implies the underlying provider.
Separately, as you note yourself, it is better to use
Join-Path ([Environment]::GetFolderPath('CommonDesktopDirectory')) notepad.lnk
to determine your .lnk
file path based on the all-users desktop path instead of using hard-coded path c:\Users\Public\Desktop\notepad.lnk