Power shell active directory средство выбора людей

В этой статье мы рассмотрим, как массово проверить ваши компьютеры на совместимость с Windows 11 с помощью PowerShell скрипта. За основу можно взять официальный скрипт HardwareReadiness.ps1 от Microsoft (https://aka.ms/HWReadinessScript).

Данный скрипт проверяет, что компьютер удовлетворяет следующим минимальным требованиям, необходимым для запуска Windows 11:

  • Совместимый x64 процессор (полный список поддерживаемых CPU)
  • 4+ ГБ RAM
  • Минимальный размер диска 64 ГБ
  • Устройство с UEFI и включенной Secure Boot
  • Видеокарта совместимая с DirectX 12 и WDDM 2.0 драйверов
  • TPM 2.0 модуль
  • Монитор с разрешением 720x

Чтобы вручную проверить совместимость отдельного компьютера с Windows 11,

  1. Cкачайте скрипт HardwareReadiness.ps1 по ссылке выше.
  2. Откройте консоль Windows PowerShell с правами администратора (в скрипте используется командлет Get-WMIObject, который не поддерживается в более новой версии PowerShell Core)
  3. Разрешите запуск PowerShell скрипта в текущей сессии:
    Set-ExecutionPolicy -Scope Process RemoteSigned
  4. Выполните скрипт:
    .\HardwareReadiness.ps1

PowerShell скрипт HardwareReadiness.ps1 - проверка компьютера на совместимость с Windows 11

Скрипт вернул код 0. Это значит, что компьютер совместим с требованиями Windows 11 (
returncode:0
,
resurnresult=CAPABLE
).

{"returnCode":0,"returnReason":"","logging":"Storage: OSDiskSize=427GB. PASS; Memory: System_Memory=32GB. PASS; TPM: TPMVersion=2.0, 0, 1.38. PASS; Processor: {AddressWidth=64; MaxClockSpeed=3901; NumberOfLogicalCores=12; Manufacturer=AuthenticAMD; Caption=AMD64 Family 25 Model 80 Stepping 0; }. PASS; SecureBoot: Capable. PASS; ","returnResult":"CAPABLE"}

Если нужно проверить множество корпоративных компьютеров на совместимость с Windows 11, тогда для распространения этого скрипта и сбора информации можно использовать такие инструменты как SCCM, Intune или даже WSUS для запуска сторонних скриптов. В самом простом случае можно запустить этот PowerShell скрипт с помощью групповых политик и сохранить результаты в свойства компьютера в Active Directory.

Код скрипт нужно немного модифицировать.

PowerShell скрипт для записи информации о совместимых с Win 11 компьютерах в AD

Данный код запишет в атрибут компьютера Info в Active Directory информацию о совместимости с Windows 11.

Скопируйте скрипт в папку
\\winitpro.loc\Netlogon
на контроллере домена.

PowerShell логон скрипт в папке NETLOGON

Откройте консоль управления доменными групповыми политиками (
gpmc.msc
) и создайте новую GPO для OU с компьютерами.

Перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown) -> Startup -> вкладка PowerShell Scripts и укажите UNC путь к скрипту HardwareReadiness.ps1

:/>  Как перезагрузить страницу на клавиатуре и работать в windows на клавиатуре. Полезные сочетания клавиш. Длинное сообщение⁠⁠

Запуск PowerShell скрипта при загрузке компьютера через GPO

Перезагрузите компьютер. Запустите консоль ADUC (
dsa.msc
), и откройте свойства компьютера. Перейдите на вкладку редактора атрибутов и проверьте, что в параметре Info теперь содержится результаты проверки компьютера на совместимость с Windows 11.

Информация о совместимости компьютера с Windows 11 в Active Directory

После того, как логон скрипт отработает на всех компьютерах, вы можете быстро вывести информацию о совместимых и не совместимых компьютерах из Active Directory с помощью командлета Get-ADComputer.

Get-ADComputer - значение атрибута

$Report = @()
$computers = Get-ADComputer -Filter {enabled -eq "true"} -properties *| Where-Object { $_.Info -match '"returnCode":1'}
foreach ($computer in $computers){
    $jsonString =$computer.info
    $object = $jsonString | ConvertFrom-Json
    $returnReasonValues = $object.returnReason -split ', '
    $CompInfo = [PSCustomObject]@{
          "Computer" = $computer.name
          "NonCompatibleItems" = $returnReasonValues
        }
    $Report += $CompInfo
}
$Report|fl

Для преобразования данных из JSON формата используется командлет ConvertFrom-Json.

PowerShell - собрать информацию о совместимости компьютеров с Windows 11 из Active Directory

It’s a very similar concept to our PowerShell Active Directory Group Picker. You can probably speed the search up by specifying an ADSI SearchRoot, this way it will only search a specific organisation unit in Active Directory as opposed to everywhere! But for this example we’ll search everywhere.

We’ve also limited the results to 30 to speed up the search too.

cls
Add-Type -AssemblyName PresentationCore,PresentationFramework
function Select-ADObject
{  
$form = New-Object System.Windows.Forms.Form
$form.Text = "Active Directory Search"
$form.Size = New-Object System.Drawing.Size(340,320)
$form.StartPosition = "CenterScreen"
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Point(260,10)
$SearchButton.Size = New-Object System.Drawing.Size(50,23)
$SearchButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$SearchButton.Text = 'Search'
$SearchButton.Add_Click({
$SearchButton.Enabled = $false
$CancelButton.Enabled = $false
#start progress bar
$ProgressBar.Style="Marquee"
$ProgressBar.MarqueeAnimationSpeed = 10;
$searchVal = $SearchText.Text
$job = Start-Job -ArgumentList $searchVal -ScriptBlock  {
param($searchVal)                      
if ($searchVal -ne $null -and $searchVal -ne "") {
$objSearcher=[adsisearcher]"(&(objectCategory=person)(|(name=*$searchVal*)(samaccountname=*$searchVal*)))"
$objSearcher.SizeLimit = 30
$colProplist = "name"
foreach ($i in $colPropList) { $objSearcher.PropertiesToLoad.Add($i) | out-null } 
$colResults = $objSearcher.FindAll()
}
return $colResults
}
while($job.State -eq 'Running') {
[System.Windows.Forms.Application]::DoEvents()
}
$results = $job | Receive-Job -AutoRemoveJob -Wait
$ListBox.Items.Clear()                
if ($results -eq $null -or $results.Count -eq 0) {
$SearchButton.Enabled = $true
$CancelButton.Enabled = $true
#needed to reset marquee to 0
$ProgressBar.Style="Blocks"
$ProgressBar.MarqueeAnimationSpeed = 0;
$ProgressBar.Value = 0;
$SelectButton.Enabled = $false
[System.Windows.MessageBox]::Show("Search returned no results.")
return
}
foreach ($objResult in $results)
{          
[void] $ListBox.Items.Add(($objResult.Properties).name[0])	
}
$SearchButton.Enabled = $true
$CancelButton.Enabled = $true
#needed to reset marquee to 0
$ProgressBar.Style="Blocks"
$ProgressBar.MarqueeAnimationSpeed = 0;
$ProgressBar.Value = 0;
return
})
$form.Controls.Add($SearchButton)
$SearchText = New-Object System.Windows.Forms.TextBox
$SearchText.Location = New-Object System.Drawing.Point(10,11)
$SearchText.Size = New-Object System.Drawing.Size(245,20)
$SearchText.Multiline = $false   
$SearchText.AcceptsReturn = $true 
$SearchText.Add_KeyUp({
if ($_.KeyCode -eq [System.Windows.Forms.Keys]::Enter) {
$SearchButton.PerformClick()
}
})
$form.Controls.Add($SearchText)
$SelectButton = New-Object System.Windows.Forms.Button
$SelectButton.Location = New-Object System.Drawing.Point(205,245)
$SelectButton.Size = New-Object System.Drawing.Size(50,23)
$SelectButton.Text = "Select"
$SelectButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$SelectButton.Add_Click({ 
if ($ListBox.SelectedItems.Count -eq 0) {
[System.Windows.MessageBox]::Show("No item selected.")
return
}
$script:selectedADGroup = $ListBox.SelectedItem; 
write-host $ListBox.SelectedText; 
$form.Close() 
})
$SelectButton.Enabled = $false
$form.Controls.Add($SelectButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(260,245)
$CancelButton.Size = New-Object System.Drawing.Size(50,23)
$CancelButton.Text = "Cancel"
$CancelButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$CancelButton.Add_Click({ $script:selectedADGroup = $null; $form.Close()})
$form.Controls.Add($CancelButton)
$ListBox = New-Object System.Windows.Forms.ListBox
$ListBox.Location = New-Object System.Drawing.Point(10,40)
$ListBox.Size = New-Object System.Drawing.Size(300, 20)
$ListBox.Height = 200
$ListBox.Add_SelectedIndexChanged({
if ($ListBox.SelectedItems.Count -eq 1) {
$SelectButton.Enabled = $true
}
})
$form.Controls.Add($ListBox)
$ProgressBar = New-Object System.Windows.Forms.ProgressBar
$ProgressBar.Location = New-Object System.Drawing.Point(10, 246)
$ProgressBar.Size = New-Object System.Drawing.Size(190, 21)
$ProgressBar.Value = 0
$ProgressBar.Style="Marquee"
$ProgressBar.MarqueeAnimationSpeed = 0;
$form.Controls.Add($ProgressBar)
$form.TopMost = $true
$form.Add_Shown({$form.Activate(); $SearchText.focus()})
[void] $form.ShowDialog()
return $script:selectedADGroup
}
$selectedObject = Select-ADObject
write-host $selectedObject

PowerShell Active Directory People Picker

PowerShell Active Directory People Picker

In this article, we’ll examine how to employ Microsoft’s official HardwareReadiness.ps1 PowerShell script to run a bulk Windows 11 hardware compatibility check on domain computers.

  • A compatible x64 processor (complete list of supported CPUs)
  • At least 4 GB of RAM
  • A minimum of 64 GB hard drive size
  • A device that has UEFI and Secure Boot enabled
  • A video card that is compatible with DirectX 12 and has WDDM 2.0 drivers
  • A TPM 2.0 module
:/>  Копирование файлов в командной строке Windows

To manually verify if a specific machine’s hardware is in compliance with the requirements of Windows 11:

  1. Download the HardwareReadiness.ps1 script by clicking here.
  2. Launch an elevated Windows PowerShell console (this script utilizes the Get-WMIObject cmdlet, which is not supported in latest versions of PowerShell Core)
  3. Activate PowerShell script execution in the existing session with the following command: Set-ExecutionPolicy -Scope Process RemoteSigned
  4. Commence the script using the following command: .HardwareReadiness.ps1

Once executed, the script should return the code 0. This indicates that your machine satisfies the hardware requirements for Windows 11 (the output would be returncode:0 , returnresult=CAPABLE).

If you need to conduct a large-scale Windows 11 compatibility check on enterprise computers, a feasible tool to use would be this PowerShell script. This Script effectively gathers information through mediums like SCCM, Intune, or even WSUS, whose capabilities extend to deploying third-party software and scripts. In more straightforward scenarios, execution of this PowerShell script via Group Policies and storing the results in the properties of the computer object in Active Directory proves to be sufficient.

Keep in mind that the original source code of the script will need to be slightly adjusted.

A point of note is that this PowerShell script file is digitally signed by Microsoft. It is however important to keep in mind that the signing certificate expired in 2022.

This above PowerShell script completes the task of entering Windows 11 compatibility data into the ‘Info’ computer attribute located within Active Directory.

Ensure to copy the aforementioned PS1 script file into the directory labeled \woshub.locNetlogon present on the domain controller.

:/>  Как закрыть файл с помощью клавиатуры на компьютере

Open the Domain Group Policy Management console (gpmc.msc), create a new GPO, and link it to the computer’s OU.

Navigate to Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown) -> Startup -> tab PowerShell Scripts, and specify the UNC path to the HardwareReadiness.ps1 script

Reboot the client’s computer. Start the ADUC console (dsa.msc) and open the computer properties. Go to the Attribute Editor tab and check that the Info parameter now contains the results of checking your computer for Windows 11 compatibility. In the Attribute Editor tab, check that the Info parameter now contains the results of your computer’s Windows 11 compatibility check.

Once the logon script has been run on all computers, you can quickly view information about compatible and incompatible computers from Active Directory by using the Get-ADComputer cmdlet:

$Report = @()

$returnReasonValues = $object.returnReason -split ', '

"Computer" = $computer.name

"NonCompatibleItems" = $returnReasonValues

$Report += $CompInfo

The ConvertFrom-Json cmdlet is used to convert data from JSON format.

Оставьте комментарий