(PowerShell) ドラッグ&ドロップしたフォルダ内のショートカットを置換
概要
やりたいこと:
ドラッグアンドドロップしたフォルダを再帰的に走査してショートカットファイルのパスを置換。
必要な準備:
「*.ps1」スクリプトを動かす設定。
重要:
動作確認はまだ。ツギハギだし言語知識不足なのでおそらく動かない。
コード
#=============================================================================== # 定数 #=============================================================================== # 置換前ディレクトリ Set-Variable -Name replacingDirBef -Value 'path\to\before' -Option Constant # 置換後ディレクトリ Set-Variable -Name replacingDirAft -Value 'path\to\after' -Option Constant #=============================================================================== # パス置換関数 #=============================================================================== function ReplacePath([string] $path) { $path = $path -ireplace $replacingDirBef, $replacingDirAft return $path } #=============================================================================== # メイン #=============================================================================== Write-Output "処理開始" # ショートカット編集用WSHオブジェクト $wsShell = New-Object -ComObject WScript.Shell # 引数すべて処理 foreach($arg in $Args) { # ショートカットファイル一覧の取得 # サブディレクトリを含む # 隠しファイルや読み取り専用ファイルは対象外 $shortcuts = Get-ChildItem -LiteralPath $arg *.lnk -Recurse # 各ショートカットの置換 $shortcuts | ForEach-Object { # ショートカット作成 $link = $wsShell.CreateShortcut($_.FullName) # 置換後のパス生成 $newTargetPath = ReplacePath($link.TargetPath) # 置換前後で変更がない場合はメッセージ出力して次のファイルの処理へ if ($link.TargetPath -eq $newTargetPath) { Write-Output ("置換不要: " + $_.FullName) return } # ショートカットの参照先と作業フォルダを更新 $link.TargetPath = $newTargetPath $link.WorkingDirectory = ReplacePath($link.WorkingDirectory) $link.Save(); Write-Output ("置換実施: " + $_.FullName) } } Write-Output "処理完了" Read-Host "press any key to close."