{"id":353711,"date":"2024-08-19T08:31:38","date_gmt":"2024-08-19T08:31:38","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/salvare-i-tipi-di-unita-con-powershell\/"},"modified":"2024-10-13T19:05:47","modified_gmt":"2024-10-13T19:05:47","slug":"salvare-i-tipi-di-unita-con-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/salvare-i-tipi-di-unita-con-powershell\/","title":{"rendered":"Come recuperare e salvare in modo efficiente le informazioni sui tipi di unit\u00e0 con PowerShell"},"content":{"rendered":"<p>La gestione efficiente delle risorse hardware \u00e8 fondamentale per i professionisti IT e per i <a href=\"https:\/\/www.ninjaone.com\/it\/cos-e-un-msp\" target=\"_blank\" rel=\"noopener\">Managed Service Provider (MSP)<\/a>. Un compito che si presenta spesso \u00e8 quello di <strong>identificare i tipi di unit\u00e0 installate in un sistema<\/strong>.<\/p>\n<p>Che si tratti di distinguere tra <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/ssd-vs-hdd-vs-sshd\/\" target=\"_blank\" rel=\"noopener\">SSD e HDD<\/a> o che si tratti di registrare i dettagli delle unit\u00e0 a scopo di inventario, disporre di un metodo affidabile per recuperare e salvare queste informazioni \u00e8 importantissimo. In questo articolo analizzeremo uno script <a href=\"https:\/\/www.ninjaone.com\/it\/it-hub\/gestione-degli-endpoint\/cos-e-powershell\/\" target=\"_blank\" rel=\"noopener\">PowerShell<\/a> progettato per questo scopo, spiegandone le funzionalit\u00e0, i potenziali casi d&#8217;uso e le best practice.<\/p>\n<h2>Background<\/h2>\n<p>I professionisti IT hanno spesso bisogno di raccogliere dettagli sull&#8217;hardware per vari motivi, come il monitoraggio delle prestazioni, la gestione dell&#8217;inventario e la risoluzione dei problemi. Lo script PowerShell fornito \u00e8 stato creato per recuperare informazioni sulle unit\u00e0 fisse, in particolare sulle unit\u00e0 a stato solido (SSD) e sulle unit\u00e0 a disco rigido (HDD), e per salvare i risultati in un campo personalizzato.<\/p>\n<p>Questo script \u00e8 particolarmente utile in ambienti in cui l&#8217;automazione e la precisione sono fondamentali, dato che offre una soluzione semplificata a un&#8217;attivit\u00e0 amministrativa comune.<\/p>\n<h2>Lo script per recuperare e salvare le informazioni sui tipi di unit\u00e0:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Get the drive types of all fixed SSD and HDD drives.\r\n.DESCRIPTION\r\n    Gets the drive types of all fixed SSD and HDD drives and can save the results to a custom field.\r\n\r\n.EXAMPLE\r\n    (No Parameters)\r\n    ## EXAMPLE OUTPUT WITHOUT PARAMS ##\r\n    DiskNumber DriveLetter MediaType BusType SerialNumber\r\n    ---------- ----------- --------- ------- ------------\r\n    0          C:          SSD       SATA    50026B768B3A4E3A\r\n    1          D:          HDD       SATA    WD-WCC4N0JYJYJY\r\n\r\nPARAMETER: -CustomFieldParam \"ReplaceMeWithAnyMultilineCustomField\"\r\n    The name of the custom field to save the results to.\r\n.EXAMPLE\r\n    -CustomFieldParam \"ReplaceMeWithAnyMultilineCustomField\"\r\n    ## EXAMPLE OUTPUT WITH CustomFieldParam ##\r\n    DiskNumber DriveLetter MediaType BusType SerialNumber\r\n    ---------- ----------- --------- ------- ------------\r\n    0          C:          SSD       SATA    50026B768B3A4E3A\r\n    1          D:          HDD       SATA    WD-WCC4N0JYJYJY\r\n    [Info] Saving the results to the custom field. (ReplaceMeWithAnyMultilineCustomField)\r\n    [Info] The results have been saved to the custom field. (ReplaceMeWithAnyMultilineCustomField)\r\n\r\nCustom Field Output:\r\n    #0, Letter: C:, Media: SSD, Bus: SATA, SN: 50026B768B3A4E3A\r\n    #1, Letter: D:, Media: HDD, Bus: SATA, SN: WD-WCC4N0JYJYJY\r\n\r\n.PARAMETER CustomFieldName\r\n    The name of the custom field to save the results to.\r\n.INPUTS\r\n    None\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10\/Server 2016\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]$CustomFieldName\r\n)\r\n\r\nbegin {\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n}\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n    if ($env:customFieldName -and $env:customFieldName -ne 'null') {\r\n        $CustomFieldName = $env:customFieldName\r\n    }\r\n\r\n    # Get the drive type of all drives\r\n    $Disks = Get-PhysicalDisk | Where-Object { $_.BusType -notlike \"File Backed Virtual\" -and -not ($_.PhysicalLocation -like \"*USB*\" -or $_.BusType -like \"*USB*\") } | Select-Object -Property DeviceID, MediaType, BusType, SerialNumber\r\n    if ($($Disks | Where-Object { $_.MediaType -like \"Unspecified\" }).Count) {\r\n        Write-Host \"[Info] An Unspecified MediaType likely indicates this machine is a VM or there is an issue with that drive.\"\r\n    }\r\n    # Get the partitions with mounted drive letters\r\n    $Partitions = Get-Partition | Where-Object { $_.DriveLetter -ne $null } | Select-Object -Property DriveLetter, DiskNumber\r\n    # Join the two collections\r\n    $Drives = $Disks | ForEach-Object {\r\n        $Disk = $_\r\n        $Partition = $Partitions | Where-Object { $_.DiskNumber -eq $Disk.DeviceID }\r\n        [PSCustomObject]@{\r\n            DiskNumber   = $_.DeviceID\r\n            DriveLetter  = $Partition.DriveLetter | Where-Object { $_ }\r\n            MediaType    = $_.MediaType\r\n            BusType      = $_.BusType\r\n            SerialNumber = $_.SerialNumber\r\n        }\r\n    }\r\n    $($Drives | Out-String) | Write-Host\r\n\r\n    # Save the results to a custom field\r\n    if ($CustomFieldName) {\r\n        Write-Host \"[Info] Saving the results to the custom field. ($CustomFieldName)\"\r\n        $CustomField = $(\r\n            $Drives | ForEach-Object {\r\n                \"#:$($_.DiskNumber), Letter: $($_.DriveLetter), Media: $($_.MediaType), Bus: $($_.BusType), SN: $($_.SerialNumber)\"\r\n            }\r\n        ) | Ninja-Property-Set-Piped -Name $CustomFieldName 2&gt;&amp;1\r\n        if ($CustomField.Exception) {\r\n            Write-Host $CustomField.Exception.Message\r\n            Write-Host \"[Error] Failed to save the results to the custom field. ($CustomFieldName)\"\r\n        }\r\n        else {\r\n            Write-Host \"[Info] The results have been saved to the custom field. ($CustomFieldName)\"\r\n        }\r\n    }\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"blog-cta-new blog-cta-style-1\"><div class=\"cta-left\"><h2><\/h2><p><\/p><\/div><div class=\"cta-right\"><a class=\"button\" href=\"\"><\/a><\/div><\/div>\n<h2>Analisi dettagliata<\/h2>\n<p>Analizziamo lo script passo per passo per capire la sua funzionalit\u00e0 e le modalit\u00e0 attraverso le quali raggiunge il suo obiettivo.<\/p>\n<h3>Prerequisiti<\/h3>\n<p>Lo script richiede PowerShell versione 5.1 o superiore. Inizia definendo una .SYNOPSIS e una .DESCRIPTION, utili per fornire una panoramica del suo scopo. Le sezioni .EXAMPLE mostrano i risultati attesi con e senza -CustomFieldParam.<\/p>\n<h3>Parametri e configurazione iniziale<\/h3>\n<p>Lo script accetta un parametro, CustomFieldName, che specifica il nome del campo personalizzato in cui verranno salvati i risultati. Include anche una funzione Test-IsElevated per verificare se lo script \u00e8 in esecuzione con privilegi di amministratore, necessari per accedere a informazioni dettagliate sull&#8217;unit\u00e0.<\/p>\n<h3>Elaborazione delle informazioni sull&#8217;unit\u00e0<\/h3>\n<ol>\n<li><strong>Controllo dei privilegi elevati<\/strong>: Lo script verifica innanzitutto se \u00e8 in esecuzione con i privilegi necessari. In caso contrario, termina con un messaggio di errore.<\/li>\n<li><strong>Gestione delle variabili d&#8217;ambiente<\/strong>: Se il nome di un campo personalizzato \u00e8 impostato tramite una variabile d&#8217;ambiente, questa sovrascrive il parametro dello script.<\/li>\n<li><strong>Recupero delle informazioni sulle unit\u00e0<\/strong>: Utilizzando Get-PhysicalDisk, lo script recupera tutte le unit\u00e0 fisiche, escludendo le unit\u00e0 virtuali e USB. Quindi seleziona le propriet\u00e0 rilevanti: DeviceID, MediaType, BusType e SerialNumber.<\/li>\n<li><strong>Informazioni sulla partizione<\/strong>: Lo script recupera i dettagli della partizione utilizzando Get-Partition, concentrandosi sulle partizioni con lettere di unit\u00e0 assegnate.<\/li>\n<li><strong>Aggregazione dei dati<\/strong>: Unisce le informazioni sulle unit\u00e0 fisiche e sulle partizioni, creando un elenco completo di unit\u00e0 con i rispettivi dettagli.<\/li>\n<\/ol>\n<h3>Salvataggio dell&#8217;output e dei campi personalizzati<\/h3>\n<p>Lo script invia le informazioni sull&#8217;unit\u00e0 alla console. Se viene fornito un CustomFieldName, formatta i dati e tenta di salvarli nel campo personalizzato specificato, utilizzando un ipotetico cmdlet Ninja-Property-Set-Piped. Gestisce i potenziali errori durante questo processo e fornisce un feedback sul successo dell&#8217;operazione.<\/p>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<p>Un MSP gestisce pi\u00f9 sistemi di clienti e deve verificare regolarmente le configurazioni hardware per garantire prestazioni ottimali e identificare potenziali problemi.<\/p>\n<p>Distribuendo questo script sui computer client, l&#8217;MSP pu\u00f2 automatizzare la raccolta delle informazioni sui tipi di unit\u00e0 e registrare i dati per riferimenti futuri. Ci\u00f2 consente di identificare rapidamente i sistemi che potrebbero beneficiare di aggiornamenti hardware, come la sostituzione di un HDD con un SSD per migliorare le prestazioni.<\/p>\n<h2>Confronti<\/h2>\n<p>Rispetto ai metodi manuali o all&#8217;utilizzo di strumenti diversi, questo script offre un approccio unificato all&#8217;interno dell&#8217;ambiente PowerShell, riducendo la necessit\u00e0 di applicazioni esterne. Anche se strumenti come Windows Management Instrumentation (WMI) o software di terze parti possono ottenere risultati simili, l&#8217;integrazione di questo script con i campi personalizzati e le sue capacit\u00e0 di automazione lo rendono una soluzione pi\u00f9 <a href=\"https:\/\/www.ninjaone.com\/it\/efficienza-it\" target=\"_blank\" rel=\"noopener\">efficiente<\/a> e scalabile.<\/p>\n<h2>Domande frequenti<\/h2>\n<ol>\n<li><strong> Ho bisogno di privilegi amministrativi per eseguire questo script?<\/strong> S\u00ec, lo script richiede privilegi di amministrazione per accedere alle informazioni dettagliate sull&#8217;unit\u00e0.<\/li>\n<li><strong>Questo script pu\u00f2 essere utilizzato su virtual machine?<\/strong> Lo script potrebbe non fornire risultati accurati sulle virtual machine, poich\u00e9 il MediaType pu\u00f2 essere elencato come &#8220;Unspecified&#8221;.<\/li>\n<li><strong>Cosa succede se il nome del campo personalizzato non viene fornito?<\/strong> Se il parametro CustomFieldName non \u00e8 specificato, lo script mostrer\u00e0 le informazioni sull&#8217;unit\u00e0 soltanto nella console.<\/li>\n<\/ol>\n<h2>Implicazioni<\/h2>\n<p>La verifica regolare dei tipi di unit\u00e0 pu\u00f2 avere implicazioni significative per la sicurezza e le prestazioni dell&#8217;IT. Per esempio, l&#8217;identificazione degli HDD pi\u00f9 vecchi consente di effettuare sostituzioni proattive, riducendo il rischio di perdita di dati a causa di un guasto dell&#8217;unit\u00e0. Inoltre, la comprensione dell&#8217;architettura di storage pu\u00f2 aiutare a ottimizzare le strategie di backup e a garantire che i dati critici siano archiviati sull&#8217;hardware pi\u00f9 affidabile.<\/p>\n<h2>Raccomandazioni<\/h2>\n<ul>\n<li>Esegui sempre lo script con privilegi elevati.<\/li>\n<li>Pianifica regolarmente l&#8217;esecuzione dello script su tutti i sistemi gestiti per mantenere aggiornati gli inventari hardware.<\/li>\n<li>Assicurati che ci siano un&#8217;adeguata gestione degli errori e meccanismi di logging per la risoluzione di eventuali problemi durante l&#8217;esecuzione.<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>Questo script PowerShell offre ai professionisti IT e agli MSP una soluzione affidabile per recuperare e salvare i tipi di unit\u00e0 in modo efficiente. Automatizzando questo processo, le organizzazioni possono mantenere inventari hardware accurati, ottimizzare le prestazioni e migliorare le strategie complessive di gestione IT.<\/p>\n<p>Strumenti come <a href=\"https:\/\/www.ninjaone.com\/it\/\" target=\"_blank\" rel=\"noopener\">NinjaOne<\/a> possono semplificare ulteriormente questo processo integrando script come questo in flussi di lavoro di automazione pi\u00f9 ampi, e fornendo una piattaforma di gestione IT completa che supporti operazioni proattive ed efficienti.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","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":"","_lmt_disable":""},"operating_system":[4212],"use_cases":[4269],"class_list":["post-353711","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/353711","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=353711"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=353711"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=353711"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=353711"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}