tankcr

Get-PCInfo

Aug 16th, 2022
1,287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#PSScriptInfo
  2.  
  3. .VERSION 3.5
  4.  
  5. .GUID ebf446a3-3362-4774-83c0-b7299410b63f
  6.  
  7. .AUTHOR Michael Niehaus
  8.  
  9. .COMPANYNAME Microsoft
  10.  
  11. .COPYRIGHT
  12.  
  13. .TAGS Windows AutoPilot
  14.  
  15. .LICENSEURI
  16.  
  17. .PROJECTURI
  18.  
  19. .ICONURI
  20.  
  21. .EXTERNALMODULEDEPENDENCIES
  22.  
  23. .REQUIREDSCRIPTS
  24.  
  25. .EXTERNALSCRIPTDEPENDENCIES
  26.  
  27. .RELEASENOTES
  28. Version 1.0:  Original published version.
  29. Version 1.1:  Added -Append switch.
  30. Version 1.2:  Added -Credential switch.
  31. Version 1.3:  Added -Partner switch.
  32. Version 1.4:  Switched from Get-WMIObject to Get-CimInstance.
  33. Version 1.5:  Added -GroupTag parameter.
  34. Version 1.6:  Bumped version number (no other change).
  35. Version 2.0:  Added -Online parameter.
  36. Version 2.1:  Bug fix.
  37. Version 2.3:  Updated comments.
  38. Version 2.4:  Updated "online" import logic to wait for the device to sync, added new parameter.
  39. Version 2.5:  Added AssignedUser for Intune importing, and AssignedComputerName for online Intune importing.
  40. Version 2.6:  Added support for app-based authentication via Connect-MSGraphApp.
  41. Version 2.7:  Added new Reboot option for use with -Online -Assign.
  42. Version 2.8:  Fixed up parameter sets.
  43. Version 2.9:  Fixed typo installing AzureAD module.
  44. Version 3.0:  Fixed typo for app-based auth, added logic to explicitly install NuGet (silently).
  45. Version 3.2:  Fixed logic to explicitly install NuGet (silently).
  46. Version 3.3:  Added more logging and error handling for group membership.
  47. Version 3.4:  Added logic to verify that devices were added successfully.  Fixed a bug that could cause all Autopilot devices to be added to the specified AAD group.
  48. Version 3.5:  Added logic to display the serial number of the gathered device.
  49. #>
  50.  
  51. <#
  52. .SYNOPSIS
  53. Retrieves the Windows AutoPilot deployment details from one or more computers
  54.  
  55. MIT LICENSE
  56.  
  57. Copyright (c) 2020 Microsoft
  58.  
  59. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  60.  
  61. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  62.  
  63. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  64.  
  65. .DESCRIPTION
  66. This script uses WMI to retrieve properties needed for a customer to register a device with Windows Autopilot.  Note that it is normal for the resulting CSV file to not collect a Windows Product ID (PKID) value since this is not required to register a device.  Only the serial number and hardware hash will be populated.
  67. .PARAMETER Name
  68. The names of the computers.  These can be provided via the pipeline (property name Name or one of the available aliases, DNSHostName, ComputerName, and Computer).
  69. .PARAMETER OutputFile
  70. The name of the CSV file to be created with the details for the computers.  If not specified, the details will be returned to the PowerShell
  71. pipeline.
  72. .PARAMETER Append
  73. Switch to specify that new computer details should be appended to the specified output file, instead of overwriting the existing file.
  74. .PARAMETER Credential
  75. Credentials that should be used when connecting to a remote computer (not supported when gathering details from the local computer).
  76. .PARAMETER Partner
  77. Switch to specify that the created CSV file should use the schema for Partner Center (using serial number, make, and model).
  78. .PARAMETER GroupTag
  79. An optional tag value that should be included in a CSV file that is intended to be uploaded via Intune (not supported by Partner Center or Microsoft Store for Business).
  80. .PARAMETER AssignedUser
  81. An optional value specifying the UPN of the user to be assigned to the device.  This can only be specified for Intune (not supported by Partner Center or Microsoft Store for Business).
  82. .PARAMETER Online
  83. Add computers to Windows Autopilot via the Intune Graph API
  84. .PARAMETER AssignedComputerName
  85. An optional value specifying the computer name to be assigned to the device.  This can only be specified with the -Online switch and only works with AAD join scenarios.
  86. .PARAMETER AddToGroup
  87. Specifies the name of the Azure AD group that the new device should be added to.
  88. .PARAMETER Assign
  89. Wait for the Autopilot profile assignment.  (This can take a while for dynamic groups.)
  90. .PARAMETER Reboot
  91. Reboot the device after the Autopilot profile has been assigned (necessary to download the profile and apply the computer name, if specified).
  92. .EXAMPLE
  93. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER -OutputFile .\MyComputer.csv
  94. .EXAMPLE
  95. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER -OutputFile .\MyComputer.csv -GroupTag Kiosk
  96. .EXAMPLE
  97. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER -OutputFile .\MyComputer.csv -GroupTag Kiosk -AssignedUser [email protected]
  98. .EXAMPLE
  99. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER -OutputFile .\MyComputer.csv -Append
  100. .EXAMPLE
  101. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER1,MYCOMPUTER2 -OutputFile .\MyComputers.csv
  102. .EXAMPLE
  103. Get-ADComputer -Filter * | .\GetWindowsAutoPilotInfo.ps1 -OutputFile .\MyComputers.csv
  104. .EXAMPLE
  105. Get-CMCollectionMember -CollectionName "All Systems" | .\GetWindowsAutoPilotInfo.ps1 -OutputFile .\MyComputers.csv
  106. .EXAMPLE
  107. .\Get-WindowsAutoPilotInfo.ps1 -ComputerName MYCOMPUTER1,MYCOMPUTER2 -OutputFile .\MyComputers.csv -Partner
  108. .EXAMPLE
  109. .\GetWindowsAutoPilotInfo.ps1 -Online
  110.  
  111. #>
  112.  
  113. [CmdletBinding(DefaultParameterSetName = 'Default')]
  114. param(
  115.     [Parameter(Mandatory=$False,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,Position=0)][alias("DNSHostName","ComputerName","Computer")] [String[]] $Name = @("localhost"),
  116.     [Parameter(Mandatory=$False)] [String] $OutputFile = "",
  117.     [Parameter(Mandatory=$False)] [String] $GroupTag = "",
  118.     [Parameter(Mandatory=$False)] [String] $AssignedUser = "",
  119.     [Parameter(Mandatory=$False)] [Switch] $Append = $false,
  120.     [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential] $Credential = $null,
  121.     [Parameter(Mandatory=$False)] [Switch] $Partner = $false,
  122.     [Parameter(Mandatory=$False)] [Switch] $Force = $false,
  123.     [Parameter(Mandatory=$True,ParameterSetName = 'Online')] [Switch] $Online = $false,
  124.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [String] $TenantId = "",
  125.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [String] $AppId = "",
  126.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [String] $AppSecret = "",
  127.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [String] $AddToGroup = "",
  128.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [String] $AssignedComputerName = "",
  129.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [Switch] $Assign = $false,
  130.     [Parameter(Mandatory=$False,ParameterSetName = 'Online')] [Switch] $Reboot = $false
  131. )
  132.  
  133. Begin
  134. {
  135.     # Initialize empty list
  136.     $computers = @()
  137.  
  138.     # If online, make sure we are able to authenticate
  139.     if ($Online) {
  140.  
  141.         # Get NuGet
  142.         $provider = Get-PackageProvider NuGet -ErrorAction Ignore
  143.         if (-not $provider) {
  144.             Write-Host "Installing provider NuGet"
  145.             Find-PackageProvider -Name NuGet -ForceBootstrap -IncludeDependencies
  146.         }
  147.        
  148.         # Get WindowsAutopilotIntune module (and dependencies)
  149.         $module = Import-Module WindowsAutopilotIntune -PassThru -ErrorAction Ignore
  150.         if (-not $module) {
  151.             Write-Host "Installing module WindowsAutopilotIntune"
  152.             Install-Module WindowsAutopilotIntune -Force
  153.         }
  154.         Import-Module WindowsAutopilotIntune -Scope Global
  155.  
  156.         # Get Azure AD if needed
  157.         if ($AddToGroup)
  158.         {
  159.             $module = Import-Module AzureAD -PassThru -ErrorAction Ignore
  160.             if (-not $module)
  161.             {
  162.                 Write-Host "Installing module AzureAD"
  163.                 Install-Module AzureAD -Force
  164.             }
  165.         }
  166.  
  167.         # Connect
  168.         if ($AppId -ne "")
  169.         {
  170.             $graph = Connect-MSGraphApp -Tenant $TenantId -AppId $AppId -AppSecret $AppSecret
  171.             Write-Host "Connected to Intune tenant $TenantId using app-based authentication (Azure AD authentication not supported)"
  172.         }
  173.         else {
  174.             $graph = Connect-MSGraph
  175.             Write-Host "Connected to Intune tenant $($graph.TenantId)"
  176.             if ($AddToGroup)
  177.             {
  178.                 $aadId = Connect-AzureAD -AccountId $graph.UPN
  179.                 Write-Host "Connected to Azure AD tenant $($aadId.TenantId)"
  180.             }
  181.         }
  182.  
  183.         # Force the output to a file
  184.         if ($OutputFile -eq "")
  185.         {
  186.             $OutputFile = "$($env:TEMP)\autopilot.csv"
  187.         }
  188.     }
  189. }
  190.  
  191. Process
  192. {
  193.     foreach ($comp in $Name)
  194.     {
  195.         $bad = $false
  196.  
  197.         # Get a CIM session
  198.         if ($comp -eq "localhost") {
  199.             $session = New-CimSession
  200.         }
  201.         else
  202.         {
  203.             $session = New-CimSession -ComputerName $comp -Credential $Credential
  204.         }
  205.  
  206.         # Get the common properties.
  207.         Write-Verbose "Checking $comp"
  208.         $serial = (Get-CimInstance -CimSession $session -Class Win32_BIOS).SerialNumber
  209.  
  210.         # Get the hash (if available)
  211.         $devDetail = (Get-CimInstance -CimSession $session -Namespace root/cimv2/mdm/dmmap -Class MDM_DevDetail_Ext01 -Filter "InstanceID='Ext' AND ParentID='./DevDetail'")
  212.         if ($devDetail -and (-not $Force))
  213.         {
  214.             $hash = $devDetail.DeviceHardwareData
  215.         }
  216.         else
  217.         {
  218.             $bad = $true
  219.             $hash = ""
  220.         }
  221.  
  222.         # If the hash isn't available, get the make and model
  223.         if ($bad -or $Force)
  224.         {
  225.             $cs = Get-CimInstance -CimSession $session -Class Win32_ComputerSystem
  226.             $make = $cs.Manufacturer.Trim()
  227.             $model = $cs.Model.Trim()
  228.             if ($Partner)
  229.             {
  230.                 $bad = $false
  231.             }
  232.         }
  233.         else
  234.         {
  235.             $make = ""
  236.             $model = ""
  237.         }
  238.  
  239.         # Getting the PKID is generally problematic for anyone other than OEMs, so let's skip it here
  240.         $product = ""
  241.  
  242.         # Depending on the format requested, create the necessary object
  243.         if ($Partner)
  244.         {
  245.             # Create a pipeline object
  246.             $c = New-Object psobject -Property @{
  247.                 "Device Serial Number" = $serial
  248.                 "Windows Product ID" = $product
  249.                 "Hardware Hash" = $hash
  250.                 "Manufacturer name" = $make
  251.                 "Device model" = $model
  252.             }
  253.             # From spec:
  254.             #   "Manufacturer Name" = $make
  255.             #   "Device Name" = $model
  256.  
  257.         }
  258.         else
  259.         {
  260.             # Create a pipeline object
  261.             $c = New-Object psobject -Property @{
  262.                 "Device Serial Number" = $serial
  263.                 "Windows Product ID" = $product
  264.                 "Hardware Hash" = $hash
  265.             }
  266.            
  267.             if ($GroupTag -ne "")
  268.             {
  269.                 Add-Member -InputObject $c -NotePropertyName "Group Tag" -NotePropertyValue $GroupTag
  270.             }
  271.             if ($AssignedUser -ne "")
  272.             {
  273.                 Add-Member -InputObject $c -NotePropertyName "Assigned User" -NotePropertyValue $AssignedUser
  274.             }
  275.         }
  276.  
  277.         # Write the object to the pipeline or array
  278.         if ($bad)
  279.         {
  280.             # Report an error when the hash isn't available
  281.             Write-Error -Message "Unable to retrieve device hardware data (hash) from computer $comp" -Category DeviceError
  282.         }
  283.         elseif ($OutputFile -eq "")
  284.         {
  285.             $c
  286.         }
  287.         else
  288.         {
  289.             $computers += $c
  290.             Write-Host "Gathered details for device with serial number: $serial"
  291.         }
  292.  
  293.         Remove-CimSession $session
  294.     }
  295. }
  296.  
  297. End
  298. {
  299.     if ($OutputFile -ne "")
  300.     {
  301.         if ($Append)
  302.         {
  303.             if (Test-Path $OutputFile)
  304.             {
  305.                 $computers += Import-CSV -Path $OutputFile
  306.             }
  307.         }
  308.         if ($Partner)
  309.         {
  310.             $computers | Select "Device Serial Number", "Windows Product ID", "Hardware Hash", "Manufacturer name", "Device model" | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''} | Out-File $OutputFile
  311.         }
  312.         elseif ($AssignedUser -ne "")
  313.         {
  314.             $computers | Select "Device Serial Number", "Windows Product ID", "Hardware Hash", "Group Tag", "Assigned User" | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''} | Out-File $OutputFile
  315.         }
  316.         elseif ($GroupTag -ne "")
  317.         {
  318.             $computers | Select "Device Serial Number", "Windows Product ID", "Hardware Hash", "Group Tag" | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''} | Out-File $OutputFile
  319.         }
  320.         else
  321.         {
  322.             $computers | Select "Device Serial Number", "Windows Product ID", "Hardware Hash" | ConvertTo-CSV -NoTypeInformation | % {$_ -replace '"',''} | Out-File $OutputFile
  323.         }
  324.     }
  325.     if ($Online)
  326.     {
  327.         # Add the devices
  328.         $importStart = Get-Date
  329.         $imported = @()
  330.         $computers | % {
  331.             $imported += Add-AutopilotImportedDevice -serialNumber $_.'Device Serial Number' -hardwareIdentifier $_.'Hardware Hash' -groupTag $_.'Group Tag' -assignedUser $_.'Assigned User'
  332.         }
  333.  
  334.         # Wait until the devices have been imported
  335.         $processingCount = 1
  336.         while ($processingCount -gt 0)
  337.         {
  338.             $current = @()
  339.             $processingCount = 0
  340.             $imported | % {
  341.                 $device = Get-AutopilotImportedDevice -id $_.id
  342.                 if ($device.state.deviceImportStatus -eq "unknown") {
  343.                     $processingCount = $processingCount + 1
  344.                 }
  345.                 $current += $device
  346.             }
  347.             $deviceCount = $imported.Length
  348.             Write-Host "Waiting for $processingCount of $deviceCount to be imported"
  349.             if ($processingCount -gt 0){
  350.                 Start-Sleep 30
  351.             }
  352.         }
  353.         $importDuration = (Get-Date) - $importStart
  354.         $importSeconds = [Math]::Ceiling($importDuration.TotalSeconds)
  355.         $successCount = 0
  356.         $current | % {
  357.             Write-Host "$($device.serialNumber): $($device.state.deviceImportStatus) $($device.state.deviceErrorCode) $($device.state.deviceErrorName)"
  358.             if ($device.state.deviceImportStatus -eq "complete") {
  359.                 $successCount = $successCount + 1
  360.             }
  361.         }
  362.         Write-Host "$successCount devices imported successfully.  Elapsed time to complete import: $importSeconds seconds"
  363.        
  364.         # Wait until the devices can be found in Intune (should sync automatically)
  365.         $syncStart = Get-Date
  366.         $processingCount = 1
  367.         while ($processingCount -gt 0)
  368.         {
  369.             $autopilotDevices = @()
  370.             $processingCount = 0
  371.             $current | % {
  372.                 if ($device.state.deviceImportStatus -eq "complete") {
  373.                     $device = Get-AutopilotDevice -id $_.state.deviceRegistrationId
  374.                     if (-not $device) {
  375.                         $processingCount = $processingCount + 1
  376.                     }
  377.                     $autopilotDevices += $device
  378.                 }  
  379.             }
  380.             $deviceCount = $autopilotDevices.Length
  381.             Write-Host "Waiting for $processingCount of $deviceCount to be synced"
  382.             if ($processingCount -gt 0){
  383.                 Start-Sleep 30
  384.             }
  385.         }
  386.         $syncDuration = (Get-Date) - $syncStart
  387.         $syncSeconds = [Math]::Ceiling($syncDuration.TotalSeconds)
  388.         Write-Host "All devices synced.  Elapsed time to complete sync: $syncSeconds seconds"
  389.  
  390.         # Add the device to the specified AAD group
  391.         if ($AddToGroup)
  392.         {
  393.             $aadGroup = Get-AzureADGroup -Filter "DisplayName eq '$AddToGroup'"
  394.             if ($aadGroup)
  395.             {
  396.                 $autopilotDevices | % {
  397.                     $aadDevice = Get-AzureADDevice -ObjectId "deviceid_$($_.azureActiveDirectoryDeviceId)"
  398.                     if ($aadDevice) {
  399.                         Write-Host "Adding device $($_.serialNumber) to group $AddToGroup"
  400.                         Add-AzureADGroupMember -ObjectId $aadGroup.ObjectId -RefObjectId $aadDevice.ObjectId
  401.                     }
  402.                     else {
  403.                         Write-Error "Unable to find Azure AD device with ID $($_.azureActiveDirectoryDeviceId)"
  404.                     }
  405.                 }
  406.                 Write-Host "Added devices to group '$AddToGroup' ($($aadGroup.ObjectId))"
  407.             }
  408.             else {
  409.                 Write-Error "Unable to find group $AddToGroup"
  410.             }
  411.         }
  412.  
  413.         # Assign the computer name
  414.         if ($AssignedComputerName -ne "")
  415.         {
  416.             $autopilotDevices | % {
  417.                 Set-AutopilotDevice -Id $_.Id -displayName $AssignedComputerName
  418.             }
  419.         }
  420.  
  421.         # Wait for assignment (if specified)
  422.         if ($Assign)
  423.         {
  424.             $assignStart = Get-Date
  425.             $processingCount = 1
  426.             while ($processingCount -gt 0)
  427.             {
  428.                 $processingCount = 0
  429.                 $autopilotDevices | % {
  430.                     $device = Get-AutopilotDevice -id $_.id -Expand
  431.                     if (-not ($device.deploymentProfileAssignmentStatus.StartsWith("assigned"))) {
  432.                         $processingCount = $processingCount + 1
  433.                     }
  434.                 }
  435.                 $deviceCount = $autopilotDevices.Length
  436.                 Write-Host "Waiting for $processingCount of $deviceCount to be assigned"
  437.                 if ($processingCount -gt 0){
  438.                     Start-Sleep 30
  439.                 }  
  440.             }
  441.             $assignDuration = (Get-Date) - $assignStart
  442.             $assignSeconds = [Math]::Ceiling($assignDuration.TotalSeconds)
  443.             Write-Host "Profiles assigned to all devices.  Elapsed time to complete assignment: $assignSeconds seconds"
  444.             if ($Reboot)
  445.             {
  446.                 Restart-Computer -Force
  447.             }
  448.         }
  449.     }
  450. }
  451.  
Advertisement
Add Comment
Please, Sign In to add comment