Home > OS >  How to programatically set Shortcuts TargetPath to a website?
How to programatically set Shortcuts TargetPath to a website?

Time:05-09

I want to use powershell to modify the TargetPath of a shortcut to open a website I found the below script that almost works

function Set-Shortcut {
  param(
  [Parameter(ValueFromPipelineByPropertyName=$true)]
  $LinkPath,
  $Hotkey,
  $IconLocation,
  $Arguments,
  $TargetPath
  )
  begin {
    $shell = New-Object -ComObject WScript.Shell
  }

  process {
    $link = $shell.CreateShortcut($LinkPath)

    $PSCmdlet.MyInvocation.BoundParameters.GetEnumerator() |
      Where-Object { $_.key -ne 'LinkPath' } |
      ForEach-Object { $link.$($_.key) = $_.value }
    $link.Save()
  }
}

However

Set-Shortcut -LinkPath "C:\Users\user\Desktop\test.lnk" -TargetPath powershell start process "www.youtube.com"

Will default out to attaching a default path if you do not define one to look like:

"C:\Users\micha\Desktop\powershell start process "www.youtube.com""

how do I get rid of that default file path?

BONUS: I'd be appreciative if someone broke down this line of code:

ForEach-Object { $link.$($_.key) = $_.value }

CodePudding user response:

have you tried to change the properties of the shortcut object directly?

Try this and let me know:

function Set-Shortcut {

[CmdletBinding()]
param (
    [Parameter(Mandatory, Position = 0, ValueFromPipeline)]
    [System.String]$FilePath,

    [Parameter(Mandatory, Position = 1)]
    [System.String]$TargetPath
)

Begin {
    $shell = new-object -ComObject WScript.Shell
}

Process {
    try {
        $file = Get-ChildItem -Path $FilePath -ErrorAction Stop

        $shortcut = $shell.CreateShortcut($file.FullName)
        $shortcut.TargetPath = $TargetPath
        $shortcut.Save()    
    }
    catch {
        throw $PSItem
    }
}

End {
    while ($result -ne -1) {
        $result = [System.Runtime.InteropServices.Marshal]::ReleaseComObject($shell)
    }
}
  • Related