Keep CED workstation Wi-Fi available before sign-in and package release 0.6.22
This commit is contained in:
1 parent
2cca02db35
commit
bfa520dec8
9 files changed
+386
-57
No files matched your search
@@ -1,32 +1,65 @@
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# Invoked by the CED computer startup policy, after the native WLAN CSE.
|
||||
# Native WLAN AutoConfig holds the machine profile before interactive logon.
|
||||
$computer=Get-CimInstance Win32_ComputerSystem
|
||||
if(-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or $env:COMPUTERNAME -notmatch '^(AF|SD|SI)-'){return}
|
||||
$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'
|
||||
if((Get-Acl -LiteralPath $destination).GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access) -ne $acl.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)){Set-Acl -LiteralPath $destination -AclObject $acl}
|
||||
$source=Join-Path $PSScriptRoot 'Repair-SguCedWifi.ps1'
|
||||
$helper=Join-Path $destination 'Repair-SguCedWifi.ps1'
|
||||
if($source -ine $helper -and (-not(Test-Path -LiteralPath $helper) -or (Get-FileHash -LiteralPath $source).Hash -ne (Get-FileHash -LiteralPath $helper).Hash)){Copy-Item -LiteralPath $source -Destination $helper -Force}
|
||||
$service=Get-Service WlanSvc
|
||||
if($service.StartType -ne 'Automatic'){Set-Service WlanSvc -StartupType Automatic}
|
||||
if($service.Status -ne 'Running'){Start-Service WlanSvc}
|
||||
$subscription='<QueryList><Query Id="0" Path="Microsoft-Windows-GroupPolicy/Operational"><Select Path="Microsoft-Windows-GroupPolicy/Operational">*[System[(EventID=8000 or EventID=8002 or EventID=8004 or EventID=8006)]]</Select></Query><Query Id="1" Path="Microsoft-Windows-TerminalServices-LocalSessionManager/Operational"><Select Path="Microsoft-Windows-TerminalServices-LocalSessionManager/Operational">*[System[EventID=23]]</Select></Query><Query Id="2" Path="Microsoft-Windows-WLAN-AutoConfig/Operational"><Select Path="Microsoft-Windows-WLAN-AutoConfig/Operational">*[System[EventID=8001]]</Select></Query></QueryList>'
|
||||
$subscription=[Security.SecurityElement]::Escape($subscription)
|
||||
$command=[Security.SecurityElement]::Escape("$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe")
|
||||
$arguments=[Security.SecurityElement]::Escape('-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "'+$helper+'"')
|
||||
$taskXml=@"
|
||||
<?xml version="1.0" encoding="UTF-16"?>
|
||||
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||
<RegistrationInfo><Author>La Salle</Author><Description>Computer Wi-Fi recovery after boot, computer policy, logoff or network change. No periodic polling.</Description></RegistrationInfo>
|
||||
<Triggers><BootTrigger><Enabled>true</Enabled><Delay>PT10S</Delay></BootTrigger><EventTrigger><Enabled>true</Enabled><Subscription>$subscription</Subscription><Delay>PT3S</Delay></EventTrigger></Triggers>
|
||||
<Principals><Principal id="System"><UserId>S-1-5-18</UserId><RunLevel>HighestAvailable</RunLevel></Principal></Principals>
|
||||
<Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><StartWhenAvailable>true</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><Enabled>true</Enabled><ExecutionTimeLimit>PT1M</ExecutionTimeLimit></Settings>
|
||||
<Actions Context="System"><Exec><Command>$command</Command><Arguments>$arguments</Arguments></Exec></Actions>
|
||||
</Task>
|
||||
"@
|
||||
$taskName='CED WiFi policy connection'
|
||||
$existing=Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
||||
$versionFile=Join-Path $destination 'maintenance-v2.sha256'
|
||||
$sha=[Security.Cryptography.SHA256]::Create()
|
||||
try{$hash=[BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($taskXml))).Replace('-','')}finally{$sha.Dispose()}
|
||||
$valid=$existing -and $existing.Triggers.Count -eq 2 -and @($existing.Triggers|Where-Object{$_.Repetition.Interval}).Count -eq 0 -and $existing.Principal.UserId -in 'SYSTEM','S-1-5-18' -and (Test-Path -LiteralPath $versionFile) -and (Get-Content -LiteralPath $versionFile -Raw).Trim() -eq $hash
|
||||
if(-not $valid){Register-ScheduledTask -TaskName $taskName -Xml $taskXml -Force|Out-Null;$hash|Set-Content -LiteralPath $versionFile -Encoding ASCII}
|
||||
$profileState=& $helper
|
||||
if(-not $profileState.MachineProfileReady){
|
||||
# Computer authentication reads the existing restricted AD WLAN object.
|
||||
# The PSK stays in memory and Windows encrypts it into its machine store.
|
||||
$searchRoot=$null;$searcher=$null
|
||||
try{
|
||||
# Serverless LDAP can select Azure's private DC address, which these clients
|
||||
# cannot route to. Use the local DC with signed and sealed machine binding.
|
||||
$domainDn=($computer.Domain.Split('.')|ForEach-Object{'DC='+$_}) -join ','
|
||||
$searchRoot=[DirectoryServices.DirectoryEntry]::new('LDAP://192.168.54.211/CN=Policies,CN=System,'+$domainDn)
|
||||
$searchRoot.AuthenticationType=[DirectoryServices.AuthenticationTypes]::Secure -bor [DirectoryServices.AuthenticationTypes]::Signing -bor [DirectoryServices.AuthenticationTypes]::Sealing
|
||||
$searcher=[DirectoryServices.DirectorySearcher]::new($searchRoot)
|
||||
$searcher.Filter='(&(objectClass=ms-net-ieee-80211-GroupPolicy)(cn=CED Wi-Fi))'
|
||||
[void]$searcher.PropertiesToLoad.Add('ms-net-ieee-80211-GP-PolicyData')
|
||||
$found=@($searcher.FindAll())
|
||||
if($found.Count -ne 1){throw 'Expected exactly one authorized CED WLAN policy.'}
|
||||
[xml]$policy=[string]$found[0].Properties['ms-net-ieee-80211-gp-policydata'][0]
|
||||
$profile=$policy.SelectSingleNode('//*[local-name()="WLANProfile"]')
|
||||
$profileState=& $helper -ProvisionXml $profile.OuterXml
|
||||
}finally{if($searcher){$searcher.Dispose()};if($searchRoot){$searchRoot.Dispose()};$profile=$null;$policy=$null}
|
||||
}
|
||||
if(-not $profileState.MachineProfileReady){throw 'Machine Wi-Fi profile is not ready.'}
|
||||
Start-ScheduledTask -TaskName $taskName
|
||||
@@ -91,20 +91,22 @@ $clientRoot = Join-Path $resolvedOutputRoot "sgu-windows-client-bootstrap-$Versi
|
||||
$serverRoot = Join-Path $resolvedOutputRoot "sgu-server-bootstrap-$Version"
|
||||
$linuxClientRoot = Join-Path $resolvedOutputRoot "sgu-linux-client-bootstrap-$Version"
|
||||
$azureRoot = Join-Path $resolvedOutputRoot "sgu-azure-infrastructure-$Version"
|
||||
$wifiRoot = Join-Path $resolvedOutputRoot "sgu-ced-wifi-policy-$Version"
|
||||
$clientZip = "$clientRoot.zip"
|
||||
$serverZip = "$serverRoot.zip"
|
||||
$linuxClientZip = "$linuxClientRoot.zip"
|
||||
$azureZip = "$azureRoot.zip"
|
||||
$wifiZip = "$wifiRoot.zip"
|
||||
foreach ($target in @(
|
||||
$clientRoot,$serverRoot,$linuxClientRoot,$azureRoot,
|
||||
$clientZip,$serverZip,$linuxClientZip,$azureZip)) {
|
||||
$clientRoot,$serverRoot,$linuxClientRoot,$azureRoot,$wifiRoot,
|
||||
$clientZip,$serverZip,$linuxClientZip,$azureZip,$wifiZip)) {
|
||||
if (Test-Path -LiteralPath $target) {
|
||||
throw "Release target already exists: $target"
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory `
|
||||
-Path $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot `
|
||||
-Path $clientRoot,$serverRoot,$linuxClientRoot,$azureRoot,$wifiRoot `
|
||||
-Force | Out-Null
|
||||
$welcomeFontNames = @(
|
||||
'IndivisaTextSans-Regular.otf',
|
||||
@@ -206,6 +208,12 @@ Copy-RequiredFile -Source (Join-Path $PSScriptRoot 'Start-SguServerBootstrap.cmd
|
||||
Copy-RequiredFile -Source (Join-Path $PSScriptRoot 'Start-SguAzureServerBootstrap.cmd') `
|
||||
-Destination (Join-Path $serverRoot 'Start-SguAzureServerBootstrap.cmd')
|
||||
$serverScripts = @(
|
||||
'Set-SguCedWifiPolicy.ps1',
|
||||
'Install-SguCedWifiMaintenance.ps1',
|
||||
'Repair-SguCedWifi.ps1',
|
||||
'Sync-SguCedWifiReaders.ps1',
|
||||
'Connect-SguCedWifi.ps1',
|
||||
'Invoke-SguCedClientEnrollment.ps1',
|
||||
'Deploy-AuthBroker.ps1',
|
||||
'Disable-SguAzureUserRoaming.ps1',
|
||||
'Enable-SguAzureUserRoaming.ps1',
|
||||
@@ -298,11 +306,31 @@ Write-PackageManifest -PackageRoot $azureRoot -PackageVersion $Version -PackageK
|
||||
Compress-Archive -Path (Join-Path $azureRoot '*') -DestinationPath $azureZip `
|
||||
-CompressionLevel Optimal
|
||||
|
||||
# Existing domains can publish the WLAN correction without running forest setup.
|
||||
foreach ($scriptName in @(
|
||||
'Set-SguCedWifiPolicy.ps1',
|
||||
'Install-SguCedWifiMaintenance.ps1',
|
||||
'Repair-SguCedWifi.ps1',
|
||||
'Sync-SguCedWifiReaders.ps1',
|
||||
'Connect-SguCedWifi.ps1',
|
||||
'Invoke-SguCedClientEnrollment.ps1')) {
|
||||
Copy-RequiredFile -Source (Join-Path $PSScriptRoot $scriptName) `
|
||||
-Destination (Join-Path $wifiRoot $scriptName)
|
||||
}
|
||||
Copy-RequiredFile -Source (Join-Path $repositoryRoot 'docs\ced-wifi-release.md') `
|
||||
-Destination (Join-Path $wifiRoot 'README.md')
|
||||
Copy-RequiredFile -Source (Join-Path $repositoryRoot 'docs\ced-network-operations.md') `
|
||||
-Destination (Join-Path $wifiRoot 'ced-network-operations.md')
|
||||
Write-PackageManifest -PackageRoot $wifiRoot -PackageVersion $Version -PackageKind CedWifiPolicy
|
||||
Compress-Archive -Path (Join-Path $wifiRoot '*') -DestinationPath $wifiZip `
|
||||
-CompressionLevel Optimal
|
||||
|
||||
$checksums = @(
|
||||
("{0} {1}" -f (Get-FileHash -LiteralPath $clientZip -Algorithm SHA256).Hash, (Split-Path $clientZip -Leaf))
|
||||
("{0} {1}" -f (Get-FileHash -LiteralPath $serverZip -Algorithm SHA256).Hash, (Split-Path $serverZip -Leaf))
|
||||
("{0} {1}" -f (Get-FileHash -LiteralPath $linuxClientZip -Algorithm SHA256).Hash, (Split-Path $linuxClientZip -Leaf))
|
||||
("{0} {1}" -f (Get-FileHash -LiteralPath $azureZip -Algorithm SHA256).Hash, (Split-Path $azureZip -Leaf))
|
||||
("{0} {1}" -f (Get-FileHash -LiteralPath $wifiZip -Algorithm SHA256).Hash, (Split-Path $wifiZip -Leaf))
|
||||
)
|
||||
$checksumsPath = Join-Path $resolvedOutputRoot "SHA256SUMS-$Version.txt"
|
||||
[IO.File]::WriteAllLines($checksumsPath, $checksums, [Text.UTF8Encoding]::new($false))
|
||||
@@ -317,6 +345,8 @@ $checksumsPath = Join-Path $resolvedOutputRoot "SHA256SUMS-$Version.txt"
|
||||
ServerSha256 = (Get-FileHash -LiteralPath $serverZip -Algorithm SHA256).Hash
|
||||
AzureInfrastructurePackage = $azureZip
|
||||
AzureInfrastructureSha256 = (Get-FileHash -LiteralPath $azureZip -Algorithm SHA256).Hash
|
||||
CedWifiPolicyPackage = $wifiZip
|
||||
CedWifiPolicySha256 = (Get-FileHash -LiteralPath $wifiZip -Algorithm SHA256).Hash
|
||||
Checksums = $checksumsPath
|
||||
RuntimeInstaller = $runtimeInstaller.Name
|
||||
}
|
||||
@@ -23,6 +23,7 @@ $assetPaths = @(
|
||||
(Join-Path $ReleaseDirectory "sgu-server-bootstrap-$Version.zip"),
|
||||
(Join-Path $ReleaseDirectory "sgu-linux-client-bootstrap-$Version.zip"),
|
||||
(Join-Path $ReleaseDirectory "sgu-azure-infrastructure-$Version.zip"),
|
||||
(Join-Path $ReleaseDirectory "sgu-ced-wifi-policy-$Version.zip"),
|
||||
(Join-Path $ReleaseDirectory "SHA256SUMS-$Version.txt")
|
||||
)
|
||||
foreach ($assetPath in $assetPaths) {
|
||||
@@ -143,7 +144,8 @@ Las contraseñas se solicitan de forma interactiva y no se escriben en archivos
|
||||
target_commitish = $TargetCommitish
|
||||
name = "SGU Credential Provider $Version"
|
||||
body = $releaseNotes
|
||||
draft = [bool]$Draft
|
||||
# Keep the release private until every attachment has uploaded.
|
||||
draft = $true
|
||||
prerelease = $Version -match '-'
|
||||
}
|
||||
|
||||
@@ -175,6 +177,11 @@ Las contraseñas se solicitan de forma interactiva y no se escriben en archivos
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $Draft) {
|
||||
$release = Invoke-GiteaJson -Method ([Net.Http.HttpMethod]::Patch) `
|
||||
-RelativeUri "$repositoryPath/releases/$($release.id)" -Body @{draft=$false}
|
||||
}
|
||||
|
||||
[pscustomobject]@{
|
||||
Tag = $tagName
|
||||
ReleaseName = $release.name
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
[CmdletBinding()]
|
||||
param([switch]$PreferCedNow,[string]$ProvisionXml='')
|
||||
$ErrorActionPreference='Stop'
|
||||
$computer=Get-CimInstance Win32_ComputerSystem
|
||||
if(-not $computer.PartOfDomain -or $computer.DomainRole -ne 1 -or $env:COMPUTERNAME -notmatch '^(AF|SD|SI)-'){return}
|
||||
$destination='C:\ProgramData\LCI-Admin\CED-WiFi'
|
||||
if(-not ('Sgu.CedMachineWifi' -as [type])){
|
||||
Add-Type -ReferencedAssemblies System.dll,System.Xml.dll -TypeDefinition @'
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
namespace Sgu {
|
||||
public class CedWifiResult { public string Interface; public string Ssid; public string Profile; public bool MachineProfileReady; public bool GroupProfileRepaired; public bool MachineProfileCreated; public int OtherProfilesMadeManual; public bool ConnectionRequested; public uint QueryError; }
|
||||
public static class CedMachineWifi {
|
||||
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] struct Connection { public int Mode; [MarshalAs(UnmanagedType.LPWStr)] public string Profile; public IntPtr Ssid; public IntPtr Bssids; public int BssType; public uint Flags; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct Session { public int Id; public IntPtr Name; public int State; }
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanOpenHandle(uint v,IntPtr r,out uint n,out IntPtr h);
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanEnumInterfaces(IntPtr h,IntPtr r,out IntPtr p);
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanGetProfileList(IntPtr h,ref Guid i,IntPtr r,out IntPtr p);
|
||||
[DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanGetProfile(IntPtr h,ref Guid i,string name,IntPtr r,out IntPtr xml,ref uint flags,out uint access);
|
||||
[DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanSetProfile(IntPtr h,ref Guid i,uint flags,string xml,string security,[MarshalAs(UnmanagedType.Bool)]bool overwrite,IntPtr r,out uint reason);
|
||||
[DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanSetProfilePosition(IntPtr h,ref Guid i,string name,uint position,IntPtr r);
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanQueryInterface(IntPtr h,ref Guid i,int opcode,IntPtr r,out uint size,out IntPtr data,out int type);
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanSetInterface(IntPtr h,ref Guid i,int opcode,uint size,ref int data,IntPtr r);
|
||||
[DllImport("wlanapi.dll",CharSet=CharSet.Unicode)] static extern uint WlanConnect(IntPtr h,ref Guid i,ref Connection c,IntPtr r);
|
||||
[DllImport("wlanapi.dll")] static extern uint WlanCloseHandle(IntPtr h,IntPtr r);
|
||||
[DllImport("wlanapi.dll")] static extern void WlanFreeMemory(IntPtr p);
|
||||
[DllImport("wtsapi32.dll",CharSet=CharSet.Unicode,SetLastError=true)] static extern bool WTSEnumerateSessions(IntPtr h,int reserved,int version,out IntPtr list,out int count);
|
||||
[DllImport("wtsapi32.dll",CharSet=CharSet.Unicode)] static extern bool WTSQuerySessionInformation(IntPtr h,int id,int type,out IntPtr data,out int bytes);
|
||||
[DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr p);
|
||||
static void Check(uint e){if(e!=0)throw new System.ComponentModel.Win32Exception((int)e);}
|
||||
static XmlDocument Read(IntPtr h,ref Guid id,string name,out uint flags){IntPtr p=IntPtr.Zero;uint access;flags=0;uint e=WlanGetProfile(h,ref id,name,IntPtr.Zero,out p,ref flags,out access);if(e!=0)return null;try{var x=new XmlDocument();x.LoadXml(Marshal.PtrToStringUni(p));return x;}finally{WlanFreeMemory(p);}}
|
||||
static string Text(XmlDocument x,string name){XmlNode n=x.SelectSingleNode("//*[local-name()='"+name+"']");return n==null?"":n.InnerText;}
|
||||
static bool Auto(XmlDocument x){bool changed=false;XmlElement root=x.DocumentElement;XmlNode mode=root.SelectSingleNode("*[local-name()='connectionMode']");if(mode==null)throw new InvalidOperationException("Missing connection mode.");if(mode.InnerText!="auto"){mode.InnerText="auto";changed=true;}XmlNode sw=root.SelectSingleNode("*[local-name()='autoSwitch']");if(sw==null){sw=x.CreateElement("autoSwitch",root.NamespaceURI);root.InsertAfter(sw,mode);changed=true;}if(sw.InnerText!="false"){sw.InnerText="false";changed=true;}return changed;}
|
||||
static void Save(IntPtr h,ref Guid id,uint flags,XmlDocument x){uint reason;uint e=WlanSetProfile(h,ref id,flags,x.OuterXml,null,true,IntPtr.Zero,out reason);if(e!=0)throw new InvalidOperationException("Cannot save WLAN profile: "+e+", reason="+reason);}
|
||||
static void Connected(IntPtr h,ref Guid id,CedWifiResult result){IntPtr p=IntPtr.Zero;uint size;int type;uint e=WlanQueryInterface(h,ref id,7,IntPtr.Zero,out size,out p,out type);result.QueryError=e;try{if(e==0&&size>=556){result.Profile=Marshal.PtrToStringUni(IntPtr.Add(p,8));int len=Marshal.ReadInt32(p,520);if(len>=0&&len<=32){byte[] ssid=new byte[len];Marshal.Copy(IntPtr.Add(p,524),ssid,0,len);result.Ssid=Encoding.UTF8.GetString(ssid);}}}finally{if(p!=IntPtr.Zero)WlanFreeMemory(p);}}
|
||||
static void Connect(IntPtr h,ref Guid id,string name){Connection c=new Connection{Mode=0,Profile=name,BssType=1};Check(WlanConnect(h,ref id,ref c,IntPtr.Zero));}
|
||||
public static int UserSessions(){IntPtr list=IntPtr.Zero;int count,result=0;if(!WTSEnumerateSessions(IntPtr.Zero,0,1,out list,out count))throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());try{int size=Marshal.SizeOf(typeof(Session));for(int i=0;i<count;i++){Session s=(Session)Marshal.PtrToStructure(IntPtr.Add(list,i*size),typeof(Session));IntPtr p=IntPtr.Zero;int bytes;try{if(WTSQuerySessionInformation(IntPtr.Zero,s.Id,5,out p,out bytes)&&bytes>2&&!String.IsNullOrEmpty(Marshal.PtrToStringUni(p)))result++;}finally{if(p!=IntPtr.Zero)WTSFreeMemory(p);}}}finally{WTSFreeMemory(list);}return result;}
|
||||
public static CedWifiResult[] Ensure(string provision,bool prefer,bool rollback,string prior,IDictionary facts){
|
||||
const string ssid="Centro de Experiencia Digital", backup="CED - Equipo";IntPtr h=IntPtr.Zero,list=IntPtr.Zero;uint v;var results=new List<CedWifiResult>();Check(WlanOpenHandle(2,IntPtr.Zero,out v,out h));
|
||||
try{Check(WlanEnumInterfaces(h,IntPtr.Zero,out list));int count=Marshal.ReadInt32(list);for(int i=0;i<count;i++){Guid id=(Guid)Marshal.PtrToStructure(IntPtr.Add(list,8+i*532),typeof(Guid));var r=new CedWifiResult{Interface=id.ToString()};Connected(h,ref id,r);int interfaceState=Marshal.ReadInt32(list,8+i*532+528);if(r.QueryError==5&&interfaceState==1&&facts!=null&&facts.Contains(id.ToString())){string[] row=facts[id.ToString()] as string[];if(row!=null&&row.Length==2){r.Profile=row[0];r.Ssid=row[1];}}
|
||||
if(rollback){if(!String.IsNullOrEmpty(prior))Connect(h,ref id,prior);results.Add(r);continue;}
|
||||
IntPtr autoData=IntPtr.Zero;uint autoSize;int autoType;try{Check(WlanQueryInterface(h,ref id,1,IntPtr.Zero,out autoSize,out autoData,out autoType));if(Marshal.ReadInt32(autoData)==0){int enabled=1;Check(WlanSetInterface(h,ref id,1,4,ref enabled,IntPtr.Zero));}}finally{if(autoData!=IntPtr.Zero)WlanFreeMemory(autoData);}
|
||||
uint gpFlags;XmlDocument gp=Read(h,ref id,ssid,out gpFlags);
|
||||
if(gp!=null&&(gpFlags&2)==0){bool changed=Auto(gp);if(Text(gp,"protected")=="false")changed=true;if(changed){Save(h,ref id,gpFlags,gp);r.GroupProfileRepaired=true;gp=Read(h,ref id,ssid,out gpFlags);}}
|
||||
uint flags;XmlDocument machine=Read(h,ref id,backup,out flags);
|
||||
if(machine==null){XmlDocument source=null;if(!String.IsNullOrEmpty(provision)){source=new XmlDocument();source.LoadXml(provision);}else if(gp!=null)source=(XmlDocument)gp.CloneNode(true);
|
||||
if(source!=null){if(Text(source,"authentication")!="WPA2PSK"&&Text(source,"authentication")!="WPA3SAE")throw new InvalidOperationException("Expected Personal Wi-Fi profile.");XmlNode ssidNode=source.SelectSingleNode("//*[local-name()='SSID']/*[local-name()='name']");if(ssidNode==null||ssidNode.InnerText!=ssid)throw new InvalidOperationException("Unexpected SSID.");source.DocumentElement.SelectSingleNode("*[local-name()='name']").InnerText=backup;Auto(source);Save(h,ref id,0,source);r.MachineProfileCreated=true;machine=Read(h,ref id,backup,out flags);}
|
||||
}else if(Auto(machine)){Save(h,ref id,flags,machine);machine=Read(h,ref id,backup,out flags);}
|
||||
r.MachineProfileReady=machine!=null&&(flags&2)==0&&Text(machine,"protected")=="true"&&Text(machine,"connectionMode")=="auto";
|
||||
if(r.MachineProfileReady){IntPtr profiles=IntPtr.Zero;try{Check(WlanGetProfileList(h,ref id,IntPtr.Zero,out profiles));int n=Marshal.ReadInt32(profiles),gpCount=0,backupPosition=-1;for(int p=0;p<n;p++){IntPtr item=IntPtr.Add(profiles,8+p*516);string name=Marshal.PtrToStringUni(item);if((Marshal.ReadInt32(item,512)&1)!=0)gpCount++;if(name==backup)backupPosition=p;uint f;XmlDocument other=Read(h,ref id,name,out f);if(other==null||f!=0)continue;XmlNode sn=other.SelectSingleNode("//*[local-name()='SSID']/*[local-name()='name']");XmlNode mode=other.DocumentElement.SelectSingleNode("*[local-name()='connectionMode']");if(sn!=null&&sn.InnerText!=ssid&&mode!=null&&mode.InnerText=="auto"){mode.InnerText="manual";Save(h,ref id,f,other);r.OtherProfilesMadeManual++;}}if(backupPosition!=gpCount)Check(WlanSetProfilePosition(h,ref id,backup,(uint)gpCount,IntPtr.Zero));}finally{if(profiles!=IntPtr.Zero)WlanFreeMemory(profiles);}
|
||||
if((prefer&&r.Ssid!=ssid)||(String.IsNullOrEmpty(r.Ssid)&&r.QueryError==5023)){Connect(h,ref id,backup);r.ConnectionRequested=true;}
|
||||
}
|
||||
results.Add(r);
|
||||
}}finally{if(list!=IntPtr.Zero)WlanFreeMemory(list);WlanCloseHandle(h,IntPtr.Zero);}return results.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
function Get-CedConnectionFacts {
|
||||
$facts=@{};$events=@()
|
||||
try{$events=@(Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-WLAN-AutoConfig/Operational';Id=8001,8003} -MaxEvents 64 -ErrorAction Stop)}catch{}
|
||||
foreach($event in $events){
|
||||
[xml]$xml=$event.ToXml();$data=$xml.Event.EventData.Data
|
||||
$interface=[string]($data|Where-Object Name -eq InterfaceGuid).'#text'
|
||||
if(-not $interface){continue};$key=([guid]$interface).ToString()
|
||||
if($facts.ContainsKey($key)){continue}
|
||||
if($event.Id -eq 8001){$facts[$key]=[string[]]@([string]($data|Where-Object Name -eq ProfileName).'#text',[string]($data|Where-Object Name -eq SSID).'#text')}else{$facts[$key]=[string[]]@('','')}
|
||||
}
|
||||
return ,$facts
|
||||
}
|
||||
$before=@([Sgu.CedMachineWifi]::Ensure($ProvisionXml,[bool]$PreferCedNow,$false,'',(Get-CedConnectionFacts)))
|
||||
$ProvisionXml=$null
|
||||
$requested=@($before|Where-Object ConnectionRequested).Count -gt 0
|
||||
$rolledBack=$false
|
||||
if($requested){
|
||||
for($attempt=0;$attempt -lt 10;$attempt++){
|
||||
Start-Sleep -Seconds 2
|
||||
$state=@([Sgu.CedMachineWifi]::Ensure('',$false,$false,'',(Get-CedConnectionFacts)))
|
||||
if($state.Ssid -contains 'Centro de Experiencia Digital'){break}
|
||||
}
|
||||
if($PreferCedNow -and $state.Ssid -notcontains 'Centro de Experiencia Digital'){
|
||||
foreach($prior in $before|Where-Object Profile){[void][Sgu.CedMachineWifi]::Ensure('',$false,$true,$prior.Profile,(Get-CedConnectionFacts))}
|
||||
$rolledBack=$true
|
||||
}
|
||||
}else{$state=$before}
|
||||
foreach($r in $state){
|
||||
$adapter=Get-NetAdapter|Where-Object{[guid]$_.InterfaceGuid -eq [guid]$r.Interface}
|
||||
if(-not $adapter -or -not $r.Ssid){continue}
|
||||
if($r.Ssid -eq 'Centro de Experiencia Digital'){
|
||||
$desired=@('192.168.54.211','192.168.54.1')
|
||||
$actual=@((Get-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4).ServerAddresses)
|
||||
if(($actual -join ',') -ne ($desired -join ',')){Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $desired}
|
||||
}else{
|
||||
# Emergency Wi-Fi must obtain its own DNS; the internal domain NRPT stays intact.
|
||||
$localKey='HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\'+([guid]$adapter.InterfaceGuid).ToString('B')
|
||||
$manual=(Get-ItemProperty -LiteralPath $localKey -Name NameServer -ErrorAction SilentlyContinue).NameServer
|
||||
if($manual){Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ResetServerAddresses}
|
||||
}
|
||||
}
|
||||
if($requested -and -not $rolledBack){Register-DnsClient -ErrorAction SilentlyContinue}
|
||||
$result=[pscustomobject]@{Utc=[DateTime]::UtcNow.ToString('o');Computer=[string]$env:COMPUTERNAME;Identity=[string][Security.Principal.WindowsIdentity]::GetCurrent().Name;UserSessions=[Sgu.CedMachineWifi]::UserSessions();MachineProfileReady=(@($state|Where-Object MachineProfileReady).Count -gt 0);ConnectedToCed=($state.Ssid -contains 'Centro de Experiencia Digital');RolledBack=$rolledBack;Interfaces=@($state|Select-Object Interface,Ssid,Profile,MachineProfileReady,GroupProfileRepaired,MachineProfileCreated,OtherProfilesMadeManual,ConnectionRequested,QueryError);PeriodicPolling=$false}
|
||||
if(Test-Path -LiteralPath $destination){$result|ConvertTo-Json -Depth 5|Set-Content -LiteralPath(Join-Path $destination 'machine-wifi-status.json') -Encoding UTF8}
|
||||
$result
|
||||
@@ -1,13 +1,14 @@
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(DefaultParameterSetName='File')]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$ProfilePath,
|
||||
[Parameter(Mandatory,ParameterSetName='File')][string]$ProfilePath,
|
||||
[Parameter(Mandatory,ParameterSetName='Xml')][xml]$ProfileDocument,
|
||||
[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') {
|
||||
foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-SguCedWifi.ps1','Invoke-SguCedClientEnrollment.ps1') {
|
||||
if (-not (Test-Path (Join-Path $PSScriptRoot $file))) { throw "Deploy the complete script set; missing $file." }
|
||||
}
|
||||
Import-Module ActiveDirectory
|
||||
@@ -15,7 +16,7 @@ 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
|
||||
[xml]$profile = if($PSCmdlet.ParameterSetName -eq 'Xml'){$ProfileDocument.Clone()}else{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
|
||||
@@ -33,12 +34,15 @@ if ($keyType -eq 'networkKey') {
|
||||
} 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'
|
||||
$switch=$profile.SelectSingleNode('/w:WLANProfile/w:autoSwitch',$ns)
|
||||
if(-not $switch){$switch=$profile.CreateElement('autoSwitch',$profile.DocumentElement.NamespaceURI);[void]$profile.DocumentElement.InsertAfter($switch,$profile.SelectSingleNode('/w:WLANProfile/w:connectionMode',$ns))}
|
||||
$switch.InnerText='false'
|
||||
$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)
|
||||
$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController | Where-Object Name -match '^(AF|SD|SI)-')
|
||||
$members = @(Get-ADGroupMember $group -Server $DomainController)
|
||||
$add = @($computers | Where-Object { $_.DistinguishedName -notin $members.DistinguishedName })
|
||||
$remove = @($members | Where-Object { $_.DistinguishedName -notin $computers.DistinguishedName })
|
||||
@@ -60,7 +64,7 @@ $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>' +
|
||||
'<globalFlags><enableAutoConfig>true</enableAutoConfig><showDeniedNetwork>false</showDeniedNetwork><allowEveryoneToCreateAllUserProfiles>true</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
|
||||
@@ -76,6 +80,7 @@ if (-not $policy) {
|
||||
$entry = [DirectoryServices.DirectoryEntry]::new("LDAP://$DomainController/$policyDn")
|
||||
try {
|
||||
$security = $entry.ObjectSecurity
|
||||
$beforeSecurity=$security.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)
|
||||
$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
|
||||
@@ -88,15 +93,14 @@ try {
|
||||
foreach ($computer in $computers) {
|
||||
$security.AddAccessRule([DirectoryServices.ActiveDirectoryAccessRule]::new($computer.SID,[DirectoryServices.ActiveDirectoryRights]::GenericRead,[Security.AccessControl.AccessControlType]::Allow))
|
||||
}
|
||||
$entry.ObjectSecurity = $security
|
||||
$entry.CommitChanges()
|
||||
if($beforeSecurity -ne $security.GetSecurityDescriptorSddlForm([Security.AccessControl.AccessControlSections]::Access)){$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') {
|
||||
foreach ($file in 'Install-SguCedWifiMaintenance.ps1','Connect-SguCedWifi.ps1','Repair-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) {
|
||||
@@ -126,4 +130,26 @@ if ($changed) {
|
||||
$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 }
|
||||
$filterName='CED - Wi-Fi AF SD SI'
|
||||
$query="SELECT * FROM Win32_ComputerSystem WHERE DomainRole = 1 AND (Name LIKE 'AF-%' OR Name LIKE 'SD-%' OR Name LIKE 'SI-%')"
|
||||
$encodedQuery="1;3;10;$($query.Length);WQL;root\CIMv2;$query;"
|
||||
$filter=@(Get-ADObject -SearchBase "CN=SOM,CN=WMIPolicy,CN=System,$($domain.DistinguishedName)" -LDAPFilter '(objectClass=msWMI-Som)' -Server $DomainController -Properties msWMI-Name,msWMI-ID,msWMI-Parm2|Where-Object {$_.'msWMI-Name' -eq $filterName})
|
||||
if($filter.Count -gt 1){throw 'Duplicate CED wireless WMI filters.'}
|
||||
if(-not $filter.Count){
|
||||
$id=([guid]::NewGuid()).ToString('B').ToUpperInvariant();$timestamp=[DateTime]::UtcNow.ToString('yyyyMMddHHmmss.ffffff-000')
|
||||
$created=New-ADObject -Name $id -Type msWMI-Som -Path "CN=SOM,CN=WMIPolicy,CN=System,$($domain.DistinguishedName)" -Server $DomainController -OtherAttributes @{'msWMI-Name'=$filterName;'msWMI-ID'=$id;'msWMI-Parm1'='Wi-Fi clients AF, SD and SI only; excludes APPS and all servers.';'msWMI-Parm2'=$encodedQuery;'msWMI-Author'='La Salle';'msWMI-CreationDate'=$timestamp;'msWMI-ChangeDate'=$timestamp} -PassThru
|
||||
$filter=@(Get-ADObject -Identity $created.DistinguishedName -Server $DomainController -Properties msWMI-ID,msWMI-Parm2)
|
||||
}elseif($filter[0].'msWMI-Parm2' -ne $encodedQuery){throw 'CED wireless WMI query differs; inspect before modifying.'}
|
||||
$reference="[$($domain.DNSRoot);$($filter[0].'msWMI-ID');0]"
|
||||
$current=Get-ADObject -Identity $gpoDn -Server $DomainController -Properties gPCWQLFilter
|
||||
if($current.gPCWQLFilter -ne $reference){Set-ADObject -Identity $gpoDn -Server $DomainController -Replace @{gPCWQLFilter=$reference};$changed=$true}
|
||||
foreach($setting in @(
|
||||
@{Key='HKLM\Software\Policies\Microsoft\Windows\System';Name='DontDisplayNetworkSelectionUI';Value=0},
|
||||
@{Key='HKLM\Software\Policies\Microsoft\Windows\WcmSvc\GroupPolicy';Name='fBlockNonDomain';Value=0},
|
||||
@{Key='HKLM\SYSTEM\CurrentControlSet\Services\WlanSvc';Name='Start';Value=2},
|
||||
@{Key='HKLM\Software\Policies\LaSalle\CEDWifi';Name='ConfigurationVersion';Value=2}
|
||||
)){
|
||||
$old=Get-GPRegistryValue -Guid $gpo.Id -Server $DomainController -Key $setting.Key -ValueName $setting.Name -ErrorAction SilentlyContinue
|
||||
if(-not $old -or [string]$old.Value -ne [string]$setting.Value){Set-GPRegistryValue -Guid $gpo.Id -Server $DomainController -Key $setting.Key -ValueName $setting.Name -Type DWord -Value $setting.Value|Out-Null;$changed=$true}
|
||||
}
|
||||
[pscustomobject]@{Gpo=$GpoName;Id=$gpo.Id;SSID=$ssid;TargetOu=$TargetOuDn;Computers=$computers.Count;ReaderGroup=$ReaderGroup;Changed=$changed}
|
||||
@@ -49,7 +49,7 @@ if ($InstallRefreshTask) {
|
||||
$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)
|
||||
$computers = @(Get-ADComputer -SearchBase $TargetOuDn -Filter 'Enabled -eq $true' -Server $DomainController | Where-Object Name -match '^(AF|SD|SI)-')
|
||||
$members = @(Get-ADGroupMember $group -Server $DomainController)
|
||||
$add = @($computers | Where-Object DistinguishedName -notin $members.DistinguishedName)
|
||||
$remove = @($members | Where-Object DistinguishedName -notin $computers.DistinguishedName)
|
||||
|
||||
Reference in new issue
Block a user