Keep CED workstation Wi-Fi available before sign-in and package release 0.6.22

This commit is contained in:
alexrg committed 2026-10-14 15:48:44 -06:00
1 parent 2cca02db35
commit bfa520dec8
9 files changed
+386 -57

No files matched your search

+108
View File
@@ -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