Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

Creating URL Shortcuts on Desktops Using PowerShell

Key Takeaways

  • The script automates the creation of URL shortcuts on desktops for individual or multiple users in Windows environments.
  • Flexibility is offered through parameters for creating shortcuts for all users, all existing users, or specific users.
  • Admin rights are required for creating shortcuts in the C:UsersPublicDesktop directory, enhancing security.
  • The script supports customization of shortcut names, URLs, and icons, allowing for a personalized user experience.
  • Use cases include streamlined deployment of shortcuts for company resources on employee workstations.
  • This approach is more efficient than manual shortcut creation, especially in large organizations.

Creating a URL shortcut on a desktop is a seemingly small but significantly practical task in the IT world. It streamlines access to frequently visited websites, enhancing efficiency for users. While this functionality may appear basic, its implementation across various user profiles in an organization demands a more nuanced approach, especially when considering different user privileges and system environments.

Background

The script in discussion is designed to automate the process of creating URL shortcuts on desktops in Windows environments. This utility is particularly valuable for IT professionals and Managed Service Providers (MSPs) who manage a large number of computers. Often, there’s a need to provide all users or specific groups with direct access to essential web resources, such as company portals, HR systems, or cloud applications. Manually performing this task is time-consuming and prone to errors, hence the need for an automated, customizable script.

The Script:

<#
.SYNOPSIS
    This script creates a URL desktop shortcut with your specified options. It can create a shortcut for all users (including new ones) or for existing ones only.
.DESCRIPTION
    This script creates a URL desktop shortcut with your specified options. 
    It can create a shortcut for all users (including new ones) or for existing ones only.
.EXAMPLE
    To create a URL shortcut that opens in the default browser:
    
    -Name "Test" -URL "https://www.google.com" -AllUsers

    Creating Shortcut at C:UsersJohnSmithDesktopTest.url

.PARAMETER NAME
    The name of the shortcut, e.g., "Login Portal".

.PARAMETER URL
    The website URL to open, e.g., "https://www.google.com".

.PARAMETER AllExistingUsers
    Creates the shortcut for all existing users but not for new users, e.g., C:Users*Desktopshortcut.url.

.PARAMETER AllUsers
    Creates the shortcut in C:UsersPublicDesktop.

.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 7, Windows Server 2008
    Release Notes: Split the script into three separate scripts and added Script Variable support.
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]$Name,
    [Parameter()]
    [String]$Url,
    [Parameter()]
    [Switch]$AllExistingUsers,
    [Parameter()]
    [Switch]$AllUsers
)
begin {
    # If Form Variables are used, replace the existing params with them.
    if ($env:shortcutName -and $env:shortcutName -notlike "null") { $Name = $env:shortcutName }
    if ($env:createTheShortcutFor -and $env:createTheShortcutFor -notlike "null") { 
        if ($env:createTheShortcutFor -eq "All Users") { $AllUsers = $True }
        if ($env:createTheShortcutFor -eq "All Existing Users") { $AllExistingUsers = $True }
    }
    if ($env:linkForUrlShortcut -and $env:linkForUrlShortcut -notlike "null") { $Url = $env:linkForUrlShortcut }

    # Double-check that a user was specified for shortcut creation.
    if (!$AllUsers -and !$AllExistingUsers) {
        Write-Error "You must specify which desktop to create the shortcut on!"
        exit 1
    }

    # Double-check that a shortcut name was given.
    if (-not $Name) {
        Write-Error "You must specify a name for the shortcut!"
        exit 1
    }

    # Creating a shortcut at C:UsersPublicDesktop requires admin rights.
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    if (!(Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }

    # This will get all the registry paths for all actual users (not system or network service accounts, but actual users).
    function Get-UserHives {
        param (
            [Parameter()]
            [ValidateSet('AzureAD', 'DomainAndLocal', 'All')]
            [String]$Type = "All",
            [Parameter()]
            [String[]]$ExcludedUsers,
            [Parameter()]
            [switch]$IncludeDefault
        )

        # User account SIDs follow a particular pattern depending on whether they're Azure AD, a Domain account, or a local "workgroup" account.
        $Patterns = switch ($Type) {
            "AzureAD" { "S-1-12-1-(d+-?){4}$" }
            "DomainAndLocal" { "S-1-5-21-(d+-?){4}$" }
            "All" { "S-1-12-1-(d+-?){4}$" ; "S-1-5-21-(d+-?){4}$" } 
        }

        # We'll need the NTuser.dat file to load each user's registry hive. So, we grab it if their account SID matches the above pattern.
        $UserProfiles = Foreach ($Pattern in $Patterns) { 
            Get-ItemProperty "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList*" |
                Where-Object { $_.PSChildName -match $Pattern } | 
                Select-Object @{Name = "SID"; Expression = { $_.PSChildName } }, 
                @{Name = "UserHive"; Expression = { "$($_.ProfileImagePath)NTuser.dat" } }, 
                @{Name = "UserName"; Expression = { "$($_.ProfileImagePath | Split-Path -Leaf)" } },
                @{Name = "Path"; Expression = { $_.ProfileImagePath } }
        }

        # There are some situations where grabbing the .Default user's info is needed.
        switch ($IncludeDefault) {
            $True {
                $DefaultProfile = "" | Select-Object UserName, SID, UserHive, Path
                $DefaultProfile.UserName = "Default"
                $DefaultProfile.SID = "DefaultProfile"
                $DefaultProfile.Userhive = "$env:SystemDriveUsersDefaultNTUSER.DAT"
                $DefaultProfile.Path = "C:UsersDefault"

                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }
            }
        }

        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }
    }

    # The actual shortcut creation
    function New-Shortcut {
        [CmdletBinding()]
        param(
            [Parameter()]
            [String]$Arguments,
            [Parameter()]
            [String]$IconPath,
            [Parameter(ValueFromPipeline = $True)]
            [String]$Path,
            [Parameter()]
            [String]$Target,
            [Parameter()]
            [String]$WorkingDir
        )
        process {
            Write-Host "Creating Shortcut at $Path"
            $ShellObject = New-Object -ComObject ("WScript.Shell")
            $Shortcut = $ShellObject.CreateShortcut($Path)
            $Shortcut.TargetPath = $Target
            if ($WorkingDir) { $Shortcut.WorkingDirectory = $WorkingDir }
            if ($Arguments) { $ShortCut.Arguments = $Arguments }
            if ($IconPath) { $Shortcut.IconLocation = $IconPath }
            $Shortcut.Save()

            if (!(Test-Path $Path -ErrorAction SilentlyContinue)) {
                Write-Error "Unable to create Shortcut at $Path"
                exit 1
            }
        }
    }
}
process {
    $ShortcutPath = New-Object System.Collections.Generic.List[String]

    # Creating the filenames for the path
    if ($Url) { 
        $File = "$Name.url"
        $Target = $Url 
    }

    # Building the path's and adding it to the ShortcutPath list
    if ($AllUsers) { $ShortcutPath.Add("$env:PublicDesktop$File") }

    if ($AllExistingUsers) {
        $UserProfiles = Get-UserHives
        # Loop through each user profile
        $UserProfiles | ForEach-Object { $ShortcutPath.Add("$($_.Path)Desktop$File") }
    }

    $ShortcutPath | ForEach-Object { New-Shortcut -Target $Target -Path $_ }

    exit 0
}end {
    
    
    
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

The script functions in a PowerShell environment and employs several parameters to customize the shortcut creation process. Here’s a step-by-step breakdown:

  • Parameter Initialization: The script starts by defining parameters such as the shortcut’s name, URL, icon, and the scope of its deployment (either all users, all existing users, or specific users).
  • Environment Variable Check: It checks for specific environment variables, allowing it to adapt based on external inputs or deployment conditions.
  • Prerequisites Validation: Before proceeding, the script verifies if the user has specified the desktop (all users, existing users, or a particular user) and the shortcut name. It also checks for administrative privileges as creating a shortcut in C:UsersPublicDesktop requires such rights.
  • User Hive Extraction: It employs a function to identify user profiles on the system, excluding system or network service accounts.
  • Shortcut Creation Logic: Depending on the chosen parameters, it constructs the appropriate file path and uses a COM object to create the shortcut, setting its target to the specified URL.
  • Execution and Cleanup: After creating the shortcuts, the script exits gracefully, providing the opportunity to pass metadata for logging or audit purposes.

Potential Use Cases

Consider an MSP managing IT infrastructure for a company that recently adopted a new online project management tool. To ensure easy access for all employees, the MSP can use this script to create a desktop shortcut to the tool’s URL on every employee’s computer, saving time and reducing potential confusion or miscommunication about the tool’s web address.

Comparisons

Traditionally, URL shortcuts are either created manually or through group policy settings in a domain environment. Manual creation is labor-intensive and not scalable. Group policies, while powerful, can be complex to configure and are not suited for non-domain or mixed-environment setups. This PowerShell script provides a more direct, flexible, and scriptable approach that can be easily integrated into larger automation workflows.

FAQs

Q1: Will this script work on non-Windows systems? 
A: No, it’s specifically designed for Windows environments.

Q2: Is administrative privilege mandatory for using this script? 
A: Yes, for creating shortcuts in the C:UsersPublicDesktop directory.

Q3: Can the script be modified to add custom icons to shortcuts? 
A: Yes, it includes parameters for setting custom icons.

Implications

While the script enhances operational efficiency, it also poses certain security implications. Improper use could lead to the unauthorized distribution of shortcuts, potentially to malicious sites. It’s crucial to ensure that the URLs provided are safe and from trusted sources.

Recommendations

  • Always run the script in a test environment before deployment.
  • Regularly review and update the list of URLs to maintain shortcut relevance and security.
  • Monitor the script’s execution as part of your organization’s broader security audit.

Final Thoughts

In the fast-paced IT environment, efficiency and automation are key. A tool like NinjaOne, offering comprehensive IT management and automation solutions, complements such scripts by providing a platform for deploying, managing, and monitoring such automation tasks across diverse IT infrastructures. The integration of such scripts into a unified management solution like NinjaOne can significantly enhance IT operational efficiency and reliability.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).