Search code examples
windowspowershellexeshortcut

how to create several shortcuts at the same time for all .exe files in a directory using powershell


Hi I want to create several shortcuts at same time using powershel and something like this

Get-ChildItem -Path D:\something\ -Include *.exe -File -Recurse -ErrorAction SilentlyContinue

get the results and generate shortcuts(.lnk files) for all .exe files

(.exe is just one example of file type)

Can u help me? thx


Solution

  • To create shortcuts of all your .exe files in a directory, you can do the following:

    • Create Windows Script host COM object to create shortcuts. You can have a look at Creating COM Objects with New-Object from MSDN for more information.
    • Get all .exe files in a directory. Similar to what you have done already with Get-ChildItem.
    • Iterate each of these files. Can use foreach or Foreach-Object here.
    • Extract BaseName from files. This means getting test from test.exe. We need this to make the shortcut file.
    • Create shortcut from path. This path is just the destination path + filename + .lnk extension. We can use Join-Path here to make this path.
    • Set target path of shortcut to the executable and save shortcut.

    Demonstration:

    $sourcePath = "C:\path\to\shortcuts"
    $destinationPath = "C:\path\to\destination"
    
    # Create COM Object for creating shortcuts
    $wshShell = New-Object -ComObject WScript.Shell
    
    # Get all .exe files from source directory
    $exeFiles = Get-ChildItem -Path $sourcePath -Filter *.exe -Recurse
    
    # Go through each file
    foreach ($file in $exeFiles)
    {
        # Get executable filename
        $basename = $file.BaseName
    
        # Create shortcut path to save to
        $shortcutPath = Join-Path -Path $destinationPath -ChildPath ($basename + ".lnk")
    
        # Create shortcut
        $shortcut = $wshShell.CreateShortcut($shortcutPath)
    
        # Set target path of shortcut to executable
        $shortcut.TargetPath = $file.FullName
    
        # Finally save the shortcut to the path
        $shortcut.Save()
    }