Fishaffair
Fishaffair

Reputation: 3

Why shortcuts are not created?

i have trouble in powershell (Windows 10 1809) I want that this script seach all .exe files in my directory D:\Test in Recursive mode and make shortcuts in D:\ . But my code just creating link.lnk in D:\ . Why?

$1 = get-childitem "D:\Test" -recurse | where {$_.extension -eq ".exe"} | % {
Write-Host $_.FullName
}
ForEach ($item in $1)  {
$Shell = New-Object -ComObject ("WScript.Shell")
$ShortCut = $Shell.CreateShortcut("D:\link.lnk")
$ShortCut.TargetPath= $1
$Shortcut.Save()
}

Upvotes: 0

Views: 41

Answers (1)

HAL9256
HAL9256

Reputation: 13523

It looks like you are naming all of the shortcuts D:\link.lnk, and the loop will just overwrite the same name over and over. Specifying a unique shortcut link filename using the BaseName property (name minus the extension) should solve your problem. Also you need to use the loop $item to specify the TargetPath.

Also, the by looping through with the Write-Host you don't actually assign anything to your variable $1. By removing the % { Write-Host $_.FullName } $1 does get the proper output. So the proper code should be:

$1 = get-childitem "D:\Test" -recurse | where {$_.extension -eq ".exe"}

ForEach ($item in $1)  {
    Write-Host "Creating Shortcut: D:\$($item.BaseName).lnk  Pointing to: $($item.FullName)"
    $Shell = New-Object -ComObject ("WScript.Shell")
    $ShortCut = $Shell.CreateShortcut("D:\$($item.BaseName).lnk")
    $ShortCut.TargetPath= $item.FullName
    $Shortcut.Save()
}

Upvotes: 1

Related Questions