Add multiple paths to a variable in powershell

Can
Can used Ask the Experts™
on
Hi All,

Im a noob at powershell, i need some help; I want to create a shortcut to 2 different paths, to my desktop and documents folder. This is my script:

$SourceFileLocation = "C:\AAA\BBB\CCC.exe"
$ShortcutLocation = “C:\Users\AAA\Desktop\BBB.lnk”
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation)
$Shortcut.TargetPath = $SourceFileLocation
$Shortcut.Save()

This work fine for creating one shortcut. Yet, i want to add a second path to the $Shortcutlocation variable. A simple comma does not seem to work. Any ideas how to do this?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
You need a loop:
$WScriptShell = New-Object -ComObject WScript.Shell
$ShortcutName = "BBB.lnk"
$SourceFileLocation = "C:\AAA\BBB\CCC.exe"
[environment]::GetFolderPath('Desktop'), [environment]::GetFolderPath('MyDocuments') | ForEach-Object {
	$ShortcutLocation = "$($_)\$($ShortcutName)"
	$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation)
	$Shortcut.TargetPath = $SourceFileLocation
	$Shortcut.Save()
}
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($WScriptShell) | Out-Null

Open in new window

And you shouldn't hard-code user profile paths, and clean up com objects.
"Batchelor", Developer and EE Topic Advisor
Top Expert 2015
Commented:
Adding a comma to the variable content would create an array. But many commands and in particular Windows object methods like WScript.Shell.CreateShortCut do not allow to provide an array, only single values. So you need to use a loop:
$SourceFileLocation = 'C:\AAA\BBB\CCC.exe'
$ShortcutLocation = 'C:\Users\AAA\Desktop\BBB.lnk', 'C:\Users\AAA\Desktop\CCC.lnk'
$WScriptShell = New-Object -ComObject WScript.Shell

foreach ($dest in $ShortcutLocation)
{
  $Shortcut = $WScriptShell.CreateShortcut($dest)
  $Shortcut.TargetPath = $SourceFileLocation
  $Shortcut.Save()
}

Open in new window

Instead of your documents folder I used the desktop another time, but that should be easy to adjust for you ;-).
CanSystem Administrator

Author

Commented:
Thank you guys,  This was what i needed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial