如何以编程方式将快捷方式 TargetPath 设置为网站?

How to programatically set Shortcuts TargetPath to a website?

我想用powershell修改快捷方式打开网站的TargetPath 我发现下面的脚本几乎可以工作

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()
  }
}

但是

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

如果您没有定义一个默认路径,将默认附加一个默认路径:

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

如何删除默认文件路径?

奖金: 如果有人分解了这行代码,我将不胜感激:

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

您是否尝试过直接更改快捷方式对象的属性?

试试这个让我知道:

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)
    }
}