使用Powershell修改应用程序快捷方式时出错

问题描述

我有以下Powershell代码,当单击任务栏上的固定图标时,Chrome始终使用配置文件打开:

$shortcutPath = "$($Env:APPDATA)\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Google Chrome.lnk"
$shell = New-Object -COM WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)  ## Open the lnk
$shortcut.TargetPath

if ($shortcut.TargetPath.EndsWith("chrome.exe")) {
  $shortcut.TargetPath = """$($shortcut.TargetPath)"" --profile-directory=""Default"""
  $shortcut.Save()  ## Save
}

执行它时,if语句将引发以下错误

Value does not fall within the expected range.
At line:2 char:31
+   $shortcut.TargetPath = """$($shortcut.TargetPath)"" --profile-direc ...
+                               ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [],ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

为什么我遇到上述错误?以及如何解决?谢谢!

解决方法

您不应将参数添加到TargetPath属性中,而应在快捷方式的Arguments属性中进行设置:

$shortcutPath = "$($Env:APPDATA)\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\Google Chrome.lnk"
$shell = New-Object -COM WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)  ## Open the lnk

Write-Host "TargetPath = $($shortcut.TargetPath)"
Write-Host "Arguments  = $($shortcut.Arguments)"

if ($shortcut.Arguments -ne '--profile-directory="Default"' ) {
  $shortcut.Arguments = '--profile-directory="Default"'
  $shortcut.Save()  ## Save
}

# Important,always clean-up COM objects when done
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shortcut)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()