Reputation: 1
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
Reputation: 1161
So a few things to note here:
Get-Childitem
instead of dir
... | Foreach-Object { ...
instead of ... | % ...
$_
variable within the loop instead of looping within a loop$Destination
is no longer used$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:
"C:\C:\IBM-Shortcuts\*.hod"
, this has one too many C:\
in it.$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"
foreach
loop hereUpvotes: 1