Configure CED Wi-Fi policy and scoped management enrollment

This commit is contained in:
alexrg committed 2026-10-01 10:16:24 -06:00
1 parent b07dbe17d0
commit 46c0be732a
14 files changed
+921 -6

No files matched your search

+122
View File
@@ -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;i<count;i++) {
Guid id=(Guid)Marshal.PtrToStructure(IntPtr.Add(list,8+i*532),typeof(Guid));
// GP's CSE can leave a Personal key unprotected. Let Native Wi-Fi
// encrypt it for this machine while retaining the GP profile type.
IntPtr xmlPointer=IntPtr.Zero; uint flags=0, access;
Check(WlanGetProfile(handle,ref id,profile,IntPtr.Zero,out xmlPointer,ref flags,out access));
try {
if(requireGroupPolicy && (flags & 1)==0) throw new InvalidOperationException("The requested profile is not managed by Group Policy.");
string xml=Marshal.PtrToStringUni(xmlPointer);
if((flags & 1)!=0 && xml.Contains("<protected>false</protected>")) {
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
}
+32
View File
@@ -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'
+45
View File
@@ -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.
+100
View File
@@ -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 }
}
}
+44
View File
@@ -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}
+31
View File
@@ -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 }
+29
View File
@@ -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}
+42
View File
@@ -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}
+129
View File
@@ -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 = '<WLANPolicy xmlns="http://www.microsoft.com/networking/WLAN/policy/v1">' +
"<name>$escapedName</name><description>Wi-Fi administrado exclusivamente para la OU CED.</description>" +
'<globalFlags><enableAutoConfig>true</enableAutoConfig><showDeniedNetwork>false</showDeniedNetwork><allowEveryoneToCreateAllUserProfiles>false</allowEveryoneToCreateAllUserProfiles></globalFlags>' +
'<networkFilter><denyAllIBSS>true</denyAllIBSS><denyAllESS>false</denyAllESS></networkFilter>' +
'<profileList>' + $profile.DocumentElement.OuterXml + '</profileList></WLANPolicy>'
$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}
+82
View File
@@ -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}
+17 -6
View File
@@ -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}
}
}
+55
View File
@@ -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.'}
}
}
}