0

I have following Powershell code that make Chrome always opened using default profile when clicked on pinned icon on Taskbar:

$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
}

When executing it, the if statement throw below error:

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

Why I get above error? And how to fix it? Thank!

1 Answer 1

5

You should not add the parameter(s) to the TargetPath property, but instead set these in the shortcut's Arguments property:

$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()
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! I don't see the Arguments field when I edit the shortcut using UI, so I don't know there is an option for it. And I pretty like the GC as well, you're surely know about PS and COM very well!
@TuyenPham Ha, not well enough it seems, because I forgot to do a ReleaseComObject on the $shell itself earlier. I've put that line in now as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.