当前位置:  开发笔记 > 后端 > 正文

使用Powershell编辑快捷方式(.lnk)属性

如何解决《使用Powershell编辑快捷方式(.lnk)属性》经验,为你挑选了2个好方法。

我发现了一个令人讨厌的VBS方法,但我正在寻找一个原生的PoSh程序来编辑.LNK文件的属性.目标是联系远程计算机,复制具有大多数正确属性的现有快捷方式,并编辑其中的几个.

如果编写新的快捷方式文件会更容易,那也可以.



1> JasonMArcher..:
Copy-Item $sourcepath $destination  ## Get the lnk we want to use as a template
$shell = New-Object -COM WScript.Shell
$shortcut = $shell.CreateShortcut($destination)  ## Open the lnk
$shortcut.TargetPath = "C:\path\to\new\exe.exe"  ## Make changes
$shortcut.Description = "Our new link"  ## This is the "Comment" field
$shortcut.Save()  ## Save

在这里找到了VB版本的代码:http: //www.tutorialized.com/view/tutorial/Extract-the-target-file-from-a-shortcut-file-.lnk/18349



2> Tim Lewis..:

下面是我用来处理.lnk文件的函数.他们被修改的发现功能的版本在这里由@Nathan哈特利提及.我已经改进Get-Shortcut了处理通配符,例如*通过传递字符串dir将它们扩展为多组FileInfo对象.

function Get-Shortcut {
  param(
    $path = $null
  )

  $obj = New-Object -ComObject WScript.Shell

  if ($path -eq $null) {
    $pathUser = [System.Environment]::GetFolderPath('StartMenu')
    $pathCommon = $obj.SpecialFolders.Item('AllUsersStartMenu')
    $path = dir $pathUser, $pathCommon -Filter *.lnk -Recurse 
  }
  if ($path -is [string]) {
    $path = dir $path -Filter *.lnk
  }
  $path | ForEach-Object { 
    if ($_ -is [string]) {
      $_ = dir $_ -Filter *.lnk
    }
    if ($_) {
      $link = $obj.CreateShortcut($_.FullName)

      $info = @{}
      $info.Hotkey = $link.Hotkey
      $info.TargetPath = $link.TargetPath
      $info.LinkPath = $link.FullName
      $info.Arguments = $link.Arguments
      $info.Target = try {Split-Path $info.TargetPath -Leaf } catch { 'n/a'}
      $info.Link = try { Split-Path $info.LinkPath -Leaf } catch { 'n/a'}
      $info.WindowStyle = $link.WindowStyle
      $info.IconLocation = $link.IconLocation

      New-Object PSObject -Property $info
    }
  }
}

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


我只是想让你知道这些功能很精彩,我很感激你发布它们.他们在Robocopy工作中为我节省了大量麻烦.
如果你得到像.TargetPath这样的空白属性,请注意CreateShortcut()需要完整的.CNK文件的UNC路径.它忽略了当前目录,".\ myshortcut.lnk"也失败了.您没有收到错误,只是空属性.
推荐阅读
拾味湖
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有