Advertisement
Guest User

Untitled

a guest
May 23rd, 2025
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.50 KB | None | 0 0
  1. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $ErrorActionPreference = 'Stop'; $WarningPreference = 'SilentlyContinue'; $ConfirmPreference = 'None'; $ProgressPreference = 'SilentlyContinue'; ${A1_Agent_Exe_Path}="C:\Windows\Action1\action1_agent.exe"; ${A1_Agent}="$true"; ${A1_OutProc}="$true"; { try { $output = "" | Select-Object User, 'CPU Model', 'CPU Size', RAM, Disk, Video, NIC, WiFi, 'Motherboard Vendor', 'BIOS Serial', 'Reboot Required', 'CPU Name', 'CPU Data Width', 'CPU Manufacturer', 'CPU Status', 'CPU Error Description',
  2. 'Motherboard Product', 'Motherboard Version', 'Motherboard Tag', 'System Manufacturer', 'System Model', 'System Type', 'BIOS Manufacturer', 'SMBIOS BIOS Version', 'BIOS Software Element State', 'BIOS Version', 'RAM Type', 'Last Boot Time', OU, 'AD Security Groups', A1_Key;
  3.  
  4. #
  5. #Options
  6. #
  7.  
  8. #systemInfoBootTime = true: read LastBootUpTime from systeminfo; false: read the timestamp of the newest 6005 event.
  9. $systemInfoBootUpTime = $true;
  10.  
  11. #
  12. # CPU Info
  13. #
  14. try {
  15. $proc = (Get-WmiObject Win32_Processor)
  16. $proc0 = if ( $proc -is [array] ) { $proc[0] } else { $proc; }
  17. $cpu_count = if ( $proc -is [array] ) { $proc.count } else { 1; }
  18. $output.'CPU Name' = $proc0.Name;
  19. $output.'CPU Model' = $($proc0.Caption);
  20. $output.'CPU Data Width' = $($proc0.DataWidth);
  21. $CPUSpeed = [math]::Round($proc0.MaxClockSpeed / 1000 + 0.005, 2); # the above rounds up to 0.01
  22. $output.'CPU Size' = "$($cpu_count)x$CPUSpeed GHz, $($proc0.NumberOfCores)/$($proc0.NumberOfLogicalProcessors) Cores"
  23. $output.'CPU Manufacturer' = $proc0.Manufacturer;
  24. $output.'CPU Status' = switch ($proc0.CPUStatus) {
  25. 1 { 'CPU Enabled' } 2 { 'CPU Disabled by User via BIOS Setup' } 3 { 'CPU Disabled By BIOS (POST Error)' } 4 { 'CPU is Idle' } 5 { 'Reserved' } 6 { 'Reserved' } 7 { 'Other' } default { 'Unknown' }
  26. }
  27. $output.'CPU Error Description' = $proc0.ErrorDescription;
  28. }
  29. catch {}
  30.  
  31. #
  32. # RAM Info
  33. #
  34. try {
  35. $ram = Get-WmiObject Win32_PhysicalMemory;
  36. $total_RAM_size = [Int64]0;
  37. $ram.Capacity | ForEach-Object { $total_RAM_size += [Int64]$_ };
  38. $rounding = if ( $total_RAM_size -lt 1Gb ) { 2 } else { 0 };
  39. $RAMSize = [math]::Round($total_RAM_size / 1Gb, $rounding);
  40. $ram0 = if ( $ram -is [array] ) { $ram[0] } else { $ram };
  41. $RAMType = switch ($ram0.SMBIOSMemoryType) {
  42. 1 { 'Other' } 2 { 'DRAM' } 3 { 'Synch DRAM' } 4 { 'Cache DRAM' } 5 { 'EDO' } 6 { 'EDRAM' } 7 { 'VRAM' } 8 { 'SRAM' } 9 { 'RAM' } 10 { 'ROM' } 11 { 'Flash' } 12 { 'EEPROM' }
  43. 13 { 'FEPROM' } 14 { 'EPROM' } 15 { 'CDRAM' } 16 { '3DRAM' } 17 { 'SDRAM' } 18 { 'SGRAM' } 19 { 'RDRAM' } 20 { 'DDR' } 21 { 'DDR2' } 22 { 'DDR2 FB-DIMM' } 24 { 'DDR3' }
  44. 25 { 'FBD2' } 26 { 'DDR4' } default { 'Unknown' }
  45. }
  46. $output.RAM = "$($RAMSize)Gb $RAMType"
  47.  
  48. $RAMFormFactorList = @{};
  49. $ram | ForEach-Object {
  50. $RAMType = switch ($_.FormFactor) {
  51. 1 { 'Other' } 2 { 'SIP' } 3 { 'DIP' } 4 { 'ZIP' } 5 { 'SOJ' } 6 { 'Proprietary' } 7 { 'SIMM' } 8 { 'DIMM' } 9 { 'TSOP' } 10 { 'PGA' } 11 { 'RIMM' } 12 { 'SODIMM' }
  52. 13 { 'SRIMM' } 14 { 'SMD' } 15 { 'SSMP' } 16 { 'QFP' } 17 { 'TQFP' } 18 { 'SOIC' } 19 { 'LCC' } 20 { 'PLCC' } 21 { 'BGA' } 22 { 'FPBGA' } 23 { 'LGA' } default { 'Unknown' }
  53. }
  54.  
  55. if ($RAMFormFactorList.$RAMType) {
  56. $RAMFormFactorList.$RAMType = $RAMFormFactorList.$RAMType + 1;
  57. }
  58. else {
  59. $RAMFormFactorList.add( $RAMType, 1 );
  60. }
  61. }
  62. $output.'RAM Type' = ($RAMFormFactorList.keys | ForEach-Object {
  63. Write-Output "$($_) x $([int]$RAMFormFactorList.$_)";
  64. }) -join ', ';
  65. if (!$output.'RAM Type') {
  66. $output.'RAM Type' = 'Unknown';
  67. }
  68. }
  69. catch {}
  70.  
  71. #
  72. # Disk Info
  73. #
  74. try {
  75. function getRoundingRange ([UInt64]$size) {
  76. $rounding = if ( $_.Size -lt 1Gb ) { 2 } else { 0 };
  77. return $rounding;
  78. }
  79.  
  80. try {
  81. $disks = Get-WmiObject MSFT_PhysicalDisk -Namespace "root/microsoft/windows/storage" -Filter "BusType <> '7' and BusType <> '12' and BusType <> '13'" -ErrorAction Stop | Sort-Object -Property __PATH
  82. # NOTE: BusType <> 7, 12, 13 - excludes USB drives, secure digital (SD) and multimedia cards
  83. $output.Disk = ($disks | ForEach-Object {
  84. $DiskSize = [math]::Round($_.Size / 1Gb, (getRoundingRange($_.Size)));
  85. $DiskType = switch ($_.MediaType) { 3 { 'HDD' } 4 { 'SSD' } 5 { 'SCM' } default { 'Generic' } }
  86. Write-Output "$($DiskSize)Gb $DiskType";
  87. }) -join ', ';
  88.  
  89. }
  90. catch {
  91. # not supported - older version of Windows - try older way
  92. $disks = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType = '3'" | Sort-Object -Property __PATH
  93. # NOTE: DriveType = '3' is Local Disk (not removable, not network etc)
  94. $output.Disk = ($disks | ForEach-Object {
  95. $DiskSize = [math]::Round($_.Size / 1Gb, (getRoundingRange($_.Size)));
  96. Write-Output "$($DiskSize)Gb Generic";
  97. }) -join ', ';
  98. }
  99. }
  100. catch {}
  101.  
  102. #
  103. # GPU Info
  104. #
  105. try {
  106. $video = Get-WmiObject Win32_VideoController | Sort-Object -Property Name
  107. $output.Video = ($video | ForEach-Object {
  108. $VideoRAM = [Int64]($_.AdapterRAM / 1GB)
  109. Write-Output "$($_.Caption), $($_.AdapterDACType), $($VideoRAM)Gb"
  110. }) -join ', ';
  111. }
  112. catch {}
  113.  
  114. #
  115. # Network Info
  116. #
  117. function isPhysical([string]$nicName) {
  118.  
  119. $physicalNICs = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object { $_.PhysicalAdapter -eq $true -and $_.PNPDeviceID -notlike 'ROOT\*' };
  120.  
  121. foreach ($physicalNIC in $physicalNICs) {
  122.  
  123. if ($physicalNIC.Name -eq $nicName) {
  124.  
  125. return $true;
  126.  
  127. }
  128. }
  129. }
  130. try {
  131. $wifis = Get-WmiObject -Namespace ROOT\WMI -Class MSNdis_PhysicalMediumType | Where-Object { $_.NdisPhysicalMediumType -eq 9 } | Sort-Object -Property InstanceName
  132. $eths = Get-WmiObject -Namespace ROOT\WMI -Class MSNdis_PhysicalMediumType | Where-Object { $_.NdisPhysicalMediumType -eq 0 } | Sort-Object -Property InstanceName
  133.  
  134. $output.WiFi = ($wifis | ForEach-Object {
  135.  
  136. if (isPhysical($_.InstanceName)) {
  137.  
  138. Write-Output "$($_.InstanceName)"
  139.  
  140. }
  141. }) -join ', ';
  142.  
  143. $output.NIC = ($eths | ForEach-Object {
  144.  
  145. if (isPhysical($_.InstanceName)) {
  146.  
  147. Write-Output "$($_.InstanceName)"
  148.  
  149. }
  150. }) -join ', ';
  151. }
  152. catch {}
  153.  
  154. #
  155. # MB Info
  156. #
  157. try {
  158. $MB = Get-WmiObject Win32_BaseBoard;
  159. $output.'Motherboard Vendor' = if ($MB.Manufacturer) { $MB.Manufacturer } else { 'Unknown' };
  160. $output.'Motherboard Product' = if ($MB.Product) { $MB.Product } else { 'Unknown' };
  161. $output.'Motherboard Version' = if ($MB.Version) { $MB.Version } else { 'Unknown' };
  162. $output.'Motherboard Tag' = if ($MB.Tag) { $MB.Tag } else { 'Unknown' };
  163. }
  164. catch {}
  165.  
  166. #
  167. # System Info
  168. #
  169. try {
  170. $CS = Get-WMIObject Win32_ComputerSystem;
  171. $output.'System Manufacturer' = $CS.Manufacturer;
  172. $output.'System Model' = $CS.Model;
  173. $output.'System Type' = $CS.SystemType;
  174. }
  175. catch {}
  176.  
  177. #
  178. # User Info
  179. #
  180. function GetCurrentUser {
  181. $currentUser = "None"
  182. $previousUser = "None"
  183. $previousFile = "$env:windir\Action1\previousUser.txt"
  184.  
  185. if (-not([string]::IsNullOrEmpty($A1_Agent_Exe_Path))) {
  186. $currentUser = & $A1_Agent_Exe_Path loggedonuser
  187. }
  188. else {
  189. $logonEvents = Get-WinEvent -FilterHashtable @{Logname = 'Security'; ID = 4624 } -MaxEvents 1000 -ErrorAction SilentlyContinue | Where-Object { $lt = $_.Properties[8].Value; $cn = $_.Properties[6].Value; ($lt -eq "2" -or $lt -eq "7" -or $lt -eq "10" -or $lt -eq "11") -and ($cn -ne 'Window Manager' -and $cn -ne 'Font Driver Host') }
  190. $logonEvent = $logonEvents | Select-Object -First 1
  191. try {
  192. $sid = New-Object System.Security.Principal.SecurityIdentifier($logonEvent.Properties[4].Value)
  193. $currentUser = $sid.Translate([System.Security.Principal.NTAccount]).Value
  194. }
  195. catch {
  196. if ($null -ne $logonEvent) {
  197. $currentUser = "$($logonEvent.Properties[6].Value)\$($logonEvent.Properties[5].Value)"
  198. }
  199. }
  200. }
  201.  
  202. try {
  203. if (Test-Path -Path $previousFile -PathType Leaf) {
  204. $previousUser = Get-Content -Path $previousFile -ErrorAction SilentlyContinue
  205. }
  206. }
  207. catch {}
  208.  
  209. if ($currentUser -eq "None" -and -not([string]::IsNullOrEmpty($previousUser))) {
  210. $currentUser = $previousUser
  211. }
  212.  
  213. try {
  214. if ($previousUser -ne $currentUser) {
  215. New-Item -Path $previousFile -ItemType File -Value $currentUser -Force -ErrorAction Stop | Out-Null
  216. }
  217. }
  218. catch {}
  219.  
  220. return $currentUser
  221. }
  222.  
  223. $output.User = GetCurrentUser;
  224.  
  225. #
  226. # BIOS Info
  227. #
  228. try {
  229. $BIOS = Get-WMIObject Win32_BIOS;
  230. $output.'BIOS Manufacturer' = $BIOS.Manufacturer;
  231. $output.'SMBIOS BIOS Version' = $BIOS.SMBIOSBIOSVersion;
  232. $output.'BIOS Software Element State' = switch ($BIOS.SoftwareElementState) { 0 { 'Deployable' } 1 { 'Installable' } 2 { 'Executable' } 3 { 'Running' } default { 'unknown' } };
  233. $output.'BIOS Version' = $BIOS.Version;
  234. $output.'BIOS Serial' = $BIOS.SerialNumber;
  235. }
  236. catch {}
  237.  
  238. #
  239. # Reboot Status
  240. #
  241. function Test-RegistryKey ([string]$Key) {
  242. try {
  243. $keyExist = Test-Path -Path $Key -ErrorAction Stop;
  244. }
  245. catch {
  246. $keyExist = $false;
  247. }
  248.  
  249. Write-Output $keyExist;
  250. }
  251.  
  252. function Test-RegistryValueNotNull ([string]$Key, [string]$Value) {
  253. $valueNotNull = $false;
  254. try {
  255. if ((Test-Path -Path $Key -ErrorAction Stop) -and ($regVal = Get-ItemProperty -Path $Key -Name $Value -ErrorAction Stop) -and $regVal.($Value)) {
  256. $valueNotNull = $true;
  257. }
  258. }
  259. catch {}
  260.  
  261. Write-Output $valueNotNull;
  262. }
  263.  
  264. function Get-RegistryValueSafe ([string]$Key, [string]$Value) {
  265. $valueSafe = $null;
  266. try {
  267. if (Test-Path -Path $Key -ErrorAction Stop) {
  268. $valueSafe = Get-ItemProperty -Path $Key -ErrorAction Stop | Select-Object -ExpandProperty $Value -ErrorAction Stop;
  269. }
  270. }
  271. catch {}
  272.  
  273. Write-Output $valueSafe;
  274. }
  275.  
  276. #
  277. # Reboot Info
  278. #
  279. try {
  280. $rebootPending = Test-RegistryKey -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending';
  281. # $rebootInProgress = Test-RegistryKey -Key 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootInProgress';
  282. # $packagesPending = Test-RegistryKey -Key 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\PackagesPending';
  283. $rebootRequired = Test-RegistryKey -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired';
  284. # $postRebootReporting = Test-RegistryKey -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\PostRebootReporting';
  285. # $pendingFileRenameOperations = Test-RegistryValueNotNull -Key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Value 'PendingFileRenameOperations';
  286. # $pendingFileRenameOperations2 = Test-RegistryValueNotNull -Key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Value 'PendingFileRenameOperations2';
  287. $joinDomain = Test-RegistryKey -Key 'HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon\JoinDomain';
  288. $avoidSpnSet = Test-RegistryKey -Key 'HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon\AvoidSpnSet';
  289. # $updateExeVolatile = ($uev = Get-RegistryValueSafe -Key 'HKLM:\SOFTWARE\Microsoft\Updates' -Value 'UpdateExeVolatile') -and ($uev -ne 0);
  290. $computerNameChanged = ( Get-RegistryValueSafe -Key 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName' -Value 'ComputerName' ) -ne ( Get-RegistryValueSafe -Key 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName' -Value 'ComputerName' );
  291.  
  292. if ( $rebootPending -or $rebootInProgress -or $packagesPending -or $rebootRequired -or $postRebootReporting -or $pendingFileRenameOperations -or
  293. $pendingFileRenameOperations2 -or $joinDomain -or $avoidSpnSet -or $updateExeVolatile -or $computerNameChanged) {
  294. $output.'Reboot Required' = "Yes";
  295. }
  296. else {
  297. $output.'Reboot Required' = "No";
  298. }
  299. }
  300. catch {}
  301.  
  302. #
  303. # Last Boot Up Time
  304. #
  305. try {
  306. $bootDateTime = $null;
  307.  
  308. if ($systemInfoBootUpTime)
  309. {
  310. $lastBootUpTime = Get-WmiObject Win32_OperatingSystem | Select-Object @{Name='LastBootUpTime'; Expression={$_.ConverttoDateTime($_.LastBootUpTime)}};
  311. $bootDateTime = $lastBootUpTime.LastBootUpTime;
  312. }
  313. else {
  314. $startupEvent = Get-WinEvent -LogName 'System' -MaxEvents 1 -FilterXPath "<QueryList><Query Id='0' Path='System'><Select Path='System'>*[System[(EventID=6005)]]</Select></Query></QueryList>";
  315. $bootDateTime = $startupEvent.TimeCreated;
  316. }
  317.  
  318. $lastBootTimeUtc = $bootDateTime.ToUniversalTime();
  319. $formattedBootTime = Get-Date -Date $lastBootTimeUtc -Format 'yyyy-MM-dd_HH-mm-ss';
  320. $output.'Last Boot Time' = $formattedBootTime;
  321. }
  322. catch {}
  323.  
  324. function Convert-DNToCanonicalName {
  325. param (
  326. [string]$DistinguishedName
  327. )
  328.  
  329. $parts = $DistinguishedName -split '(?<!\\),';
  330. $unescapedParts = $parts -replace '\\(?!\\)', '';
  331.  
  332. $canonicalNameComponents = @();
  333. $DCComponents = @();
  334.  
  335. $cnSpecialSymbols = '([\\\/])';
  336.  
  337. for ($i = $unescapedParts.Length - 1; $i -gt 0; $i--) {
  338. $component = $unescapedParts[$i].Trim();
  339. if ($component -match '^DC=(.*)$') {
  340. $domainComponent = $Matches[1];
  341. $DCComponents += $domainComponent -replace $cnSpecialSymbols, '\$1';
  342. } elseif($component -match '^(?:CN|OU)=(.*)$') {
  343. $organizationalUnit = $Matches[1];
  344. $canonicalNameComponents += $organizationalUnit -replace $cnSpecialSymbols, '\$1';
  345. }
  346. }
  347.  
  348. [array]::Reverse($DCComponents);
  349. $canonicalName = "$($DCComponents -join '.')/$($canonicalNameComponents -join '/')";
  350. return $canonicalName;
  351. }
  352.  
  353. #
  354. #Organizational Unit
  355. #
  356. try {
  357. $hasDN = Test-RegistryValueNotNull -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine' -Value 'Distinguished-Name';
  358. if ($hasDN)
  359. {
  360. $ouDN = Get-RegistryValueSafe -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine' -Value 'Distinguished-Name';
  361. $output.OU = Convert-DNToCanonicalName -DistinguishedName $ouDN;
  362. }
  363. }
  364. catch {}
  365.  
  366. #
  367. #AD security groups
  368. #
  369. function ReadXmlFile($filePath) {
  370. $xmlData = $null;
  371. if (Test-Path -Path $filePath -PathType Leaf) {
  372. try {
  373. $xmlData = Import-Clixml -Path $filePath
  374. }
  375. catch {}
  376. }
  377. return $xmlData;
  378. }
  379.  
  380. function SaveToFile($object, $filePath){
  381. if (Test-Path -Path $filePath -PathType Leaf) {
  382. Remove-Item -Path $filePath -Force
  383. }
  384. $object | Export-Clixml $filePath;
  385. }
  386.  
  387. function Get-ComputerDomainSecurityGroups {
  388. $cacheTTL = 15; #minutes
  389. $localAppData = [System.Environment]::GetFolderPath('LocalApplicationData');
  390. $action1Folder = "Action1";
  391. $appDataFolder =Join-Path -Path $localAppData -ChildPath $action1Folder;
  392. $pathCache = Join-Path -Path $appDataFolder -ChildPath "groups.cache";
  393. $sid_to_principal = @{};
  394. $hashOfSIDs = $null;
  395.  
  396. try
  397. {
  398. $refreshGroups = $true;
  399.  
  400. $cacheData = ReadXmlFile -filePath $pathCache;
  401. if ($null -ne $cacheData -and $null -ne $cacheData.timestamp)
  402. {
  403. try {
  404. $timestamp = Get-Date -Date $cacheData.timestamp;
  405. $expiration = $timestamp.AddMinutes($cacheTTL);
  406. $refreshGroups = [datetime]::Now -gt $expiration;
  407. }
  408. catch {}
  409. }
  410.  
  411. try {
  412. #calculating hash of SIDs from registry to save and compare on each start. Need it to to detect membership changes and ignore TTL.
  413. $groupMembershipKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\GroupMembership";
  414. $groupRegistryEntries = Get-Item -Path $groupMembershipKey | Select-Object -ExpandProperty Property | Where-Object {$_ -like "Group*"};
  415. $registrySIDs = @();
  416. foreach ($groupEntry in $groupRegistryEntries) {
  417. $registrySIDs += Get-RegistryValueSafe -Key $groupMembershipKey -Value $groupEntry;
  418. }
  419.  
  420. $sortedRegistrySIDs = $registrySIDs | Sort-Object;
  421. $valuesString = $sortedRegistrySIDs -join '';
  422.  
  423. $stringAsStream = [System.IO.MemoryStream]::new();
  424. $writer = [System.IO.StreamWriter]::new($stringAsStream);
  425. $writer.write($valuesString);
  426. $writer.Flush();
  427. $stringAsStream.Position = 0;
  428.  
  429. $hashOfSIDs = (Get-FileHash -InputStream $stringAsStream) | Select-Object -ExpandProperty Hash;
  430. }
  431. catch {}
  432.  
  433. if (-not $refreshGroups -and $null -ne $cacheData)
  434. {
  435. $refreshGroups = $cacheData.hashOfSIDs -ne $hashOfSIDs;
  436. }
  437.  
  438. if (-not $refreshGroups -and $null -ne $cacheData -and $null -ne $cacheData.sid_to_principal)
  439. {
  440. $sid_to_principal = $cacheData.sid_to_principal;
  441. }
  442.  
  443. if ($refreshGroups)
  444. {
  445. $machineDN = Get-RegistryValueSafe -Key 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine' -Value 'Distinguished-Name';
  446. if ($null -ne $machineDN)
  447. {
  448. $tokenGroups = $null;
  449. try {
  450. $machineDN = $machineDN -replace '([\/])', '\$1';
  451. $de = [ADSI]("LDAP://" + $machineDN);
  452. $de.RefreshCache("tokenGroups");
  453. $tokenGroups = $de.Properties["tokenGroups"];
  454. }
  455. catch {}
  456.  
  457. if ($null -eq $tokenGroups -and $null -ne $cacheData -and $null -ne $cacheData.sid_to_principal)
  458. {
  459. $sid_to_principal = $cacheData.sid_to_principal;
  460. }
  461.  
  462. if ($null -ne $tokenGroups)
  463. {
  464. if ($tokenGroups.Count -gt 0) {
  465. foreach ($groupSidBytes in $tokenGroups) {
  466. $translatedGroup = $null;
  467. try {
  468. $groupSid = New-Object System.Security.Principal.SecurityIdentifier($groupSidBytes, 0);
  469. try {
  470. $translatedGroup = $groupSid.Translate([System.Security.Principal.NTAccount]) | Select-Object -ExpandProperty Value;
  471. }
  472. catch {
  473. try {
  474. #alternative resolving via Active Directory in case of an exception
  475. $adObject = ([ADSI]("LDAP://<SID=" + $groupSid.ToString() + ">"));
  476. $adObject.RefreshCache("msDS-PrincipalName");
  477. $translatedGroup = $adObject.Properties["msDS-PrincipalName"][0].ToString();
  478. }
  479. catch {}
  480. }
  481. finally {
  482. if ($null -eq $translatedGroup -and $null -ne $cacheData -and $null -ne $cacheData.sid_to_principal)
  483. {
  484. $translatedGroup = $cacheData.sid_to_principal[$groupSid.Value];
  485. }
  486. $sid_to_principal.Add($groupSid.Value, $translatedGroup);
  487. }
  488. }
  489. catch {}
  490. }
  491. }
  492.  
  493. $object = [PSCustomObject]@{
  494. timestamp = [datetime]::UtcNow.ToString('o')
  495. hashOfSIDs = $hashOfSIDs
  496. sid_to_principal = $sid_to_principal
  497. }
  498. if(-not (Test-Path -Path $appDataFolder -PathType Container))
  499. {
  500. New-Item -ItemType Directory -Path $appDataFolder | Out-Null;
  501. }
  502. SaveToFile -object $object -filePath $pathCache;
  503. }
  504. }
  505. }
  506. return $sid_to_principal.Values | Where-Object {$null -ne $_};
  507. }
  508. catch {}
  509. }
  510.  
  511. try {
  512. $adgroups = Get-ComputerDomainSecurityGroups | Sort-Object
  513. $cnSpecialSymbols = '([\\,])';
  514. $escapedGroups = @();
  515. foreach ($group in $adgroups) {
  516. $escapedGroups += ($group -replace $cnSpecialSymbols, '\$1');
  517. }
  518. $resultstr = $escapedGroups -join ',';
  519. $output.'AD Security Groups' = $resultstr;
  520.  
  521. }
  522. catch {}
  523.  
  524. $output.A1_Key = 'none';
  525.  
  526. $output;
  527.  
  528. echo (New-Object -Type PSObject -Property @{A1_Key='EOF'});
  529. } catch {
  530. try {
  531. $target_object = if ($_.TargetObject -eq $null) { '' } else { $_.TargetObject.ToString() + ' : ' }
  532. $Host.UI.WriteErrorLine($target_object + $_.Exception.Message + ' (line:' + $_.InvocationInfo.ScriptLineNumber + ' char:' + $_.InvocationInfo.OffsetInLine + ')' + "`nCategoryInfo: " + $_.CategoryInfo + "`nFullyQualifiedErrorId: " + $_.FullyQualifiedErrorId + "`nScript Stack Trace: `n" + $_.ScriptStackTrace);
  533. exit 888;
  534. } catch { exit 999; }
  535. }
  536. }.Invoke() | ConvertTo-Csv -NoTypeInformation -Delimiter ',';
  537. exit 0;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement