From 46c0be732a91891a32589c26bbfe17913a9defe3 Mon Sep 17 00:00:00 2001 From: Alejandro Rosales Date: Thu, 1 Oct 2026 10:16:24 -0600 Subject: [PATCH] Configure CED Wi-Fi policy and scoped management enrollment --- README.md | 1 + docs/ced-network-operations.md | 192 ++++++++++++++++++++++ scripts/Connect-SguCedWifi.ps1 | 122 ++++++++++++++ scripts/Install-SguCedWifiMaintenance.ps1 | 32 ++++ scripts/Invoke-SguCedClientEnrollment.ps1 | 45 +++++ scripts/Invoke-SguCedPreparation.ps1 | 100 +++++++++++ scripts/Set-SguCedClientSource.ps1 | 44 +++++ scripts/Set-SguCedConfigMgrCollection.ps1 | 31 ++++ scripts/Set-SguCedDnsPolicy.ps1 | 29 ++++ scripts/Set-SguCedWacCertificate.ps1 | 42 +++++ scripts/Set-SguCedWifiPolicy.ps1 | 129 +++++++++++++++ scripts/Sync-SguCedWifiReaders.ps1 | 82 +++++++++ scripts/Sync-SguWacDomainConnections.ps1 | 23 ++- scripts/Test-SguCedManagedNodes.ps1 | 55 +++++++ 14 files changed, 921 insertions(+), 6 deletions(-) create mode 100644 docs/ced-network-operations.md create mode 100644 scripts/Connect-SguCedWifi.ps1 create mode 100644 scripts/Install-SguCedWifiMaintenance.ps1 create mode 100644 scripts/Invoke-SguCedClientEnrollment.ps1 create mode 100644 scripts/Invoke-SguCedPreparation.ps1 create mode 100644 scripts/Set-SguCedClientSource.ps1 create mode 100644 scripts/Set-SguCedConfigMgrCollection.ps1 create mode 100644 scripts/Set-SguCedDnsPolicy.ps1 create mode 100644 scripts/Set-SguCedWacCertificate.ps1 create mode 100644 scripts/Set-SguCedWifiPolicy.ps1 create mode 100644 scripts/Sync-SguCedWifiReaders.ps1 create mode 100644 scripts/Test-SguCedManagedNodes.ps1 diff --git a/README.md b/README.md index 2a49c07..ea48445 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ visible while the browser populates those controls asynchronously. Operational documentation: +- [Centro de Experiencia Digital Wi-Fi policy and management](docs/ced-network-operations.md) - [One-command server recovery and client enrollment](docs/bootstrap-recovery.md) - [Broker location, health, timeout, and recovery](docs/broker-operations.md) - [Windows domain join and remote-access onboarding](docs/windows-client-onboarding.md) diff --git a/docs/ced-network-operations.md b/docs/ced-network-operations.md new file mode 100644 index 0000000..44b7d67 --- /dev/null +++ b/docs/ced-network-operations.md @@ -0,0 +1,192 @@ +# Centro de Experiencia Digital network + +The managed Wi-Fi network is **Centro de Experiencia Digital**, on the ASUS +GT-AX11000 Pro. It replaces Aula Flexible and Sala de Desarrollo for the CED PCs. +Configuration is scoped to: + +```text +OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx +``` + +The rollout targets AF-02 through AF-06, AF-08 through AF-11, and SD-01 through +SD-30: 39 domain computers. LCI-77 uses a local Wi-Fi profile and remains outside +the domain. Its Ethernet connection is retained. + +## Router configuration + +| Network | Result | +| --- | --- | +| Centro de Experiencia Digital | VLAN 53, 192.168.54.0/24, gateway 192.168.54.1, WPA2/WPA3-Personal, AES, 2.4/5 GHz | +| Sala de Desarrollo | Disabled, configuration retained for recovery | +| Sala Inmersiva | Existing SSID, key, VLAN 54 and 192.168.55.0/24 retained | +| Invitados CED | Retained | +| Esports CED | Retained with its pre-existing enable/disable state | +| NewMatrix | Existing main network retained | + +The previous Aula Flexible shared key is retained privately. The old 20 Mbps +download / 5 Mbps upload cap is removed from the CED network. DHCP provides the +domain DNS server at 192.168.54.211. AP isolation is off for management between +the CED PCs. Existing separation of the other guest networks is retained. + +Router configuration changes restart shared radios and can interrupt all Wi-Fi +connections briefly, including unchanged SSIDs. SGU-DC02 itself is connected by +Wi-Fi, despite LCI-77 having Ethernet. Prepare a server reconnection task before +applying router changes. Radio/DFS readiness can take several minutes; do not +repeat Apply while waiting for recovery. + +## Group Policy and future computers + +`Set-SguCedWifiPolicy.ps1` publishes a native computer WLAN policy in +**CED - Wi-Fi de salas**. The profile remains a read-only Group Policy profile; +it is not a manually imported all-user profile. The GPO is linked only to the +CED OU and disables user settings. + +The Personal shared key is stored in the native AD WLAN policy object. Its ACL +permits the CED computer reader group and direct CED computer SIDs, plus the +administrative/system identities needed to maintain it. The key is not stored +in SYSVOL scripts or in this repository. Exported profiles containing the key +must remain in an administrator-only private directory. + +On the tested Windows clients, the native CSE left the Personal key unprotected +and connection attempts failed. `Connect-SguCedWifi.ps1` uses the documented +Native Wi-Fi `WlanSetProfile` API to protect that key on the client while keeping +the Group Policy profile flag. It then connects and requires a successful WLAN +event for both the expected profile name and SSID. No location privacy setting +is changed. Successful live connections are left running. + +The computer startup policy installs **CED WiFi policy connection**, a SYSTEM +task that runs at startup and every 15 minutes. The task requires the native +Group Policy profile. Its code directory permits writes only by SYSTEM and +local administrators. **CED WiFi OU readers refresh** on SGU-DC02 updates the +reader group and direct policy ACLs every 15 minutes, removing computers that +leave the OU. No domain administrator password is stored in these tasks. + +New domain computers in the OU receive policy automatically after reader refresh +and normal Group Policy processing. They still need an initial path to a domain +controller, such as Ethernet or an existing Wi-Fi profile, to join the domain +and receive their first policy. A cached Personal profile can reconnect without +RADIUS or a certificate authority. Domain DNS and management services still +depend on their servers being available. + +`Set-SguCedDnsPolicy.ps1` creates **CED - DNS de dominio**, linked only to the +same OU. Its NRPT rule directs the internal domain namespace to 192.168.54.211. +This avoids public Ethernet DNS competing with Wi-Fi domain DNS on multihomed +PCs. Public namespaces retain their normal resolution settings. +The managed Wi-Fi adapter also has 192.168.54.1 as a secondary resolver for +public names if the domain DNS server is unavailable. Internal names continue +to use the NRPT domain rule; public fallback does not provide domain services. + +## Windows Admin Center + +`Set-SguCedWacCertificate.ps1` provisions a non-exportable RSA 3072-bit server +certificate for `sgu-dc02.lci.lasalle.mx` and `sgu-dc02`, binds it to the WAC +frontend, and distributes its public trust through **CED - Confianza de +administracion** in the CED OU. It backs up the previous WAC settings before +changing the binding. It does not install a certificate authority. + +LCI-77 trusts the public certificate in the current user's Root store. This does +not join it to the domain. Keep the WAC private key on SGU-DC02. Renew the +certificate and update the trust policy before expiry. + +`Sync-SguWacDomainConnections.ps1 -ComputerOuDn ` limits inventory additions +to this OU. Verification queries actual OS instances through WAC; having a saved +connection alone is not proof of management connectivity. Existing unrelated WAC +inventory entries are not deleted. Authentication and certificate validation +remain enabled. + +## Configuration Manager + +The existing collection **LCI00014** is named **Centro de Experiencia Digital**. +Its query uses the exact CED canonical OU. Periodic and incremental evaluation +are enabled, preserving the collection ID and existing client-setting deployments. +AD system discovery remains enabled, including its existing incremental polling. +`Set-SguCedConfigMgrCollection.ps1` reproduces this configuration. + +`Set-SguCedClientSource.ps1` prepares the complete Microsoft-signed client media +in `C:\ProgramData\LCI-Admin\ClientSource`, shared as `CEDClient$` with encrypted +SMB. CED computers have read access, including direct computer permissions for +machines whose existing Kerberos tickets predate reader-group membership. The +administrative `SMS_LCI` share is not opened to client computers. + +Use `/source` alone for this source, plus the installation properties +`SMSSITECODE=LCI SMSMP=sgu-dc02.lci.lasalle.mx`. Adding `/mp` gives management-point +and distribution-point discovery priority and previously left these installs +waiting. The native startup policy also installs a SYSTEM enrollment task for +future CED computers. It validates current OU membership and the Microsoft +signature, skips an existing client or running setup, and retries every 30 minutes. + +For an existing computer migration, prepare DNS/policy and migrate Wi-Fi first. +Verify the new connection before starting the client installer. Changing Wi-Fi +during source download can fail the installation and require a retry. + +```powershell +# Run on SGU-DC02 with authorized administrative credentials supplied in memory. +.\scripts\Set-SguCedClientSource.ps1 +.\scripts\Set-SguCedWifiPolicy.ps1 -ProfilePath +.\scripts\Sync-SguCedWifiReaders.ps1 -InstallRefreshTask +.\scripts\Set-SguCedDnsPolicy.ps1 +.\scripts\Set-SguCedWacCertificate.ps1 +.\scripts\Set-SguCedConfigMgrCollection.ps1 + +$credential = Get-Credential +.\scripts\Invoke-SguCedPreparation.ps1 -InventoryPath -Credential $credential -MigrateWifi +.\scripts\Test-SguCedManagedNodes.ps1 -Credential $credential +.\scripts\Invoke-SguCedPreparation.ps1 -InventoryPath -Credential $credential -InstallClient +``` + +Inventory JSON is an array of `Name`, `IP`, and `WinRM` properties. Preparation +validates the AD scope and actual remote hostname, domain, and secure channel +before changing anything. It prefers current DNS over a stale DHCP inventory +address. Existing DNS settings are backed up on each client. + +## Rollout validation — October 1, 2026 + +After the final router radio restart, the live client validation returned: + +| Check | Result | +| --- | --- | +| CED computers in scope | 39 | +| Reachable over authenticated WinRM | 39 | +| Live CED SSID and matching successful policy profile event | 39 | +| CcmExec running and site LCI assigned | 39 | +| WAC public certificate trusted in the machine Root store | 39 | +| WAC returned actual OS instances over validated HTTPS | 39 | + +ConfigMgr also reported 39 CED resources with `Client=1` and the expected OU +attribute. SD-06 was initially unavailable; it was prepared, migrated, installed, +and validated after being made available. The client installer logs on SD-06, +SD-09, and the SD-27 pilot returned exit code 0. LCI-77 successfully reconnected +with its local profile while remaining outside the domain. The router UI showed +the new SSID with WPA2/WPA3-Personal and Sala de Desarrollo disabled. + +Private per-machine validation JSON and the router screenshot are stored outside +Git in the administrator's private CED network directory. No passwords, shared +keys, private certificates, or original clear-key WLAN exports are committed. + +## Verification and recovery + +`Test-SguCedManagedNodes.ps1` checks live SSID, the successful profile event, +reachable WinRM, CcmExec, assigned site, and WAC root trust. Also verify the WAC +OS endpoint, ConfigMgr server-side client registration, and collection membership. +An installation wizard success screen or a scheduled installation request does +not establish that installation completed. + +To recover the previous Wi-Fi, first provision an existing known-good profile +and reconnection task on SGU-DC02 and affected PCs. Then restore Aula Flexible on +VLAN 53, or re-enable the preserved Sala de Desarrollo network, as appropriate. +Disable the CED GPO links and remove the CED maintenance/enrollment tasks when +rolling back the managed configuration. Use each client's `CED-dns-before.json` +to restore DNS. For WAC, restore the saved frontend settings and certificate +binding before removing the public trust policy. Do not remove unrelated GPOs, +profiles, certificates, or guest networks. + +The existing Configuration Manager 2103 / Windows Server 2025 support limitation +is not changed by this network repair. + +## References + +- [Microsoft native WLAN Group Policy protocol](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-gpwl/481e4e64-5e95-4ada-aae8-ec93ed69559a) +- [Native Wi-Fi profile storage and key protection](https://learn.microsoft.com/en-us/windows/win32/api/wlanapi/nf-wlanapi-wlansetprofile) +- [Computer startup script protocol](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-gpscr/ff1fd13e-1e18-4160-9b50-0263e108e5e1) +- [Configuration Manager client source selection](https://learn.microsoft.com/en-us/intune/configmgr/core/servers/deploy/configure/boundary-groups-distribution-points) +- [Domain DNS policy cmdlet](https://learn.microsoft.com/en-us/powershell/module/dnsclient/add-dnsclientnrptrule) diff --git a/scripts/Connect-SguCedWifi.ps1 b/scripts/Connect-SguCedWifi.ps1 new file mode 100644 index 0000000..b1fe383 --- /dev/null +++ b/scripts/Connect-SguCedWifi.ps1 @@ -0,0 +1,122 @@ +[CmdletBinding()] +param( + [string]$ProfileName = 'Centro de Experiencia Digital', + [string]$Ssid = '', + [ValidateRange(1,30)][int]$TimeoutMinutes = 10, + [string]$FallbackProfile = '', + [string]$StatusPath = '', + [switch]$Force, + [switch]$RequireGroupPolicy +) +$ErrorActionPreference = 'Stop' +if (-not $Ssid) { $Ssid = $ProfileName } +# Connect to the already provisioned profile. Do not scan BSSIDs or change +# Windows location consent: those operations are unnecessary for this task. +if (-not ('Sgu.CedWlan' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.Runtime.InteropServices; +namespace Sgu { + public static class CedWlan { + [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] + public struct Parameters { + public int Mode; + [MarshalAs(UnmanagedType.LPWStr)] public string Profile; + public IntPtr Ssid; + public IntPtr Bssids; + public int BssType; + public uint Flags; + } + [DllImport("wlanapi.dll")] static extern uint WlanOpenHandle(uint version,IntPtr reserved,out uint negotiated,out IntPtr handle); + [DllImport("wlanapi.dll")] static extern uint WlanEnumInterfaces(IntPtr handle,IntPtr reserved,out IntPtr list); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanConnect(IntPtr handle,ref Guid id,ref Parameters parameters,IntPtr reserved); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanGetProfile(IntPtr handle,ref Guid id,string profile,IntPtr reserved,out IntPtr xml,ref uint flags,out uint access); + [DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanSetProfile(IntPtr handle,ref Guid id,uint flags,string xml,string security,[MarshalAs(UnmanagedType.Bool)] bool overwrite,IntPtr reserved,out uint reason); + [DllImport("wlanapi.dll")] static extern uint WlanCloseHandle(IntPtr handle,IntPtr reserved); + [DllImport("wlanapi.dll")] static extern void WlanFreeMemory(IntPtr memory); + static void Check(uint result) { if(result!=0) throw new System.ComponentModel.Win32Exception((int)result); } + public static void Connect(string profile, bool requireGroupPolicy) { + IntPtr handle=IntPtr.Zero, list=IntPtr.Zero; uint version; + Check(WlanOpenHandle(2,IntPtr.Zero,out version,out handle)); + try { + Check(WlanEnumInterfaces(handle,IntPtr.Zero,out list)); + int count=Marshal.ReadInt32(list); + if(count==0) throw new InvalidOperationException("No WLAN interfaces."); + for(int i=0;ifalse")) { + uint reason; Check(WlanSetProfile(handle,ref id,1,xml,null,true,IntPtr.Zero,out reason)); + } + } finally { if(xmlPointer!=IntPtr.Zero) WlanFreeMemory(xmlPointer); } + Parameters p=new Parameters { Mode=0,Profile=profile,BssType=1,Flags=0 }; + Check(WlanConnect(handle,ref id,ref p,IntPtr.Zero)); + } + } finally { if(list!=IntPtr.Zero) WlanFreeMemory(list); WlanCloseHandle(handle,IntPtr.Zero); } + } + } +} +'@ +} +$start = Get-Date +$deadline = $start.AddMinutes($TimeoutMinutes) +function Write-Status([string]$Status, $Details) { + if ($StatusPath) { + [pscustomobject]@{Time=Get-Date;Profile=$ProfileName;Status=$Status;Details=$Details} | + ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $StatusPath -Encoding UTF8 + } +} +if (-not $Force) { + $liveSsid = @() + try { + $connections = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetConnectionProfiles() + $liveSsid = @($connections | Where-Object IsWlanConnectionProfile | ForEach-Object { $_.WlanConnectionProfileDetails.GetConnectedSsid() }) + } catch { # An unavailable SSID API means we must verify a fresh connection event. + } + $latest = Get-WinEvent -FilterHashtable @{ + LogName='Microsoft-Windows-WLAN-AutoConfig/Operational';Id=8001,8003 + } -MaxEvents 1 -ErrorAction SilentlyContinue + if ($liveSsid -contains $Ssid -and $latest -and $latest.Id -eq 8001) { + [xml]$latestXml = $latest.ToXml() + $data = $latestXml.Event.EventData.Data + if (@($data | Where-Object { $_.Name -eq 'SSID' -and $_.'#text' -eq $Ssid }).Count -and + @($data | Where-Object { $_.Name -eq 'ProfileName' -and $_.'#text' -eq $ProfileName }).Count) { + Write-Status 'AlreadyConnected' $null + return + } + } +} +try { +do { + [Sgu.CedWlan]::Connect($ProfileName,[bool]$RequireGroupPolicy) + Start-Sleep -Seconds 10 + $connected = Get-WinEvent -FilterHashtable @{ + LogName='Microsoft-Windows-WLAN-AutoConfig/Operational';Id=8001;StartTime=$start + } -MaxEvents 20 -ErrorAction SilentlyContinue | Where-Object { + [xml]$eventXml = $_.ToXml() + $eventData = $eventXml.Event.EventData.Data + @($eventData | Where-Object { $_.Name -eq 'SSID' -and $_.'#text' -eq $Ssid }).Count -gt 0 -and + @($eventData | Where-Object { $_.Name -eq 'ProfileName' -and $_.'#text' -eq $ProfileName }).Count -gt 0 + } + if ($connected) { + Register-DnsClient -ErrorAction SilentlyContinue + Write-Status 'Connected' $null + return + } +} while ((Get-Date) -lt $deadline) +$failures = @(Get-WinEvent -FilterHashtable @{ + LogName='Microsoft-Windows-WLAN-AutoConfig/Operational';Id=8002;StartTime=$start +} -MaxEvents 3 -ErrorAction SilentlyContinue | ForEach-Object Message) +Write-Status 'Failed' $failures +throw "No successful WLAN connection event for '$ProfileName' within $TimeoutMinutes minutes." +} catch { + Write-Status 'Failed' $_.Exception.Message + if ($FallbackProfile) { [Sgu.CedWlan]::Connect($FallbackProfile,$false) } + throw +} diff --git a/scripts/Install-SguCedWifiMaintenance.ps1 b/scripts/Install-SguCedWifiMaintenance.ps1 new file mode 100644 index 0000000..da21d92 --- /dev/null +++ b/scripts/Install-SguCedWifiMaintenance.ps1 @@ -0,0 +1,32 @@ +[CmdletBinding()] +param() +$ErrorActionPreference = 'Stop' +# Invoked by the CED computer startup policy, after the native WLAN CSE. +$destination = 'C:\ProgramData\LCI-Admin\CED-WiFi' +New-Item $destination -ItemType Directory -Force | Out-Null +$dnsBackup = 'C:\ProgramData\LCI-Admin\CED-dns-before.json' +if (-not (Test-Path $dnsBackup)) { + Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object InterfaceAlias,InterfaceIndex,ServerAddresses | + ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $dnsBackup +} +# Keep public DNS available through the router if the domain DNS server is +# offline. The separate CED NRPT GPO still pins internal names to domain DNS. +$wifi = @(Get-NetAdapter | Where-Object { $_.NdisPhysicalMedium -eq 9 -and $_.Status -eq 'Up' }) +foreach ($adapter in $wifi) { + Set-DnsClientServerAddress -InterfaceIndex $adapter.InterfaceIndex -ServerAddresses '192.168.54.211','192.168.54.1' +} +$acl = [Security.AccessControl.DirectorySecurity]::new() +$acl.SetAccessRuleProtection($true,$false) +foreach ($sid in 'S-1-5-18','S-1-5-32-544') { + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) +} +Set-Acl -LiteralPath $destination -AclObject $acl +Copy-Item (Join-Path $PSScriptRoot 'Connect-SguCedWifi.ps1') $destination -Force +$helper = Join-Path $destination 'Connect-SguCedWifi.ps1' +$arguments = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}" -RequireGroupPolicy -TimeoutMinutes 2 -StatusPath "{1}"' -f $helper,(Join-Path $destination 'status.json') +$action = New-ScheduledTaskAction -Execute "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument $arguments +$triggers = @((New-ScheduledTaskTrigger -AtStartup),(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15))) +$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 5) +Register-ScheduledTask -TaskName 'CED WiFi policy connection' -Action $action -Trigger $triggers -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null +Start-ScheduledTask 'CED WiFi policy connection' diff --git a/scripts/Invoke-SguCedClientEnrollment.ps1 b/scripts/Invoke-SguCedClientEnrollment.ps1 new file mode 100644 index 0000000..401d119 --- /dev/null +++ b/scripts/Invoke-SguCedClientEnrollment.ps1 @@ -0,0 +1,45 @@ +[CmdletBinding()] +param([switch]$InstallTask) +$ErrorActionPreference = 'Stop' +$directory = 'C:\ProgramData\LCI-Admin\CED-Client' +if ($InstallTask) { + New-Item $directory -ItemType Directory -Force | Out-Null + $acl = [Security.AccessControl.DirectorySecurity]::new() + $acl.SetAccessRuleProtection($true,$false) + foreach ($sid in 'S-1-5-18','S-1-5-32-544') { + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) + } + Set-Acl $directory $acl + $localScript = Join-Path $directory 'Invoke-SguCedClientEnrollment.ps1' + if ($PSCommandPath -ine $localScript) { Copy-Item $PSCommandPath $localScript -Force } + $action = New-ScheduledTaskAction -Execute powershell.exe -Argument ('-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}"' -f $localScript) + $triggers = @((New-ScheduledTaskTrigger -AtStartup),(New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 30))) + $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 5) + Register-ScheduledTask 'CED Configuration Manager policy enrollment' -Action $action -Trigger $triggers -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null + Start-ScheduledTask 'CED Configuration Manager policy enrollment' + return +} +if (Get-Service CcmExec -ErrorAction SilentlyContinue) { return } +if (Get-Process ccmsetup -ErrorAction SilentlyContinue) { return } +# Check the machine's current OU with its own domain identity. An offline DC +# defers enrollment; an existing Wi-Fi connection continues using its cached PSK. +$root = [ADSI]'LDAP://RootDSE' +$search = [DirectoryServices.DirectorySearcher]::new([ADSI]("LDAP://"+[string]$root.defaultNamingContext)) +try { + $search.Filter = '(&(objectClass=computer)(sAMAccountName='+$env:COMPUTERNAME+'$))' + [void]$search.PropertiesToLoad.Add('distinguishedName') + $result = $search.FindOne() + $dn = [string]$result.Properties['distinguishedname'][0] + $ou = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx' + if (-not $dn.EndsWith(','+$ou,[StringComparison]::OrdinalIgnoreCase)) { return } +} finally { $search.Dispose() } +$source = '\\sgu-dc02.lci.lasalle.mx\CEDClient$' +$bootstrap = Join-Path $source 'ccmsetup.exe' +$signature = Get-AuthenticodeSignature $bootstrap +if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike '*Microsoft Corporation*') { + throw 'Client bootstrapper is not a valid Microsoft-signed binary.' +} +Copy-Item $bootstrap (Join-Path $directory 'ccmsetup.exe') -Force +& (Join-Path $directory 'ccmsetup.exe') /service /source:$source SMSSITECODE=LCI SMSMP=sgu-dc02.lci.lasalle.mx +# ccmsetup/service runs asynchronously. Its own log and CcmExec verify completion. diff --git a/scripts/Invoke-SguCedPreparation.ps1 b/scripts/Invoke-SguCedPreparation.ps1 new file mode 100644 index 0000000..987d4a8 --- /dev/null +++ b/scripts/Invoke-SguCedPreparation.ps1 @@ -0,0 +1,100 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$InventoryPath, + [Parameter(Mandatory)][PSCredential]$Credential, + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$DomainController = $env:COMPUTERNAME, + [string]$DnsServer = '192.168.54.211', + [string]$FallbackDnsServer = '192.168.54.1', + [switch]$InstallClient, + [switch]$MigrateWifi, + [switch]$RestartPendingInstall, + [string]$ClientSource = '\\sgu-dc02.lci.lasalle.mx\CEDClient$' +) +$ErrorActionPreference = 'Stop' +Import-Module ActiveDirectory +$domain = Get-ADDomain -Server $DomainController +Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null +$allowed = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController) +$inventory = Get-Content -LiteralPath $InventoryPath -Raw | ConvertFrom-Json +$source = 'C:\Program Files\Microsoft Configuration Manager\Client\ccmsetup.exe' +if ($InstallClient) { + $signature = Get-AuthenticodeSignature -LiteralPath $source + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike '*Microsoft Corporation*') { + throw 'The Configuration Manager installer is not a valid Microsoft signed binary.' + } +} +$options = New-PSSessionOption -OpenTimeout 10000 -OperationTimeout 180000 +foreach ($item in $inventory) { + if ($item.WinRM -eq $false) { continue } + if ($item.Name -notin $allowed.Name) { throw "Inventory host outside approved OU: $($item.Name)" } + [Net.IPAddress]::Parse($item.IP) | Out-Null + $session = $null + try { + $address = $item.IP + # After migration the old DHCP address is stale. Prefer a reachable + # current AD/DNS hostname, then validate the actual remote identity. + $hostname = ($allowed | Where-Object Name -eq $item.Name).DNSHostName + if (-not $hostname) { $hostname = $item.Name+'.'+$domain.DNSRoot } + $probe = [Net.Sockets.TcpClient]::new() + try { + $pending = $probe.BeginConnect($hostname,5985,$null,$null) + if ($pending.AsyncWaitHandle.WaitOne(1000) -and $probe.Connected) { $address = $hostname } + } catch { } finally { $probe.Dispose() } + $session = New-PSSession -ComputerName $address -Credential $Credential -Authentication Negotiate -SessionOption $options + $identity = Invoke-Command -Session $session { + [pscustomobject]@{Name=$env:COMPUTERNAME;Domain=(Get-CimInstance Win32_ComputerSystem).Domain;Trusted=Test-ComputerSecureChannel} + } + if ($identity.Name -ine $item.Name -or $identity.Domain -ine $domain.DNSRoot -or -not $identity.Trusted) { + throw 'Remote identity/domain/secure-channel validation failed.' + } + $state = Invoke-Command -Session $session -ArgumentList $DnsServer,$domain.DNSRoot,$FallbackDnsServer { + param($dns,$suffix,$fallbackDns) + New-Item C:\ProgramData\LCI-Admin -ItemType Directory -Force | Out-Null + $backup = 'C:\ProgramData\LCI-Admin\CED-dns-before.json' + if (-not (Test-Path $backup)) { + Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object InterfaceAlias,InterfaceIndex,ServerAddresses | + ConvertTo-Json -Depth 3 | Set-Content -LiteralPath $backup + } + $wifi = @(Get-NetAdapter | Where-Object { $_.NdisPhysicalMedium -eq 9 -and $_.Status -eq 'Up' }) + if ($wifi.Count -ne 1) { throw 'Expected one active Wi-Fi interface.' } + Set-DnsClientServerAddress -InterfaceIndex $wifi[0].InterfaceIndex -ServerAddresses @($dns,$fallbackDns) + Set-DnsClient -InterfaceIndex $wifi[0].InterfaceIndex -ConnectionSpecificSuffix $suffix -RegisterThisConnectionsAddress $true + Register-DnsClient + & gpupdate.exe /target:computer /force /wait:90 | Out-Null + if ($LASTEXITCODE) { throw "gpupdate failed: $LASTEXITCODE" } + [pscustomobject]@{Name=$env:COMPUTERNAME;WifiPolicyPresent=(netsh.exe wlan show profiles | Select-String 'Centro de Experiencia Digital').Count -gt 0;ClientPresent=[bool](Get-Service CcmExec -ErrorAction SilentlyContinue)} + } + if (-not $state.WifiPolicyPresent) { throw 'Native CED Wi-Fi policy was not applied.' } + if ($InstallClient -and -not $state.ClientPresent) { + Copy-Item -LiteralPath $source -Destination C:\ProgramData\LCI-Admin\ccmsetup.exe -ToSession $session + Invoke-Command -Session $session -ArgumentList $ClientSource,[bool]$RestartPendingInstall { + param($clientSource,$restartPending) + if (-not $restartPending -and (Get-Process ccmsetup -ErrorAction SilentlyContinue)) { return } + # Replace a pending installer that was waiting for an inaccessible source. + if (Get-Service ccmsetup -ErrorAction SilentlyContinue) { + Stop-Service ccmsetup -Force -ErrorAction SilentlyContinue + } + # /source alone forces the complete SMB media. Combining it with + # /mp gives MP/DP discovery priority and can leave setup waiting. + $action = New-ScheduledTaskAction -Execute C:\ProgramData\LCI-Admin\ccmsetup.exe -Argument ('/source:"{0}" SMSSITECODE=LCI SMSMP=sgu-dc02.lci.lasalle.mx' -f $clientSource) + Register-ScheduledTask -TaskName 'CED Configuration Manager enrollment' -Action $action -User SYSTEM -RunLevel Highest -Force | Out-Null + Start-ScheduledTask -TaskName 'CED Configuration Manager enrollment' + } + } + if ($MigrateWifi) { + foreach ($file in 'Connect-SguCedWifi.ps1','Install-SguCedWifiMaintenance.ps1') { + Copy-Item (Join-Path $PSScriptRoot $file) (Join-Path C:\ProgramData\LCI-Admin $file) -ToSession $session -Force + } + Invoke-Command -Session $session { + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\ProgramData\LCI-Admin\Install-SguCedWifiMaintenance.ps1 + if ($LASTEXITCODE) { throw 'Wi-Fi maintenance task installation failed.' } + } + } + [pscustomobject]@{Name=$item.Name;IP=$item.IP;Prepared=$true;ClientPresent=$state.ClientPresent;InstallationRequested=[bool]$InstallClient;Error=$null} + } catch { + [pscustomobject]@{Name=$item.Name;IP=$item.IP;Prepared=$false;ClientPresent=$false;InstallationRequested=$false;Error=$_.Exception.Message} + } finally { + if ($session) { Remove-PSSession $session } + } +} diff --git a/scripts/Set-SguCedClientSource.ps1 b/scripts/Set-SguCedClientSource.ps1 new file mode 100644 index 0000000..3f71549 --- /dev/null +++ b/scripts/Set-SguCedClientSource.ps1 @@ -0,0 +1,44 @@ +[CmdletBinding()] +param( + [string]$SourcePath = 'C:\Program Files\Microsoft Configuration Manager\Client', + [string]$DestinationPath = 'C:\ProgramData\LCI-Admin\ClientSource', + [string]$ShareName = 'CEDClient$', + [string]$ReaderGroup = 'LCI\CED-WiFi-Equipos', + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx' +) +$ErrorActionPreference = 'Stop' +foreach ($file in 'ccmsetup.exe','x64\client.msi') { + if (-not (Test-Path (Join-Path $SourcePath $file))) { throw "Missing client media: $file" } +} +if ((Get-AuthenticodeSignature (Join-Path $SourcePath 'ccmsetup.exe')).Status -ne 'Valid') { + throw 'Client bootstrapper signature is invalid.' +} +New-Item -ItemType Directory -Path $DestinationPath -Force | Out-Null +$acl = [Security.AccessControl.DirectorySecurity]::new() +$acl.SetAccessRuleProtection($true,$false) +foreach ($sid in 'S-1-5-18','S-1-5-32-544') { + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) +} +$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + $ReaderGroup,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')) +Import-Module ActiveDirectory +$domain = Get-ADDomain +$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true') +foreach ($computer in $computers) { + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + $computer.SID,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')) +} +Set-Acl -LiteralPath $DestinationPath -AclObject $acl +& robocopy.exe $SourcePath $DestinationPath /E /COPY:DAT /DCOPY:DAT /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null +if ($LASTEXITCODE -ge 8) { throw "Client media copy failed: $LASTEXITCODE" } +$share = Get-SmbShare -Name $ShareName -ErrorAction SilentlyContinue +if ($share -and $share.Path -ne $DestinationPath) { throw 'Share already exists at a different path.' } +if (-not $share) { + New-SmbShare -Name $ShareName -Path $DestinationPath -ReadAccess $ReaderGroup -FullAccess 'BUILTIN\Administrators' -EncryptData $true | Out-Null +} +foreach ($computer in $computers) { + # Direct machine permissions avoid waiting for existing Kerberos group tickets. + Grant-SmbShareAccess -Name $ShareName -AccountName ($domain.NetBIOSName+'\'+$computer.SamAccountName) -AccessRight Read -Force | Out-Null +} +[pscustomobject]@{Source="\\$env:COMPUTERNAME\$ShareName";Readers=$ReaderGroup;MediaVersion=(Get-Item (Join-Path $DestinationPath 'ccmsetup.exe')).VersionInfo.FileVersion} diff --git a/scripts/Set-SguCedConfigMgrCollection.ps1 b/scripts/Set-SguCedConfigMgrCollection.ps1 new file mode 100644 index 0000000..3dc938d --- /dev/null +++ b/scripts/Set-SguCedConfigMgrCollection.ps1 @@ -0,0 +1,31 @@ +[CmdletBinding()] +param( + [string]$SiteCode = 'LCI', + [string]$CollectionId = 'LCI00014', + [string]$CollectionName = 'Centro de Experiencia Digital', + [string]$OuCanonicalName = 'LCI.LASALLE.MX/LABORATORIO/CENTRO DE EXPERIENCIA DIGITAL', + [string]$ConsoleModule = 'C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1' +) +$ErrorActionPreference = 'Stop' +if ($OuCanonicalName -match '["\r\n]') { throw 'Invalid OU canonical name.' } +Import-Module $ConsoleModule +Push-Location ($SiteCode+':\') +try { + $collection = Get-CMDeviceCollection -CollectionId $CollectionId + if (-not $collection) { throw 'Expected managed collection is missing.' } + $rules = @(Get-CMDeviceCollectionQueryMembershipRule -CollectionId $CollectionId) + if ($rules.Count -gt 1) { throw 'Review unexpected additional membership rules before changing this collection.' } + $query = 'select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.SystemOUName = "'+$OuCanonicalName+'"' + if (-not $rules.Count -or $rules[0].QueryExpression -cne $query) { + if ($rules.Count) { Remove-CMDeviceCollectionQueryMembershipRule -CollectionId $CollectionId -RuleName $rules[0].RuleName -Force } + Add-CMDeviceCollectionQueryMembershipRule -CollectionId $CollectionId -RuleName 'Centro de Experiencia Digital OU' -QueryExpression $query + } + if ($collection.Name -cne $CollectionName) { + Set-CMDeviceCollection -CollectionId $CollectionId -NewName $CollectionName -RefreshType Both + } else { + Set-CMDeviceCollection -CollectionId $CollectionId -RefreshType Both + } + Invoke-CMSystemDiscovery -SiteCode $SiteCode + Invoke-CMCollectionUpdate -CollectionId $CollectionId + [pscustomobject]@{CollectionId=$CollectionId;Name=$CollectionName;OU=$OuCanonicalName;Evaluation='Periodic and incremental'} +} finally { Pop-Location } diff --git a/scripts/Set-SguCedDnsPolicy.ps1 b/scripts/Set-SguCedDnsPolicy.ps1 new file mode 100644 index 0000000..51f7dc3 --- /dev/null +++ b/scripts/Set-SguCedDnsPolicy.ps1 @@ -0,0 +1,29 @@ +[CmdletBinding()] +param( + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$GpoName = 'CED - DNS de dominio', + [string]$DnsServer = '192.168.54.211', + [string]$DomainController = $env:COMPUTERNAME +) +$ErrorActionPreference = 'Stop' +Import-Module ActiveDirectory +Import-Module GroupPolicy +$domain = Get-ADDomain -Server $DomainController +Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null +$gpo = Get-GPO -Name $GpoName -Domain $domain.DNSRoot -Server $DomainController -ErrorAction SilentlyContinue +if (-not $gpo) { $gpo = New-GPO -Name $GpoName -Domain $domain.DNSRoot -Server $DomainController } +if ($gpo.GpoStatus -ne 'UserSettingsDisabled') { $gpo.GpoStatus = [Microsoft.GroupPolicy.GpoStatus]::UserSettingsDisabled } +$name = $domain.DNSRoot+'\'+$GpoName +$namespace = '.'+$domain.DNSRoot +$rules = @(Get-DnsClientNrptRule -GpoName $name -Server $DomainController) +$rule = @($rules | Where-Object { $_.Namespace -contains $namespace }) +if ($rule.Count -gt 1) { throw 'Duplicate domain DNS policy rules.' } +if (-not $rule.Count) { + Add-DnsClientNrptRule -GpoName $name -Server $DomainController -Namespace $namespace -NameServers $DnsServer -DisplayName 'CED internal domain DNS' | Out-Null +} elseif ($rule[0].NameServers -ne $DnsServer) { + Set-DnsClientNrptRule -GpoName $name -Server $DomainController -Name $rule[0].Name -NameServers $DnsServer +} +$link = (Get-GPInheritance -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController).GpoLinks | Where-Object GpoId -eq $gpo.Id +if (-not $link) { New-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } +elseif (-not $link.Enabled) { Set-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } +[pscustomobject]@{Gpo=$GpoName;TargetOu=$TargetOuDn;Namespace=$namespace;NameServers=$DnsServer} diff --git a/scripts/Set-SguCedWacCertificate.ps1 b/scripts/Set-SguCedWacCertificate.ps1 new file mode 100644 index 0000000..266ad78 --- /dev/null +++ b/scripts/Set-SguCedWacCertificate.ps1 @@ -0,0 +1,42 @@ +[CmdletBinding()] +param( + [string]$DomainController = $env:COMPUTERNAME, + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$GpoName = 'CED - Confianza de administracion', + [string[]]$DnsNames = @('sgu-dc02.lci.lasalle.mx','sgu-dc02'), + [string]$ExportPath = 'C:\ProgramData\LCI-Admin\CED-WAC.cer' +) +$ErrorActionPreference = 'Stop' +Import-Module ActiveDirectory +Import-Module GroupPolicy +Import-Module 'C:\Program Files\WindowsAdminCenter\PowerShellModules\Microsoft.WindowsAdminCenter.Configuration\Microsoft.WindowsAdminCenter.Configuration.psm1' +$domain = Get-ADDomain -Server $DomainController +Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null +$subject = 'CN=CED-WAC-SGU-DC02' +$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq $subject -and $_.HasPrivateKey -and $_.NotAfter -gt (Get-Date).AddMonths(3) } | Sort-Object NotAfter -Descending | Select-Object -First 1 +if (-not $cert) { + $cert = New-SelfSignedCertificate -Type SSLServerAuthentication -Subject $subject -DnsName $DnsNames -CertStoreLocation Cert:\LocalMachine\My -Provider 'Microsoft RSA SChannel Cryptographic Provider' -KeyAlgorithm RSA -KeyLength 3072 -KeySpec KeyExchange -KeyExportPolicy NonExportable -HashAlgorithm SHA256 -NotAfter (Get-Date).AddYears(2) -FriendlyName 'CED Windows Admin Center HTTPS' +} +New-Item -ItemType Directory -Path (Split-Path $ExportPath -Parent) -Force | Out-Null +Export-Certificate -Cert $cert -FilePath $ExportPath -Force | Out-Null +Import-Certificate -FilePath $ExportPath -CertStoreLocation Cert:\LocalMachine\Root | Out-Null +$blob = Get-ItemPropertyValue -LiteralPath "HKLM:\SOFTWARE\Microsoft\SystemCertificates\Root\Certificates\$($cert.Thumbprint)" -Name Blob +$gpo = Get-GPO -Name $GpoName -Domain $domain.DNSRoot -Server $DomainController -ErrorAction SilentlyContinue +if (-not $gpo) { $gpo = New-GPO -Name $GpoName -Domain $domain.DNSRoot -Server $DomainController } +$gpo.GpoStatus = [Microsoft.GroupPolicy.GpoStatus]::UserSettingsDisabled +Set-GPRegistryValue -Guid $gpo.Id -Domain $domain.DNSRoot -Server $DomainController -Key "HKLM\Software\Policies\Microsoft\SystemCertificates\Root\Certificates\$($cert.Thumbprint)" -ValueName Blob -Type Binary -Value $blob | Out-Null +$links = (Get-GPInheritance -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController).GpoLinks +if ($gpo.Id -notin $links.GpoId) { New-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController | Out-Null } +$keyPath = Join-Path "$env:ProgramData\Microsoft\Crypto\RSA\MachineKeys" $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName +$acl = Get-Acl -LiteralPath $keyPath +$sid = [Security.Principal.SecurityIdentifier]::new('S-1-5-20') +$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'Read','Allow')) +Set-Acl -LiteralPath $keyPath -AclObject $acl +$settings = 'C:\Program Files\WindowsAdminCenter\Service\appsettings.json' +$old = (Get-Content -LiteralPath $settings -Raw | ConvertFrom-Json).Kestrel.Endpoints.WindowsAdminCenter.Certificate.Subject +if ($old -ne 'CED-WAC-SGU-DC02') { + Copy-Item -LiteralPath $settings -Destination (Join-Path (Split-Path $ExportPath -Parent) "WAC-before-CED-$((Get-Date).ToString('yyyyMMddHHmmss')).json") + Set-WACCertificateSubjectName -Thumbprint $cert.Thumbprint -Target FrontEnd + Restart-WACService +} +[pscustomobject]@{Gpo=$GpoName;TargetOu=$TargetOuDn;Thumbprint=$cert.Thumbprint;DnsNames=@($cert.DnsNameList.Unicode);Expires=$cert.NotAfter;PublicCertificate=$ExportPath;PreviousSubject=$old} diff --git a/scripts/Set-SguCedWifiPolicy.ps1 b/scripts/Set-SguCedWifiPolicy.ps1 new file mode 100644 index 0000000..3b7f056 --- /dev/null +++ b/scripts/Set-SguCedWifiPolicy.ps1 @@ -0,0 +1,129 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$ProfilePath, + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$GpoName = 'CED - Wi-Fi de salas', + [string]$DomainController = $env:COMPUTERNAME, + [string]$ReaderGroup = 'CED-WiFi-Equipos' +) +$ErrorActionPreference = 'Stop' +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') { + if (-not (Test-Path (Join-Path $PSScriptRoot $file))) { throw "Deploy the complete script set; missing $file." } +} +Import-Module ActiveDirectory +Import-Module GroupPolicy +$domain = Get-ADDomain -Server $DomainController +$ou = Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController +if ($ou.DistinguishedName -notlike "*,$($domain.DistinguishedName)") { throw 'OU is outside this domain.' } +[xml]$profile = Get-Content -LiteralPath $ProfilePath -Raw +$ns = [Xml.XmlNamespaceManager]::new($profile.NameTable) +$ns.AddNamespace('w', 'http://www.microsoft.com/networking/WLAN/profile/v1') +$ssid = $profile.SelectSingleNode('//w:SSID/w:name', $ns).InnerText +$auth = $profile.SelectSingleNode('//w:authEncryption/w:authentication', $ns).InnerText +if ($auth -notin 'WPA2PSK','WPA3SAE' -or $profile.SelectSingleNode('//w:authEncryption/w:encryption', $ns).InnerText -ne 'AES') { + throw 'Only WPA2/WPA3 Personal with AES is supported.' +} +if ($profile.SelectSingleNode('//w:sharedKey/w:protected', $ns).InnerText -ne 'false') { + throw 'Supply a privately stored export with key=clear. Never commit that XML.' +} +$keyLength = $profile.SelectSingleNode('//w:sharedKey/w:keyMaterial', $ns).InnerText.Length +$keyType = $profile.SelectSingleNode('//w:sharedKey/w:keyType', $ns).InnerText +if ($keyType -eq 'networkKey') { + if ($auth -ne 'WPA2PSK' -or $profile.SelectSingleNode('//w:sharedKey/w:keyMaterial', $ns).InnerText -notmatch '^[0-9A-Fa-f]{64}$') { throw 'Invalid WPA2 network key.' } +} elseif ($keyType -ne 'passPhrase' -or $keyLength -lt 8 -or $keyLength -gt 63) { throw 'Invalid passphrase length.' } +$profile.SelectSingleNode('/w:WLANProfile/w:name', $ns).InnerText = $ssid +$profile.SelectSingleNode('//w:connectionMode', $ns).InnerText = 'auto' +$group = Get-ADGroup -Filter "SamAccountName -eq '$ReaderGroup'" -Server $DomainController +if (-not $group) { + $group = New-ADGroup -Name $ReaderGroup -SamAccountName $ReaderGroup -GroupCategory Security -GroupScope Global -Path $TargetOuDn -Server $DomainController -PassThru +} +if (-not $group.DistinguishedName.EndsWith(",$TargetOuDn",[StringComparison]::OrdinalIgnoreCase)) { throw 'Reader group is outside the target OU.' } +$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController) +$members = @(Get-ADGroupMember $group -Server $DomainController) +$add = @($computers | Where-Object { $_.DistinguishedName -notin $members.DistinguishedName }) +$remove = @($members | Where-Object { $_.DistinguishedName -notin $computers.DistinguishedName }) +if ($add.Count) { Add-ADGroupMember $group -Members $add -Server $DomainController } +if ($remove.Count) { Remove-ADGroupMember $group -Members $remove -Server $DomainController -Confirm:$false } +$gpo = Get-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot -ErrorAction SilentlyContinue +if (-not $gpo) { $gpo = New-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot } +if ($gpo.GpoStatus -ne 'UserSettingsDisabled') { $gpo.GpoStatus = [Microsoft.GroupPolicy.GpoStatus]::UserSettingsDisabled } +$gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)" +$parent = "CN=Machine,$gpoDn" +foreach ($name in 'Microsoft','Windows','IEEE80211') { + $dn = "CN=$name,$parent" + if (-not (Get-ADObject -SearchBase $parent -SearchScope OneLevel -LDAPFilter "(cn=$name)" -Server $DomainController)) { + New-ADObject -Name $name -Type container -Path $parent -Server $DomainController + } + $parent = $dn +} +$policyDn = "CN=CED Wi-Fi,$parent" +$escapedName = [Security.SecurityElement]::Escape($ssid) +$policyXml = '' + + "$escapedNameWi-Fi administrado exclusivamente para la OU CED." + + 'truefalsefalse' + + 'truefalse' + + '' + $profile.DocumentElement.OuterXml + '' +$policy = Get-ADObject -SearchBase $parent -SearchScope OneLevel -LDAPFilter '(cn=CED Wi-Fi)' -Server $DomainController -Properties ms-net-ieee-80211-GP-PolicyData +$changed = -not $policy -or $policy.'ms-net-ieee-80211-GP-PolicyData' -cne $policyXml -or $add.Count -gt 0 -or $remove.Count -gt 0 +if (-not $policy) { + # The native WLAN CSE reads this AD object (MS-GPWL), not a startup-script profile. + New-ADObject -Name 'CED Wi-Fi' -Type ms-net-ieee-80211-GroupPolicy -Path $parent -Server $DomainController -OtherAttributes @{ + 'ms-net-ieee-80211-GP-PolicyGUID' = ([guid]::NewGuid()).ToString('B') + 'description' = 'CED managed wireless profile. Contains a PSK; restricted computer read access.' + } +} +# Remove inherited read access BEFORE publishing/updating any existing PSK. +$entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$policyDn") +try { + $security = $entry.ObjectSecurity + $security.SetAccessRuleProtection($true, $false) + foreach ($rule in @($security.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier]))) { $security.RemoveAccessRuleSpecific($rule) } + $forestRoot = Get-ADDomain -Identity (Get-ADForest -Server $DomainController).RootDomain -Server $DomainController + $controller = Get-ADComputer -Identity ($DomainController.Split('.')[0]) -Server $DomainController + foreach ($sid in @('S-1-5-18', "$($domain.DomainSID)-512", "$($forestRoot.DomainSID)-519", $controller.SID.Value)) { + $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),[DirectoryServices.ActiveDirectoryRights]::GenericAll,[Security.AccessControl.AccessControlType]::Allow)) + } + $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($group.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow)) + # Direct computer ACEs avoid needing a reboot to refresh machine group tokens. + foreach ($computer in $computers) { + $security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow)) + } + $entry.ObjectSecurity = $security + $entry.CommitChanges() +} finally { $entry.Dispose() } +if ($changed) { Set-ADObject $policyDn -Server $DomainController -Replace @{'ms-net-ieee-80211-GP-PolicyData'=$policyXml} } +$adGpo = Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber,gPCMachineExtensionNames +$root = Join-Path $env:WINDIR "SYSVOL\domain\Policies\{$($gpo.Id)}" +$startup = Join-Path $root 'Machine\Scripts\Startup' +New-Item $startup -ItemType Directory -Force | Out-Null +foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') { + $source = Join-Path $PSScriptRoot $file + $destination = Join-Path $startup $file + if (-not (Test-Path $destination) -or (Get-FileHash $source).Hash -ne (Get-FileHash $destination).Hash) { + Copy-Item $source $destination -Force + $changed = $true + } +} +$scriptPath = "\\$($domain.DNSRoot)\SYSVOL\$($domain.DNSRoot)\Policies\{$($gpo.Id)}\Machine\Scripts\Startup\Install-SguCedWifiMaintenance.ps1" +$clientScriptPath = $scriptPath.Replace('Install-SguCedWifiMaintenance.ps1','Invoke-SguCedClientEnrollment.ps1') +$ini = "[Startup]`r`n0CmdLine=powershell.exe`r`n0Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$scriptPath`"`r`n1CmdLine=powershell.exe`r`n1Parameters=-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$clientScriptPath`" -InstallTask`r`n" +$iniPath = Join-Path $root 'Machine\Scripts\scripts.ini' +if (-not (Test-Path $iniPath) -or (Get-Content $iniPath -Raw) -cne $ini) { + [IO.File]::WriteAllText($iniPath,$ini,[Text.Encoding]::Unicode) + $changed = $true +} +$extension = '[{0ACDD40C-75AC-47AB-BAA0-BF6DE7E7FE63}{2DA6AA7F-8C88-4194-A558-0D36E7FD3E64}]' +$names = [string]$adGpo.gPCMachineExtensionNames +if ($names.IndexOf($extension, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $names += $extension; $changed = $true } +$scriptsExtension = '[{42B5FAAE-6536-11D2-AE5A-0000F87571E3}{40B6664F-4972-11D1-A7CA-0000F87571E3}]' +if ($names.IndexOf($scriptsExtension, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $names += $scriptsExtension; $changed = $true } +if ($changed) { + $names = ([regex]::Matches($names, '\[[^\]]+\]') | ForEach-Object Value | Sort-Object -Unique) -join '' + $v = ([long]$adGpo.versionNumber -band 0xFFFF0000L) -bor (([long]$adGpo.versionNumber + 1) -band 0xFFFFL) + Set-ADObject $gpoDn -Server $DomainController -Replace @{gPCMachineExtensionNames=$names;versionNumber=[int]$v} + [IO.File]::WriteAllText((Join-Path $root 'GPT.INI'), "[General]`r`nVersion=$v`r`n", [Text.Encoding]::ASCII) +} +$link = (Get-GPInheritance -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController).GpoLinks | Where-Object GpoId -eq $gpo.Id +if (-not $link) { New-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } +elseif (-not $link.Enabled) { Set-GPLink -Guid $gpo.Id -Target $TargetOuDn -Domain $domain.DNSRoot -Server $DomainController -LinkEnabled Yes | Out-Null } +[pscustomobject]@{Gpo=$GpoName;Id=$gpo.Id;SSID=$ssid;TargetOu=$TargetOuDn;Computers=$computers.Count;ReaderGroup=$ReaderGroup;Changed=$changed} diff --git a/scripts/Sync-SguCedWifiReaders.ps1 b/scripts/Sync-SguCedWifiReaders.ps1 new file mode 100644 index 0000000..fe4c516 --- /dev/null +++ b/scripts/Sync-SguCedWifiReaders.ps1 @@ -0,0 +1,82 @@ +[CmdletBinding()] +param( + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$DomainController = $env:COMPUTERNAME, + [string]$GpoName = 'CED - Wi-Fi de salas', + [string]$ReaderGroup = 'CED-WiFi-Equipos', + [switch]$InstallRefreshTask +) +$ErrorActionPreference = 'Stop' +Import-Module ActiveDirectory +Import-Module GroupPolicy +$domain = Get-ADDomain -Server $DomainController +Get-ADOrganizationalUnit -Identity $TargetOuDn -Server $DomainController | Out-Null +$group = Get-ADGroup $ReaderGroup -Server $DomainController +if (-not $group.DistinguishedName.EndsWith(",$TargetOuDn",[StringComparison]::OrdinalIgnoreCase)) { throw 'Reader group is outside the target OU.' } +$gpo = Get-GPO -Name $GpoName -Server $DomainController -Domain $domain.DNSRoot +$gpoDn = "CN={$($gpo.Id)},CN=Policies,CN=System,$($domain.DistinguishedName)" +$policyDn = "CN=CED Wi-Fi,CN=IEEE80211,CN=Windows,CN=Microsoft,CN=Machine,$gpoDn" +if ($InstallRefreshTask) { + # SYSTEM authenticates to AD as this DC. Delegate only these specific + # properties; no domain administrator password is stored in a task. + $controllerSid = (Get-ADComputer ($DomainController.Split('.')[0]) -Server $DomainController).SID + $schemaDn = (Get-ADRootDSE -Server $DomainController).schemaNamingContext + foreach ($target in @(@{Dn=$group.DistinguishedName;Attribute='member'},@{Dn=$gpoDn;Attribute='versionNumber'})) { + $attribute = Get-ADObject -SearchBase $schemaDn -LDAPFilter "(lDAPDisplayName=$($target.Attribute))" -Server $DomainController -Properties schemaIDGUID + $entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$($target.Dn)") + try { + $acl = $entry.ObjectSecurity + $acl.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($controllerSid,[DirectoryServices.ActiveDirectoryRights]::WriteProperty,[Security.AccessControl.AccessControlType]::Allow,[guid]::new([byte[]]$attribute.schemaIDGUID))) + $entry.ObjectSecurity=$acl; $entry.CommitChanges() + } finally { $entry.Dispose() } + } + $taskDirectory = 'C:\ProgramData\LCI-Admin\CED-WiFi-Readers' + New-Item $taskDirectory -ItemType Directory -Force | Out-Null + $fileAcl = [Security.AccessControl.DirectorySecurity]::new() + $fileAcl.SetAccessRuleProtection($true,$false) + foreach ($sid in 'S-1-5-18','S-1-5-32-544') { + $fileAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + [Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) + } + Set-Acl $taskDirectory $fileAcl + $taskScript = Join-Path $taskDirectory 'Sync-SguCedWifiReaders.ps1' + if ($PSCommandPath -ine $taskScript) { Copy-Item $PSCommandPath $taskScript -Force } + foreach ($value in $TargetOuDn,$DomainController,$GpoName,$ReaderGroup) { + if ($value.Contains('"')) { throw 'Task parameter contains an unsupported quote.' } + } + $arguments = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "{0}" -TargetOuDn "{1}" -DomainController "{2}" -GpoName "{3}" -ReaderGroup "{4}"' -f $taskScript,$TargetOuDn,$DomainController,$GpoName,$ReaderGroup + $action = New-ScheduledTaskAction -Execute powershell.exe -Argument $arguments + $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 15) + Register-ScheduledTask -TaskName 'CED WiFi OU readers refresh' -Action $action -Trigger $trigger -User SYSTEM -RunLevel Highest -Force | Out-Null +} +$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController) +$members = @(Get-ADGroupMember $group -Server $DomainController) +$add = @($computers | Where-Object DistinguishedName -notin $members.DistinguishedName) +$remove = @($members | Where-Object DistinguishedName -notin $computers.DistinguishedName) +if ($add.Count) { Add-ADGroupMember $group -Members $add -Server $DomainController } +if ($remove.Count) { Remove-ADGroupMember $group -Members $remove -Server $DomainController -Confirm:$false } +$changed = $add.Count -gt 0 -or $remove.Count -gt 0 +$entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$policyDn") +try { + $acl = $entry.ObjectSecurity + $rules = @($acl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier])) + foreach ($rule in $rules) { + if ($rule.ActiveDirectoryRights -eq [DirectoryServices.ActiveDirectoryRights]::GenericRead -and + $rule.IdentityReference.Value -ne $group.SID.Value -and $rule.IdentityReference.Value -notin $computers.SID.Value) { + $acl.RemoveAccessRuleSpecific($rule); $changed=$true + } + } + foreach ($computer in $computers) { + if ($computer.SID.Value -notin $rules.IdentityReference.Value) { + $acl.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow));$changed=$true + } + } + if ($changed) { $entry.ObjectSecurity=$acl; $entry.CommitChanges() } +} finally { $entry.Dispose() } +if ($changed) { + $adGpo=Get-ADObject $gpoDn -Server $DomainController -Properties versionNumber + $version=([long]$adGpo.versionNumber -band 0xFFFF0000L) -bor (([long]$adGpo.versionNumber+1) -band 0xFFFFL) + Set-ADObject $gpoDn -Server $DomainController -Replace @{versionNumber=[int]$version} + [IO.File]::WriteAllText("$env:WINDIR\SYSVOL\domain\Policies\{$($gpo.Id)}\GPT.INI","[General]`r`nVersion=$version`r`n",[Text.Encoding]::ASCII) +} +[pscustomobject]@{TargetOu=$TargetOuDn;Computers=$computers.Count;Added=$add.Count;Removed=$remove.Count;Changed=$changed} diff --git a/scripts/Sync-SguWacDomainConnections.ps1 b/scripts/Sync-SguWacDomainConnections.ps1 index e42fa0f..641f83e 100644 --- a/scripts/Sync-SguWacDomainConnections.ps1 +++ b/scripts/Sync-SguWacDomainConnections.ps1 @@ -3,6 +3,7 @@ param( [Parameter(Mandatory)][uri]$Endpoint, [Parameter(Mandatory)][PSCredential]$Credential, [string]$DomainController = $env:COMPUTERNAME, + [string]$ComputerOuDn = '', [string[]]$VerifyNodes = @() ) $ErrorActionPreference = 'Stop' @@ -54,7 +55,12 @@ $login = Invoke-WebRequest -Uri "$base/api/user/login" -Method Post -WebSession if ($login.StatusCode -ne 200) { throw 'WAC rejected the supplied account.' } $existing = Invoke-RestMethod -Uri "$base/api/connections" -WebSession $webSession -$computers = @(Get-ADComputer -Server $DomainController -Filter 'Enabled -eq $true' -Properties OperatingSystem,DNSHostName | +$search = @{Server=$DomainController; Filter='Enabled -eq $true'; Properties=@('OperatingSystem','DNSHostName')} +if ($ComputerOuDn) { + Get-ADOrganizationalUnit -Identity $ComputerOuDn -Server $DomainController | Out-Null + $search.SearchBase = $ComputerOuDn +} +$computers = @(Get-ADComputer @search | Where-Object { $_.DNSHostName -and $_.OperatingSystem -like 'Windows*' }) $pending = @( foreach ($computer in $computers) { @@ -84,9 +90,14 @@ if ($missing.Count) { throw "WAC inventory verification failed: $($missing.Name foreach ($node in $VerifyNodes) { if ($node -notmatch '^[A-Za-z0-9.-]+$') { throw 'Invalid verification hostname.' } $uri = "$base/api/services/WinREST/CIM/nodes/$node/namespaces/root.cimv2/classes/Win32_OperatingSystem/instances" - $response = Invoke-WebRequest -Uri $uri -WebSession $webSession -UseBasicParsing - $result = $response.Content | ConvertFrom-Json - $instances = @($result.value | Where-Object { $null -ne $_ }) - if (-not $instances.Count) { throw "WAC returned no OS instances for $node." } - [pscustomobject]@{Node=$node;Status=$response.StatusCode;Instances=$instances.Count;ReturnedData=$true} + try { + $response = Invoke-WebRequest -Uri $uri -WebSession $webSession -UseBasicParsing + $result = $response.Content | ConvertFrom-Json + $instances = @($result.value | Where-Object { $null -ne $_ }) + if (-not $instances.Count) { throw "WAC returned no OS instances for $node." } + [pscustomobject]@{Node=$node;Status=$response.StatusCode;Instances=$instances.Count;ReturnedData=$true;Error=$null} + } catch { + # An offline node must not prevent verification of the remaining nodes. + [pscustomobject]@{Node=$node;Status=$null;Instances=0;ReturnedData=$false;Error=$_.Exception.Message} + } } diff --git a/scripts/Test-SguCedManagedNodes.ps1 b/scripts/Test-SguCedManagedNodes.ps1 new file mode 100644 index 0000000..83471bd --- /dev/null +++ b/scripts/Test-SguCedManagedNodes.ps1 @@ -0,0 +1,55 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory)][PSCredential]$Credential, + [string]$TargetOuDn = 'OU=Centro de Experiencia Digital,OU=Laboratorio,DC=lci,DC=lasalle,DC=mx', + [string]$Ssid = 'Centro de Experiencia Digital', + [string]$WacThumbprint = 'CF2B7C6899885BF9EB0E59054F8E8AB2D4390513' +) +$ErrorActionPreference = 'Stop' +Import-Module ActiveDirectory +Clear-DnsClientCache +$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Properties DNSHostName) +$online = @() +foreach ($computer in $computers) { + $client = [Net.Sockets.TcpClient]::new() + try { + $connect = $client.BeginConnect($computer.DNSHostName,5985,$null,$null) + $available = $connect.AsyncWaitHandle.WaitOne(1000) -and $client.Connected + } catch { $available = $false } finally { $client.Dispose() } + if ($available) { $online += $computer.DNSHostName } + else { [pscustomobject]@{Name=$computer.Name;Reachable=$false;WifiConnected=$false;ClientRunning=$false;Error='No WinRM TCP connection at current DNS address.'} } +} +$options = New-PSSessionOption -OpenTimeout 10000 -OperationTimeout 60000 +if ($online.Count) { + $reported = @(Invoke-Command -ComputerName $online -Credential $Credential -Authentication Kerberos -SessionOption $options -ErrorAction Continue -ArgumentList $Ssid,$WacThumbprint -ScriptBlock { + param($ssid,$thumbprint) + $liveSsid = @([Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetConnectionProfiles() | Where-Object IsWlanConnectionProfile | ForEach-Object { $_.WlanConnectionProfileDetails.GetConnectedSsid() }) + $event = Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-WLAN-AutoConfig/Operational';Id=8001} -MaxEvents 1 -ErrorAction SilentlyContinue + $profile = $null; $authentication = $null + if ($event) { + [xml]$xml = $event.ToXml() + $profile = ($xml.Event.EventData.Data | Where-Object Name -eq ProfileName).'#text' + $authentication = ($xml.Event.EventData.Data | Where-Object Name -eq AuthenticationAlgorithm).'#text' + } + $service = Get-Service CcmExec -ErrorAction SilentlyContinue + $version = $null; $site = $null + if ($service.Status -eq 'Running') { + $sms = Get-CimInstance -Namespace root\ccm -ClassName SMS_Client -ErrorAction SilentlyContinue + $version = $sms.ClientVersion + $site = (Invoke-CimMethod -Namespace root\ccm -ClassName SMS_Client -MethodName GetAssignedSite -ErrorAction SilentlyContinue).sSiteCode + } + [pscustomobject]@{ + Name=$env:COMPUTERNAME;Reachable=$true;SSID=$liveSsid -join ',';Profile=$profile + WifiConnected=($liveSsid -contains $ssid -and $profile -eq $ssid) + IP=@(Get-NetIPAddress -AddressFamily IPv4 | Where-Object IPAddress -like '192.168.*' | ForEach-Object IPAddress) -join ',' + Authentication=$authentication;ClientRunning=($service.Status -eq 'Running');ClientVersion=$version;Site=$site + WacRootTrusted=(Test-Path ("Cert:\LocalMachine\Root\"+$thumbprint));Error=$null + } + }) + $reported + foreach ($hostname in $online) { + if ($reported.PSComputerName -inotcontains $hostname) { + [pscustomobject]@{Name=$hostname.Split('.')[0];Reachable=$false;WifiConnected=$false;ClientRunning=$false;Error='WinRM session or client verification failed after TCP probe.'} + } + } +}