How to Set the Target of a .lnk File Programmatically with PowerShell or C++

Abstract: Resolve broken Windows shortcuts by programmatically updating the target path using PowerShell WScript.Shell or C++ IShellLink COM interfaces.

Created: 2026-09-30 by
To programmatically set the target of a .lnk file, you must use the Windows Shell COM object rather than simple file I/O. In PowerShell, this is achieved by creating a WScript.Shell instance and calling its CreateShortcut method to generate or modify an IWshShortcut interface. This approach allows direct manipulation of properties like TargetPath, ensuring the shortcut points to the correct executable or document.

The Limitations of Standard File Operations

A common misconception among developers is that a .lnk file is a plain text file containing the path to the target. It is not. A shortcut file is a binary structure defined by the Windows Shell API. If you attempt to write a string directly to a .lnk file using standard commands like Set-Content in PowerShell or fopen in C++, you will corrupt the file header. The operating system will fail to parse the shortcut, resulting in a broken link or an error when the user attempts to launch it. Therefore, any programmatic modification requires interacting with the COM subsystem that manages shell objects.

Implementing the Solution in PowerShell

PowerShell provides a straightforward way to access the necessary COM objects through the New-Object cmdlet. The process involves instantiating the WScript.Shell ActiveX component, which exposes the CreateShortcut method. This method returns an object that implements the IWshShortcut interface. First, define the path where the shortcut resides. Then, create the shell object. Call CreateShortcut passing the full path to the .lnk file. If the file does not exist, this call creates a new one; if it exists, it opens it for editing. You then assign values to the TargetPath property. It is crucial to also set the WorkingDirectory property, as many applications rely on the current directory for relative resource loading. Finally, invoke the Save method to commit changes to disk.
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut("C:\Users\Public\Desktop\MyApp.lnk")
$shortcut.TargetPath = "C:\Program Files\MyApp\app.exe"
$shortcut.WorkingDirectory = "C:\Program Files\MyApp"
$shortcut.Description = "Launch My Application"
$shortcut.Save()
This script can be run directly in a PowerShell console or integrated into larger automation scripts. Note that if you are modifying an existing shortcut, ensure the script has write permissions to the destination folder, particularly if targeting the desktop or start menu directories which may require elevated privileges.

Implementing the Solution in C++

For C++ developers, the equivalent functionality relies on the Windows Shell Interfaces. You need to include windows.h and shobjidl.h. The core interface is IShellLink, which provides methods to get and set various shortcut attributes. To persist these changes, you must use IPersistFile. Begin by initializing the COM library using CoInitializeEx. Create an instance of the ShellLink class using CoCreateInstance. Cast the returned pointer to IShellLink. Use the SetPath method to define the target executable. If you need to set arguments, use SetArguments. To save the changes, cast the IShellLink pointer to IPersistFile and call Save, passing the path to the .lnk file. Remember to release all COM interfaces properly to avoid memory leaks.
#include <windows.h>
#include <shobjidl.h>
#include <comdef.h>

int main() {
    CoInitialize(NULL);
    
    IShellLink* psl;
    HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, 
                                  IID_IShellLink, (void**)&psl);
    
    if (SUCCEEDED(hr)) {
        psl->SetPath(L"C:\\Program Files\\MyApp\\app.exe");
        
        IPersistFile* ppf;
        hr = psl->QueryInterface(IID_IPersistFile, (void**)&ppf);
        
        if (SUCCEEDED(hr)) {
            ppf->Save(L"C:\\Users\\Public\\Desktop\\MyApp.lnk", TRUE);
            ppf->Release();
        }
        psl->Release();
    }
    CoUninitialize();
    return 0;
}

Handling Paths and Permissions

When setting targets, always use absolute paths unless there is a specific reason to use relative ones. Relative paths in shortcuts can be ambiguous depending on the working directory context at runtime. Additionally, consider the execution context. If your script or application runs without administrative rights, you may not be able to create shortcuts in protected locations like C:\ProgramData\Microsoft\Windows\Start Menu. In such cases, target user-specific directories like %APPDATA% or the user's Desktop. For those interested in broader command-line interactions, understanding how different shells handle paths is useful. See Command Prompt Drive Switching Different From PowerShell for insights into environment handling across different terminal environments.

Verifying the Shortcut

After writing the code, verify the result by opening the shortcut manually or using a script to read back the TargetPath. Ensure no typos exist in the file paths. If the target fails to launch, check the WorkingDirectory and Arguments fields, as missing parameters are a frequent cause of silent failures in automated shortcut creation.

Frequently Asked Questions

Can I edit a .lnk file using Notepad?

No, you cannot edit a .lnk file using a text editor like Notepad because it is a binary format, not plain text. Attempting to do so will corrupt the file structure, making the shortcut invalid and unopenable by the Windows Shell.

Why does my shortcut fail to launch after changing the target?

This often happens if the WorkingDirectory is not set correctly or if the new target path contains spaces without proper quoting in the Arguments field. Always ensure the target executable exists at the specified path and that you have saved the shortcut object after making changes.

How do I pass command-line arguments to a shortcut via PowerShell?

You can set the Arguments property of the IWshShortcut object created by WScript.Shell. For example, use $shortcut.Arguments = "/config settings.xml" before calling $shortcut.Save(). This ensures the target application receives the parameters upon launch.

Is it possible to change the icon of a .lnk file programmatically?

Yes, both PowerShell and C++ allow you to set the icon index and path. In PowerShell, use the IconLocation property of the shortcut object, specifying the DLL or EXE containing the icon and the index number. In C++, use the SetIconLocation method on the IShellLink interface.

What are the risks of running shortcut modification scripts without admin rights?

If you attempt to create or modify shortcuts in system-wide directories like C:\ProgramData or the global Start Menu, the operation will fail due to insufficient permissions. Always target user-writable directories such as the Desktop or AppData folders when running under standard user accounts.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More