LiQuiD_FuSioN
LiQuiD_FuSioN

Reputation: 1

Reading Directory + Creating Shortcuts with PowerShell

everyone. I'm trying to figure out a way to read the contents of a directory in Windows and find files of a specific file extension ('.hod' in this case), then create shortcuts to each of those files into 'C:\Users\Public\Desktop.'

Below is an example I've been testing with so far in PowerShell (I know it looks utterly terrible). I'd appreciate any input. Thanks.

$shortcutfiles = dir "C:\C:\IBM-Shortcuts\*.hod"
$DestinationDir = "C:\Users\Public\Desktop"
foreach ($shortcutfile in $shortcutfiles ) {
$TargetPath = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.FullName }
$BaseName = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.BaseName }
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$DestinationDir" & "$BaseName"+lnk)
$Shortcut.TargetPath = "$TargetPath"
$Shortcut.Save()
}

Upvotes: 0

Views: 246

Answers (1)

Otter
Otter

Reputation: 1161

So a few things to note here:

  • Use Full cmdlet names instead of alias', this for clarity.
    • Get-Childitem instead of dir
    • ... | Foreach-Object { ... instead of ... | % ...
  • Only iterate over the folders contents once and reference the $_ variable within the loop instead of looping within a loop
  • if a variable is only being used once then don't bother storing it in its own variable
    • $Destination is no longer used
  • Indent your code following basic formatting rules
  • As @mklement0 mentioned, it's worth executing $WshShell = New-Object -comObject WScript.Shell only once, before the pipeline.
$WshShell = New-Object -comObject WScript.Shell

Get-ChildItem "C:\IBM-Shortcuts\*.hod" | Foreach-Object {
    $Shortcut = $WshShell.CreateShortcut("C:\Users\Public\Desktop\$($_.BaseName).lnk")
    $Shortcut.TargetPath = $_.FullName
    $Shortcut.Save()
}

Some other things to note:

  • On line 1 you are referencing "C:\C:\IBM-Shortcuts\*.hod", this has one too many C:\ in it.
  • Your use of $TargetPath = Get-ChildItem "C:\IBMiACS-Shortcuts" -Filter *.hod -Recurse | % { $_.FullName } is not setting the targetpath for the current iteration of $Shortcutfile, it is returning a list of all file paths in "C:\IBMiACS-Shortcuts"
  • Take a look into the basics of a foreach loop here

Upvotes: 1

Related Questions