Guarda una demo×
×

Guarda NinjaOne in azione!

Inviando questo modulo, accetto La politica sulla privacy di NinjaOne.

Creare collegamenti URL su desktop con PowerShell

Punti chiave

  • Lo script automatizza il processo per creare collegamenti URL su desktop per utenti singoli o multipli in ambienti Windows.
  • La flessibilità è offerta da parametri che permettono di creare collegamenti per tutti gli utenti, per tutti gli utenti esistenti o per utenti specifici.
  • I diritti di amministratore sono necessari per la creazione di collegamenti nella directory C:UsersPublicDesktop, per questioni di sicurezza.
  • Lo script supporta la personalizzazione dei nomi dei collegamenti, degli URL e delle icone, consentendo un’esperienza utente personalizzata.
  • I casi d’uso includono la distribuzione semplificata di collegamenti per le risorse aziendali sulle postazioni di lavoro dei dipendenti.
  • Questo approccio è più efficiente della creazione manuale di collegamenti, soprattutto nelle grandi organizzazioni.

La creazione di collegamenti URL sul desktop è un’operazione apparentemente minore ma in realtà molto utile nel mondo IT. Semplifica l’accesso ai siti web visitati di frequente, migliorando l’efficienza degli utenti. Sebbene questa funzionalità possa sembrare elementare, la sua implementazione tra i vari profili utente di un’organizzazione richiede un approccio a vari livelli, soprattutto se si considerano i diversi privilegi degli utenti e gli ambienti di sistema.

Background

Lo script analizzato è progettato per automatizzare il processo per creare collegamenti URL su desktop in ambienti Windows. Questo script è particolarmente prezioso per i professionisti IT e i Managed Service Provider (MSP) che gestiscono un gran numero di computer. Spesso è necessario fornire a tutti gli utenti o a gruppi specifici l’accesso diretto a risorse web essenziali, come portali aziendali, sistemi HR o applicazioni cloud. L’esecuzione manuale delle operazioni necessarie a creare collegamenti URL su desktop richiede molto tempo ed è soggetta a errori; da qui la necessità di uno script automatico e personalizzabile.

Lo script per creare collegamenti URL su desktop:

<#
.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/it/condizioni-utilizzo/
    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 {
    
    
    
}

|

<#
.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 {
    
    
    
}

 

Accedi a oltre 700 script nel Dojo di NinjaOne

Ottieni l’accesso

Analisi dettagliata

Lo script per creare collegamenti URL su desktop funziona in un ambiente PowerShell e utilizza diversi parametri per personalizzare il processo di creazione dei collegamenti. Ecco una spiegazione passo per passo:

  • Inizializzazione dei parametri: Lo script per creare collegamenti URL su desktop inizia definendo parametri quali il nome del collegamento, l’URL, l’icona e l’ambito di distribuzione (tutti gli utenti, tutti gli utenti esistenti o utenti specifici).
  • Controllo delle variabili d’ambiente: Controlla le variabili d’ambiente specifiche, consentendo di adattarsi in base agli input esterni o alle condizioni di distribuzione.
  • Convalida dei prerequisiti: Prima di procedere, lo script per creare collegamenti URL su desktop verifica se l’utente ha specificato l’ambito desktop (tutti gli utenti, gli utenti esistenti o un utente particolare) e il nome del collegamento. Controlla anche la presenza di privilegi amministrativi, poiché la creazione di un collegamento in C:UsersPublicDesktop richiede questi diritti.
  • Filtraggio degli account di tipo utente: Lo script per creare collegamenti URL su desktop utilizza una funzione per identificare i profili utente sul sistema, escludendo gli account dei servizi di sistema o di rete.
  • Operazione di creazione del collegamento: In base ai parametri scelti, costruisce il percorso appropriato del file e utilizza un oggetto COM per creare il collegamento, impostando il suo obiettivo sull’URL specificato.
  • Esecuzione e pulizia: Dopo aver creato i collegamenti, lo script per creare collegamenti URL su desktop termina, offrendo la possibilità di salvare e condividere i metadati per scopi di registrazione o di audit.

Casi d’uso potenziali

Consideriamo un MSP che gestisce l’infrastruttura IT di un’azienda che ha recentemente adottato un nuovo strumento di gestione dei progetti online. Per garantire un facile accesso a tutti i dipendenti, l’MSP può utilizzare questo script per creare un collegamento sul desktop all’URL dello strumento sul computer di ogni dipendente, risparmiando tempo e riducendo la potenziale confusione o possibili comunicazioni errate sull’indirizzo web dello strumento.

Confronti

Tradizionalmente, i collegamenti URL vengono creati manualmente o tramite le impostazioni dei criteri di gruppo in un ambiente di dominio. La creazione manuale richiede molto lavoro e non è scalabile. I criteri di gruppo, pur essendo potenti, possono essere complessi da configurare e non sono adatti per le configurazioni prive di dominio o in ambienti misti. Questo script PowerShell offre un approccio più diretto, flessibile e automatizzato per creare collegamenti URL su desktop che può essere facilmente integrato in flussi di lavoro di automazione più ampi.

Domande frequenti

D1: Questo script per creare collegamenti URL su desktop funziona su sistemi non Windows? 
R: No, è stato progettato specificamente per gli ambienti Windows.

D2: I privilegi amministrativi sono obbligatori per l’utilizzo di questo script per creare collegamenti URL su desktop? 
R: Sì, per la creazione di collegamenti nella directory C:UsersPublicDesktop.

D3: È possibile modificare lo script per creare collegamenti URL su desktop per aggiungere icone personalizzate ai collegamenti? 
R: Sì, lo script per creare collegamenti URL su desktop include parametri per l’impostazione di icone personalizzate.

Implicazioni

Se da un lato lo script per creare collegamenti URL su desktop migliora l’efficienza operativa, dall’altro comporta alcune implicazioni per la sicurezza. L’uso improprio potrebbe portare alla distribuzione non autorizzata di collegamenti, potenzialmente a siti dannosi. È fondamentale assicurarsi che gli URL forniti siano sicuri e provengano da fonti affidabili.

Raccomandazioni

  • Esegui sempre lo script per creare collegamenti URL su desktop in un ambiente di test prima della distribuzione.
  • Controlla e aggiorna regolarmente l’elenco degli URL per mantenere la pertinenza e la sicurezza dei collegamenti.
  • Monitora l’esecuzione dello script per creare collegamenti URL su desktop come parte del più ampio audit di sicurezza dell’organizzazione.

Considerazioni finali

Nel frenetico ambiente IT, l’efficienza e l’automazione sono fondamentali. Uno strumento come NinjaOne, che offre soluzioni complete per la gestione e l’automazione dell’IT, integra script come quello per creare collegamenti URL su desktop fornendo una piattaforma per l’implementazione, la gestione e il monitoraggio delle attività di automazione su diverse infrastrutture IT. L’integrazione di script in una soluzione di gestione unificata come NinjaOne può migliorare in modo significativo l’efficienza operativa e l’affidabilità dell’IT.

Passi successivi

La creazione di un team IT efficiente ed efficace richiede una soluzione centralizzata che funga da principale strumento per la fornitura di servizi. NinjaOne consente ai team IT di monitorare, gestire, proteggere e supportare tutti i dispositivi, ovunque essi si trovino, senza la necessità di una complessa infrastruttura locale.

Per saperne di più su NinjaOne Endpoint Management, fai un tour dal vivo, o inizia la tua prova gratuita della piattaforma NinjaOne.

Ti potrebbe interessare anche

Termini e condizioni NinjaOne

Cliccando sul pulsante “Accetto” qui sotto, dichiari di accettare i seguenti termini legali e le nostre condizioni d’uso:

  • Diritti di proprietà: NinjaOne possiede e continuerà a possedere tutti i diritti, i titoli e gli interessi relativi allo script (compreso il copyright). NinjaOne ti concede una licenza limitata per l’utilizzo dello script in conformità con i presenti termini legali.
  • Limitazione d’uso: Puoi utilizzare lo script solo per legittimi scopi personali o aziendali interni e non puoi condividere lo script con altri soggetti.
  • Divieto di ripubblicazione: In nessun caso ti è consentito ripubblicare lo script in una libreria di script appartenente o sotto il controllo di un altro fornitore di software.
  • Esclusione di garanzia: Lo script viene fornito “così com’è” e “come disponibile”, senza garanzie di alcun tipo. NinjaOne non promette né garantisce che lo script sia privo di difetti o che soddisfi le tue esigenze o aspettative specifiche.
  • Assunzione del rischio: L’uso che farai dello script è da intendersi a tuo rischio. Riconosci che l’utilizzo dello script comporta alcuni rischi intrinseci, che comprendi e sei pronto ad assumerti.
  • Rinuncia e liberatoria: Non riterrai NinjaOne responsabile di eventuali conseguenze negative o indesiderate derivanti dall’uso dello script e rinuncerai a qualsiasi diritto legale o di equità e a qualsiasi rivalsa nei confronti di NinjaOne in relazione all’uso dello script.
  • EULA: Se sei un cliente NinjaOne, l’uso dello script è soggetto al Contratto di licenza con l’utente finale (EULA) applicabile.