LoginSignup
1
3

More than 1 year has passed since last update.

Node.jsでWindowsのショートカット(.lnkファイル)を作成する

Last updated at Posted at 2021-04-29

概要

ユーザー権限で作成・削除が可能なショートカット(リンク)を作成する。
使用例:exe化したポータブルアプリでスタートアップへの登録。

方法

PowerShellのショートカット作成コマンドをchild_process.execから実行する。
ショートカットなので、ファイルでもディレクトリでもリンクが作成可能。
削除する場合は、fs.unlinkでショートカットのlnkファイルを削除すればよい。

code.ts
import { exec } from "child_process"

// 作成したいショートカットのパス (末尾の.lnkが必要)
let dist = "C:\\path\\to\\shortcut.lnk"

// リンク元としたいディレクトリorファイルパス
let source = "C:\\path\\to\\target"

// ショートカット作成コマンド
let command = `
  $WshShell = New-Object -ComObject WScript.Shell;
  $ShortCut = $WshShell.CreateShortcut("${dist}");
  $ShortCut.TargetPath = "${source}";
  $ShortCut.Save();
  `

// 第2引数でPowershellを指定して実行
exec(command, {"shell":"powershell.exe"})

その他のプロパティ

TargetPath以外にも、WshShortcutオブジェクトの各種プロパティ(ホットキー, 作業フォルダ等)を設定できるようだ。
WshShellオブジェクトの詳細(2) - @IT - ITmedia

参考サイト

ショートカット(lnk)の作成 - yanor.net/wiki
Using PowerShell to Create a Shortcut - ComputerPerformance

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3