{"id":208181,"date":"2024-01-29T13:30:40","date_gmt":"2024-01-29T13:30:40","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/gestione-degli-sfondi-windows-con-powershell\/"},"modified":"2024-03-04T18:10:50","modified_gmt":"2024-03-04T18:10:50","slug":"gestione-degli-sfondi-windows-con-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/gestione-degli-sfondi-windows-con-powershell\/","title":{"rendered":"Come semplificare la gestione degli sfondi Windows con PowerShell"},"content":{"rendered":"<h2>Punti chiave<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\"><strong>Automatizzare le modifiche allo sfondo<\/strong>: Lo script automatizza il processo di impostazione degli sfondi del desktop tra pi\u00f9 profili utente in ambienti Windows.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\"><strong>Ti permette di risparmiare tempo e garantisce coerenza<\/strong>: Ideale per i professionisti IT e gli MSP che gestiscono pi\u00f9 computer, garantisce uniformit\u00e0 e conformit\u00e0 dal punto di vista del branding.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\"><strong>Parametri flessibili<\/strong>: Supporta la personalizzazione con parametri per l&#8217;URL dell&#8217;immagine, la directory di archiviazione e lo stile degli sfondi Windows.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Funzionalit\u00e0 con effetto immediato<\/strong>: Include opzioni per la sostituzione dei file di sfondo transcodificati e il riavvio di Explorer per una modifica immediata.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"5\" data-aria-level=\"1\"><strong>Versatilit\u00e0 tra le varie versioni di Windows<\/strong>: Progettato per Windows 7 e versioni successive, ma ci possono essere variazioni nelle funzionalit\u00e0 per le versioni pi\u00f9 vecchie.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"6\" data-aria-level=\"1\"><strong>Supporta i formati di immagine pi\u00f9 comuni<\/strong>: Compatibile con i formati immagine pi\u00f9 diffusi, come JPG, PNG, BMP e GIF.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"7\" data-aria-level=\"1\"><strong>Considerazioni sulla sicurezza<\/strong>: Comporta la modifica delle impostazioni del registro e dei file di sistema; la gestione corretta delle autorizzazioni degli script \u00e8 fondamentale.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"8\" data-aria-level=\"1\"><strong>Si consiglia di eseguire un test completo<\/strong>: Esegui test approfonditi in ambienti controllati prima di distribuire lo script in tutta la rete.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"9\" data-aria-level=\"1\"><strong>Si integra con gli strumenti di gestione IT<\/strong>: Pu\u00f2 essere incorporato senza problemi in piattaforme di gestione IT come NinjaOne per una distribuzione e un monitoraggio efficienti.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"10\" data-aria-level=\"1\"><strong>Documenta e verifica l&#8217;uso degli script<\/strong>: Conserva i log per l&#8217;uso degli script per facilitare la verifica e la risoluzione dei problemi.<\/li>\n<\/ul>\n<p>La modifica dello sfondo del desktop per pi\u00f9 profili utente in un ambiente Windows \u00e8 un&#8217;operazione che i professionisti IT devono affrontare spesso. Che sia per motivi di branding, di conformit\u00e0 o semplicemente per rinnovare l&#8217;area di lavoro, l&#8217;automazione di questo processo consente di risparmiare tempo e di garantire coerenza. Gli script PowerShell sono diventati strumenti indispensabili nel kit di strumenti IT, perch\u00e9 offrono soluzioni potenti e flessibili per attivit\u00e0 come queste.<\/p>\n<h2>Background<\/h2>\n<p>Lo script in questione \u00e8 progettato per automatizzare il processo di impostazione degli sfondi del desktop per tutti i profili utente di un sistema Windows. Questa funzionalit\u00e0 \u00e8 particolarmente preziosa per i professionisti IT e i <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">Managed Service Provider (MSP)<\/a> che gestiscono un gran numero di computer. Consente di ottenere uniformit\u00e0 negli ambienti aziendali, assicurando che tutti gli utenti abbiano lo stesso sfondo, il che pu\u00f2 essere fondamentale per il branding o la trasmissione di informazioni importanti.<\/p>\n<h2>Lo script per la gestione degli sfondi Windows:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">&lt;#\r\n.SYNOPSIS\r\n    This sets the desktop wallpaper for all existing users (if run as System) or the currently logged-in user. To have the wallpaper change take effect immediately please select \"Replace Transcoded Wallpaper File\" and \"Restart Explorer\". These options may not work on Windows 7 and Server 2008.\r\n.DESCRIPTION\r\n    This sets the desktop wallpaper for all existing users (if run as System) or the currently logged-in user. \r\n    To have the wallpaper change take effect immediately please select \"Replace Transcoded Wallpaper File\" and \"Restart Explorer\". \r\n    These options may not work on Windows 7 and Server 2008.\r\n.EXAMPLE\r\n    (No Parameters) - Windows 10\r\n\r\n    C:ProgramDataNinjaRMMAgentscriptingcustomscript_gen_55.ps1 : No image given!\r\n    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException\r\n    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,customscript_gen_55.ps1\r\n\r\nPARAMETER: -Url \"https:\/\/www.example.com\/image.png\"\r\n    A link to the wallpaper you would like to set.\r\n\r\nPARAMETER: -Directory \"C:ExampleExample\"\r\n    A location to store the wallpaper.\r\n\r\n.EXAMPLE\r\n    -Url \"https:\/\/www.microsoft.com\/en-us\/microsoft-365\/blog\/wp-content\/uploads\/sites\/2\/2021\/06\/Msft_Nostalgia_Landscape.jpg\" -Directory \"C:ProgramDataWallpaper\" (Windows 10 as System)\r\n    \r\n    WARNING: Restarting Explorer.exe is required for wallpaper change to take effect!\r\n    URL Given, Downloading the file...\r\n    Download Attempt 1\r\n\r\n    Registry::HKEY_USERSS-1-5-21-3600085911-33463358-3311494591-1103Control PanelDesktopWallpaper changed from C:ProgramDataWallpaperwallpaper-686581913.jpg to C:ProgramDataWallpaperwallpaper-1935193304.jpg\r\n    Registry::HKEY_USERSS-1-5-21-3600085911-33463358-3311494591-1103Control PanelDesktopWallpaperStyle changed from 10 to 10\r\n    Registry::HKEY_USERSS-1-5-21-3600085911-33463358-3311494591-1103Control PanelDesktopTileWallpaper changed from 0 to 0\r\n    WARNING: Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\r\n\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002Control PanelDesktopWallpaper changed from C:ProgramDataWallpaperwallpaper-686581913.jpg to C:ProgramDataWallpaperwallpaper-1935193304.jpg\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002Control PanelDesktopWallpaperStyle changed from 10 to 10\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1002Control PanelDesktopTileWallpaper changed from 0 to 0\r\n    WARNING: Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\r\n\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1003Control PanelDesktopWallpaper changed from C:ProgramDataWallpaperwallpaper-686581913.jpg to C:ProgramDataWallpaperwallpaper-1935193304.jpg\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1003Control PanelDesktopWallpaperStyle changed from 10 to 10\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1003Control PanelDesktopTileWallpaper changed from 0 to 0\r\n    WARNING: Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\r\n\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1004Control PanelDesktopWallpaper changed from C:ProgramDataWallpaperwallpaper-686581913.jpg to C:ProgramDataWallpaperwallpaper-1935193304.jpg\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1004Control PanelDesktopWallpaperStyle changed from 10 to 10\r\n    Registry::HKEY_USERSS-1-5-21-3870645062-3653562310-3850680542-1004Control PanelDesktopTileWallpaper changed from 0 to 0\r\n    WARNING: Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\r\n\r\nPARAMETER: -WallpaperStyle \"Fill\"\r\n    This will set the wallpaper style to the appropriate option. Valid Options: \"Fill\", \"Fit\", \"Stretch\", \"Tile\", \"Center\", \"Span\"\r\n\r\nPARAMETER: -ReplaceTranscodedWallpaperFile\r\n    This will replace the file %APPDATA%MicrosoftWindowsThemesTranscodedWallpaper. This file is generated whenever the wallpaper is changed and is required for the wallpaper change to take immediate effect.\r\n\r\nPARAMETER: -RestartExplorer\r\n    This will restart explorer.exe. This is required for the wallpaper change to take immediate effect.\r\n\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum Supported OS: Windows 7+, Server 2008+\r\n    Release Notes: Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [String]$Url,\r\n    [Parameter()]\r\n    [String]$Directory,\r\n    [Parameter()]\r\n    [String]$WallpaperStyle = \"Fill\",\r\n    [Parameter()]\r\n    [Switch]$ReplaceTranscodedWallpaperFile = [System.Convert]::ToBoolean($env:replaceTranscodedWallpaperFile),\r\n    [Parameter()]\r\n    [Switch]$RestartExplorer = [System.Convert]::ToBoolean($env:restartExplorer)\r\n)\r\n\r\nbegin {\r\n\r\n    # Set Dynamic Script Variables (if used)\r\n    if ($env:localWallpaperFile -and $env:localWallpaperFile -notlike \"null\") { $ExistingImage = $env:localWallpaperFile }\r\n    if ($env:directoryToStoreWallpaperIn -and $env:directoryToStoreWallpaperIn -notlike \"null\") { $Directory = $env:directoryToStoreWallpaperIn }\r\n    if ($env:linkToWallpaperFile -and $env:linkToWallpaperFile -notlike \"null\") { $Url = $env:linkToWallpaperFile }\r\n    if ($env:wallpaperDisplayMode -and $env:wallpaperDisplayMode -notlike \"null\") { $WallpaperStyle = $env:wallpaperDisplayMode }\r\n\r\n    # Validate that we received a correct value for the wallpaper style\r\n    $AllowedFit = \"Fill\", \"Fit\", \"Stretch\", \"Tile\", \"Center\", \"Span\"\r\n    if ($AllowedFit -notcontains $WallpaperStyle) {\r\n        Write-Error \"[Error] Invalid Wallpaper Display Mode selected. Please use one of the following options. Fill, Fit, Stretch, Tile, Center or Span.\"\r\n        exit 1\r\n    }\r\n\r\n    # If the local file we were told to use doesn't exist we should ignore it.\r\n    if ($ExistingImage -and -not (Test-Path $ExistingImage -ErrorAction SilentlyContinue)) {\r\n        Write-Warning \"Existing wallpaper does not exist. Ignoring...\"\r\n        $ExistingImage = $Null\r\n    }\r\n\r\n    # If we weren't given a link or a local file to use we should error out.\r\n    if (-not ($Url) -and -not ($ExistingImage)) {\r\n        Write-Error \"No image given!\"\r\n        Exit 1\r\n    }\r\n\r\n    # If we don't have a place to store the file and it doesn't already exist we should error out.\r\n    if (-not ($Directory) -and -not ($ExistingImage)) {\r\n        Write-Error \"You must specify a location to store the wallpaper.\"\r\n        Exit 1\r\n    }\r\n\r\n    # Create the directory if it does not exist.\r\n    if ($Directory -and -not (Test-Path -Path $Directory -ErrorAction SilentlyContinue)) {\r\n        try {\r\n            New-Item -Path $Directory -ItemType Directory -ErrorAction Stop | Out-Null\r\n        }\r\n        catch {\r\n            Write-Error \"Failed to create directory!\"\r\n            Exit 1\r\n        }\r\n    }\r\n\r\n    # Warn the end-user that the wallpaper change will not take immediate effect.\r\n    if (-not ($RestartExplorer)) {\r\n        Write-Warning \"Restarting Explorer.exe is required for wallpaper change to take effect!\"\r\n    }\r\n\r\n    # Handy download function.\r\n    function Invoke-Download {\r\n        param(\r\n            [Parameter()]\r\n            [String]$URL,\r\n            [Parameter()]\r\n            [String]$BaseName,\r\n            [Parameter()]\r\n            [Switch]$SkipSleep\r\n        )\r\n        Write-Host \"URL Given, Downloading the file...\"\r\n\r\n        $SupportedTLSversions = [enum]::GetValues('Net.SecurityProtocolType')\r\n        if ( ($SupportedTLSversions -contains 'Tls13') -and ($SupportedTLSversions -contains 'Tls12') ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol::Tls13 -bor [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        elseif ( $SupportedTLSversions -contains 'Tls12' ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        else {\r\n            # Not everything requires TLS 1.2, but we'll try anyways.\r\n            Write-Warning \"TLS 1.2 and or TLS 1.3 isn't supported on this system. This download may fail!\"\r\n            if ($PSVersionTable.PSVersion.Major -lt 3) {\r\n                Write-Warning \"PowerShell 2 \/ .NET 2.0 doesn't support TLS 1.2.\"\r\n            }\r\n        }\r\n\r\n        $i = 1\r\n        While ($i -lt 4) {\r\n            if (-not ($SkipSleep)) {\r\n                $SleepTime = Get-Random -Minimum 3 -Maximum 30\r\n                Start-Sleep -Seconds $SleepTime\r\n            }\r\n\r\n            Write-Host \"Download Attempt $i\"\r\n\r\n            try {\r\n                $WebClient = New-Object System.Net.WebClient\r\n                $Response = $WebClient.OpenRead($Url)\r\n                $MimeType = $WebClient.ResponseHeaders[\"Content-Type\"]\r\n                $DesiredExtension = switch -regex ($MimeType) {\r\n                    \"image\/jpeg|image\/jpg\" { \"jpg\" }\r\n                    \"image\/png\" { \"png\" }\r\n                    \"image\/gif\" { \"gif\" }\r\n                    \"image\/bmp|image\/x-windows-bmp|image\/x-bmp\" { \"bmp\" }\r\n                    default { \r\n                        Write-Error \"The URL you provided does not provide a supported image type. Image Types Supported: jpg, jpeg, bmp, png and gif. Image Type detected: $MimeType\"\r\n                        Exit 1 \r\n                    }\r\n                }\r\n                $Path = \"$BaseName.$DesiredExtension\"\r\n                $WebClient.DownloadFile($URL, $Path)\r\n                $File = Test-Path -Path $Path -ErrorAction SilentlyContinue\r\n                $Response.Close()\r\n            }\r\n            catch {\r\n                if ($Response) { $Response.Close() }\r\n                Write-Warning \"An error has occured while downloading!\"\r\n                Write-Warning $_.Exception.Message\r\n            }\r\n\r\n            if ($File) {\r\n                $i = 4\r\n            }\r\n            else {\r\n                $i++\r\n            }\r\n        }\r\n\r\n        if (-not (Test-Path $Path)) {\r\n            Write-Error \"Failed to download file!\"\r\n            Exit 1\r\n        }\r\n\r\n        $Path\r\n    }\r\n\r\n    # Get a list of all the user profiles for when the script is ran as System.\r\n    function Get-UserHives {\r\n        param (\r\n            [Parameter()]\r\n            [ValidateSet('AzureAD', 'DomainAndLocal', 'All')]\r\n            [String]$Type = \"All\",\r\n            [Parameter()]\r\n            [String[]]$ExcludedUsers,\r\n            [Parameter()]\r\n            [switch]$IncludeDefault\r\n        )\r\n    \r\n        # User account SID's follow a particular patter depending on if they're Azure AD or a Domain account or a local \"workgroup\" account.\r\n        $Patterns = switch ($Type) {\r\n            \"AzureAD\" { \"S-1-12-1-(d+-?){4}$\" }\r\n            \"DomainAndLocal\" { \"S-1-5-21-(d+-?){4}$\" }\r\n            \"All\" { \"S-1-12-1-(d+-?){4}$\" ; \"S-1-5-21-(d+-?){4}$\" } \r\n        }\r\n    \r\n        # We'll need the NTuser.dat file to load each users registry hive. So we grab it if their account sid matches the above pattern. \r\n        $UserProfiles = Foreach ($Pattern in $Patterns) { \r\n            Get-ItemProperty \"HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList*\" |\r\n                Where-Object { $_.PSChildName -match $Pattern } | \r\n                Select-Object @{Name = \"SID\"; Expression = { $_.PSChildName } },\r\n                @{Name = \"UserName\"; Expression = { \"$($_.ProfileImagePath | Split-Path -Leaf)\" } }, \r\n                @{Name = \"UserHive\"; Expression = { \"$($_.ProfileImagePath)NTuser.dat\" } }, \r\n                @{Name = \"Path\"; Expression = { $_.ProfileImagePath } }\r\n        }\r\n    \r\n        # There are some situations where grabbing the .Default user's info is needed.\r\n        switch ($IncludeDefault) {\r\n            $True {\r\n                $DefaultProfile = \"\" | Select-Object UserName, SID, UserHive, Path\r\n                $DefaultProfile.UserName = \"Default\"\r\n                $DefaultProfile.SID = \"DefaultProfile\"\r\n                $DefaultProfile.Userhive = \"$env:SystemDriveUsersDefaultNTUSER.DAT\"\r\n                $DefaultProfile.Path = \"C:UsersDefault\"\r\n    \r\n                $DefaultProfile | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n            }\r\n        }\r\n    \r\n        $UserProfiles | Where-Object { $ExcludedUsers -notcontains $_.UserName }\r\n    }\r\n\r\n    # This makes setting registry keys A LOT easier.\r\n    function Set-HKProperty {\r\n        param (\r\n            $Path,\r\n            $Name,\r\n            $Value,\r\n            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]\r\n            $PropertyType = 'DWord'\r\n        )\r\n        if (-not $(Test-Path -Path $Path)) {\r\n            # Check if path does not exist and create the path\r\n            New-Item -Path $Path -Force | Out-Null\r\n        }\r\n        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {\r\n            # Update property and print out what it was changed from and changed to\r\n            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name\r\n            try {\r\n                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Error \"[Error] Unable to Set registry key for $Name please see below error!\"\r\n                Write-Error $_\r\n                exit 1\r\n            }\r\n            Write-Host \"$Path$Name changed from $CurrentValue to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)\"\r\n        }\r\n        else {\r\n            # Create property with value\r\n            try {\r\n                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Error \"[Error] Unable to Set registry key for $Name please see below error!\"\r\n                Write-Error $_\r\n                exit 1\r\n            }\r\n            Write-Host \"Set $Path$Name to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue).$Name)\"\r\n        }\r\n    }\r\n\r\n    # This function was made just so I didn't have to make two versions of what's essentially the same code.\r\n    function Set-WallpaperKeys {\r\n        param(\r\n            $BasePath,\r\n            $WallpaperStyle,\r\n            $ImagePath\r\n        )\r\n\r\n        $RegKey = \"$BasePathControl PanelDesktop\"\r\n        $Style = switch ($WallpaperStyle) {\r\n            \"Fill\" { 10 }\r\n            \"Fit\" { 6 }\r\n            \"Stretch\" { 2 }\r\n            \"Tile\" { 0 }\r\n            \"Center\" { 0 }\r\n            \"Span\" { 22 }\r\n        }\r\n\r\n        Set-HKProperty -Path $RegKey -Name \"Wallpaper\" -Value $ImagePath -PropertyType \"String\"\r\n        Set-HKProperty -Path $RegKey -Name \"WallpaperStyle\" -Value $Style -PropertyType \"String\"\r\n        if ($WallpaperStyle -eq \"Tile\") {\r\n            Set-HKProperty -Path $RegKey -Name \"TileWallpaper\" -Value 1 -PropertyType \"String\"\r\n        }\r\n        else {\r\n            Set-HKProperty -Path $RegKey -Name \"TileWallpaper\" -Value 0 -PropertyType \"String\"\r\n        }\r\n    }\r\n\r\n    # This will overwrite the %APPDATA%MicrosoftWindowsThemesTranscodedWallpaper file.\r\n    function Reset-TranscodedWallpaper {\r\n        param(\r\n            $Username,\r\n            $BasePath\r\n        )\r\n\r\n        Write-Host \"Replacing transcoded wallpaper file for $Username.\"\r\n\r\n        if (-not (Test-Path \"$BasePathMicrosoftWindowsThemesTranscodedWallpaper\" -ErrorAction SilentlyContinue)) {\r\n            Write-Host \"Transcoded Wallpaper File does not exist. Creating it...\"\r\n            New-Item -ItemType \"file\" -Path \"$BasePathMicrosoftWindowsThemes\" -Name \"TranscodedWallpaper\" | Out-Null\r\n            # After creating a blank one windows will automatically overwrite it with what's used by the current wallpaper. We'll need to sleep to overwrite it.\r\n            Start-Sleep -Seconds 7\r\n        }\r\n\r\n        # If there's more than one file or the file for some reason still does not exist then something fishy is going on.\r\n        $TranscodedWallpaper = Get-ChildItem \"$BasePathMicrosoftWindowsThemes\" | Where-Object { $_.Name -eq \"TranscodedWallpaper\" }\r\n        if (($TranscodedWallpaper | Measure-Object).Count -gt 1) {\r\n            Write-Warning -Message \"There is more than 1 Transcoded wallpaper file user $Username may have to Log out and Log back in again to complete the wallpaper update.\"\r\n        }\r\n        elseif (($TranscodedWallpaper | Measure-Object).Count -lt 1) {\r\n            Write-Warning -Message \"Transcoded wallpaper file does not exist. User $Username may have to Log out and Log back in again to complete the wallpaper update.\"\r\n        }\r\n        else {\r\n            try {\r\n                if (Test-Path $TranscodedWallpaper.FullName -ErrorAction SilentlyContinue) { Get-Item $TranscodedWallpaper.FullName | Remove-Item -Force }\r\n                Copy-Item -Path $ExistingImage -Destination $TranscodedWallpaper.FullName -Force -ErrorAction Stop\r\n            }\r\n            catch {\r\n                Write-Warning -Message \"Failed to update Transcoded wallpaper file. User $Username may have to Log out and Log back in again to complete the wallpaper update.\"\r\n            }\r\n        } \r\n    }\r\n\r\n    # This just restarts explorer.exe\r\n    function Reset-Explorer {\r\n        Write-Host \"Restarting Explorer.exe\"\r\n        Get-Process explorer | Stop-Process -Force\r\n        Start-Process explorer.exe\r\n    }\r\n\r\n    function Test-IsSystem {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        return $id.Name -like \"NT AUTHORITY*\" -or $id.IsSystem\r\n    }\r\n}\r\nprocess {\r\n\r\n    # If we were given a local file and a link use the local file.\r\n    if ($Url -and -not ($ExistingImage)) {\r\n        \r\n        $ExistingImage = Invoke-Download -Url $Url -BaseName \"$Directorywallpaper-$(Get-Random)\"\r\n    }\r\n    \r\n    # Warn that older OS's don't always show the change immediately.\r\n    if ([System.Environment]::OSVersion.Version.Major -lt 10) {\r\n        Write-Warning \"On older Operating Systems wallpaper changes may require the user to log out and log back in to take effect.\"\r\n    }\r\n\r\n    if (-not (Test-IsSystem)) {\r\n\r\n        # Set's the wallpaper registry keys.\r\n        Set-WallpaperKeys -BasePath \"Registry::HKEY_CURRENT_USER\" -ImagePath $ExistingImage -WallpaperStyle $WallpaperStyle\r\n\r\n        if (-not ($ReplaceTranscodedWallpaperFile)) {\r\n            Write-Warning \"Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\"\r\n            Write-Host \"\"\r\n            continue\r\n        }\r\n\r\n        # Replaces the transcoded wallpaper file.\r\n        Reset-TranscodedWallpaper -Username $env:USERNAME -BasePath $env:APPDATA\r\n        \r\n        if ($RestartExplorer) {\r\n            Reset-Explorer\r\n        }\r\n\r\n        exit 0\r\n    }\r\n\r\n    Write-Host \"\"\r\n\r\n    $UserProfiles = Get-UserHives -Type \"All\"\r\n    # Loop through each profile on the machine\r\n    Foreach ($UserProfile in $UserProfiles) {\r\n        # Load User ntuser.dat if it's not already loaded\r\n        If (($ProfileWasLoaded = Test-Path Registry::HKEY_USERS$($UserProfile.SID)) -eq $false) {\r\n            Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe LOAD HKU$($UserProfile.SID) `\"$($UserProfile.UserHive)`\"\" -Wait -WindowStyle Hidden\r\n        }\r\n\r\n        # Sets the wallpaper registry keys.\r\n        Set-WallpaperKeys -BasePath \"Registry::HKEY_USERS$($UserProfile.SID)\" -ImagePath $ExistingImage -WallpaperStyle $WallpaperStyle\r\n\r\n        if (-not ($ReplaceTranscodedWallpaperFile)) {\r\n            Write-Warning \"Replacing the wallpaper transcoded file is required for wallpaper change to take immediate effect.\"\r\n            Write-Host \"\"\r\n            continue\r\n        }\r\n\r\n        # Replace the transcoded wallpaper\r\n        Reset-TranscodedWallpaper -Username $UserProfile.UserName -BasePath \"$($UserProfile.Path)AppDataRoaming\"\r\n        \r\n        Write-Host \"\"\r\n\r\n        # Unload NTuser.dat\r\n        If ($ProfileWasLoaded -eq $false) {\r\n            [gc]::Collect()\r\n            Start-Sleep 1\r\n            Start-Process -FilePath \"cmd.exe\" -ArgumentList \"\/C reg.exe UNLOAD HKU$($UserProfile.SID)\" -Wait -WindowStyle Hidden | Out-Null\r\n        }\r\n    }\r\n\r\n    if ($RestartExplorer) {\r\n        Reset-Explorer\r\n    }\r\n\r\n    exit 0\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Accedi a oltre 700 script nel Dojo NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Ottieni l&#8217;accesso<\/a><\/p>\n<\/div>\n<h2>Analisi dettagliata dello script per la gestione degli sfondi Windows<\/h2>\n<p>Lo script per la gestione degli sfondi Windows opera in diverse fasi:<\/p>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\"><strong>Inizializzazione dei parametri<\/strong>: Lo script per la gestione degli sfondi Windows inizia definendo parametri come l&#8217;URL dello sfondo, la directory di archiviazione e lo stile (ad esempio, Fill, Fit, Stretch).<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\"><strong>Controlli pre-esecuzione<\/strong>: Convalida lo stile dello sfondo e verifica l&#8217;esistenza dell&#8217;immagine e della directory specificate.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\"><strong>Scaricare lo sfondo<\/strong>: Se viene fornito un URL, lo script per la gestione degli sfondi Windows scarica l&#8217;immagine nella directory specificata.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Impostazione dello sfondo per ogni utente<\/strong>: Lo script per la gestione degli sfondi Windows modifica le impostazioni del registro per ogni profilo utente per cambiare lo sfondo. Gestisce anche casi speciali come gli account di sistema.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"5\" data-aria-level=\"1\"><strong>Opzioni a effetto immediato<\/strong>: Le opzioni di sostituzione del file di sfondo transcodificato e di riavvio del processo di Explorer assicurano che le modifiche abbiano effetto immediato.<\/li>\n<\/ul>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<p>Immagina che un amministratore IT di una grande azienda debba aggiornare gli sfondi Windows dei desktop con un nuovo logo aziendale su tutti i computer dei dipendenti. Utilizzando questo script per la gestione degli sfondi Windows, potr\u00e0 distribuire il nuovo sfondo su tutta la rete, garantendo che ogni utente, indipendentemente dalle impostazioni individuali, veda il marchio aggiornato.<\/p>\n<h2>Confronti<\/h2>\n<p>Tradizionalmente, la modifica degli sfondi Windows su pi\u00f9 profili richiedeva regolazioni manuali o effettuate tramite criteri di gruppo. Questo script offre un approccio pi\u00f9 diretto e flessibile, particolarmente utile in ambienti in cui i criteri di gruppo non sono utilizzabili o sono troppo complicati da implementare.<\/p>\n<h2>Domande frequenti<\/h2>\n<p><strong>D: Questo script per la gestione degli sfondi Windows funziona su tutte le versioni di Windows?<\/strong><br \/>\nR: Lo script per la gestione degli sfondi Windows \u00e8 stato progettato per Windows 7 e versioni successive, ma alcune funzionalit\u00e0 potrebbero non essere disponibili su versioni pi\u00f9 vecchie come Windows 7 o Server 2008.<\/p>\n<p><strong>D: Posso utilizzare qualsiasi formato di immagine come sfondo?<\/strong><br \/>\nR: Lo script per la gestione degli sfondi Windows supporta formati comuni come JPG, PNG, BMP e GIF.<\/p>\n<h2>Implicazioni<\/h2>\n<p>Se da un lato questo script per la gestione degli sfondi Windows offre una certa praticit\u00e0, dall&#8217;altro evidenzia la necessit\u00e0 di un&#8217;attenta gestione delle autorizzazioni e dei criteri di esecuzione degli script, in quanto richiede la modifica delle impostazioni del registro di sistema e dei file di sistema, che potrebbe comportare rischi per la sicurezza se effettuata in modo improprio.<\/p>\n<h2>Raccomandazioni<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"6\" data-aria-level=\"1\"><strong>Testa accuratamente<\/strong>: Testa sempre gli script in un ambiente controllato prima di distribuirli in tutta la rete.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"7\" data-aria-level=\"1\"><strong>Gestisci le autorizzazioni<\/strong>: Limita l&#8217;esecuzione degli script al personale autorizzato per evitare utilizzi scorretti.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"8\" data-aria-level=\"1\"><strong>Modifiche al documento<\/strong>: Tieni traccia di quando e come lo script per la gestione degli sfondi Windows viene utilizzato, per scopi di verifica e risoluzione dei problemi.<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>In un ambiente IT dinamico, strumenti come <a href=\"https:\/\/www.ninjaone.com\/it\/efficienza-it\/\">NinjaOne possono migliorare in modo significativo l&#8217;efficienza e l&#8217;efficacia di attivit\u00e0<\/a> come la distribuzione di questo script PowerShell. Grazie alle sue solide <a href=\"https:\/\/www.ninjaone.com\/it\/rmm\/automazione-it\/\">capacit\u00e0 di gestione e automazione<\/a>, NinjaOne \u00e8 in grado di semplificare il processo di distribuzione, rendendo pi\u00f9 semplice e affidabile per i professionisti IT il mantenimento di ambienti desktop coerenti tra pi\u00f9 profili utente. Questo allineamento tra automazione e gestione rafforza l&#8217;importanza di integrare strumenti potenti come gli <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/category\/scripts-it\">script PowerShell<\/a> in strategie di gestione IT pi\u00f9 ampie.<\/p>\n","protected":false},"author":35,"featured_media":207460,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4275],"class_list":["post-208181","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/208181","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=208181"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media\/207460"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=208181"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=208181"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=208181"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}