首页 > 解决方案 > 如何使用powershell同时为目录中的所有.exe文件创建多个快捷方式

问题描述

嗨,我想使用 powershel 和类似的东西同时创建几个快捷方式

Get-ChildItem -Path D:\something\ -Include *.exe -File -Recurse -ErrorAction SilentlyContinue

获取结果并为所有 .exe 文件生成快捷方式(.lnk 文件)

(.exe 只是文件类型的一个例子)

你能帮我吗?谢谢

标签: windowspowershellexeshortcut

解决方案


要在目录中创建所有文件的快捷方式.exe,您可以执行以下操作:

  • 创建Windows 脚本宿主COM 对象以创建快捷方式。您可以查看使用 MSDN 中的New-Object 创建 COM 对象以获取更多信息。
  • 获取.exe目录中的所有文件。类似于你已经用Get-ChildItem.
  • 迭代这些文件中的每一个。可以使用foreachForeach-Object在这里。
  • BaseName从文件中提取。这意味着testtest.exe. 我们需要它来制作快捷方式文件。
  • 从路径创建快捷方式。该路径只是目标路径+文件名+.lnk扩展名。我们可以使用Join-Pathhere来制作这条路径。
  • 将快捷方式的目标路径设置为可执行文件并保存快捷方式。

示范:

$sourcePath = "C:\path\to\shortcuts"
$destinationPath = "C:\path\to\destination"

# Create COM Object for creating shortcuts
$wshShell = New-Object -ComObject WScript.Shell

# Get all .exe files from source directory
$exeFiles = Get-ChildItem -Path $sourcePath -Filter *.exe -Recurse

# Go through each file
foreach ($file in $exeFiles)
{
    # Get executable filename
    $basename = $file.BaseName

    # Create shortcut path to save to
    $shortcutPath = Join-Path -Path $destinationPath -ChildPath ($basename + ".lnk")

    # Create shortcut
    $shortcut = $wshShell.CreateShortcut($shortcutPath)

    # Set target path of shortcut to executable
    $shortcut.TargetPath = $file.FullName

    # Finally save the shortcut to the path
    $shortcut.Save()
}

推荐阅读