param( [string]$Solution = 'C:\Users\tonycao\work\twincat3-auto-cli\TwinCAT_EL6695_Primary\TwinCATProject1.sln', [string]$TargetNetId = '169.254.176.217.1.1' ) $ErrorActionPreference = 'Continue' $LogFile = 'C:\Users\tonycao\work\twincat3-auto-cli\TwinCAT_EL6695_Primary\Logs\scan-demo.log' New-Item -ItemType Directory -Force -Path (Split-Path $LogFile) | Out-Null function Log($m) { $line = (Get-Date -Format 'HH:mm:ss') + " $m" Write-Host $line Add-Content -Path $LogFile -Value $line -Encoding utf8 } Log '=== Open XAE for scan demo ===' try { $dte = New-Object -ComObject TcXaeShell.DTE.17.0 } catch { $dte = New-Object -ComObject TcXaeShell.DTE.15.0 } $dte.MainWindow.Visible = $true try { $dte.SuppressUI = $false } catch { } Log "Open solution: $Solution" $dte.Solution.Open($Solution) for ($i = 1; $i -le 120; $i++) { Start-Sleep -Seconds 1 if ($dte.Solution.IsOpen) { Log "IsOpen after ${i}s"; break } } $sm = $null for ($i = 1; $i -le 30; $i++) { try { $sm = $dte.Solution.Projects.Item(1).Object; if ($sm) { Log 'SysManager ready'; break } } catch {} Start-Sleep -Seconds 3 } Log 'Wait 20s for tree load...' Start-Sleep -Seconds 20 # Set target and activate to go online try { $sm.SetTargetNetId($TargetNetId); Log 'SetTargetNetId OK' } catch { Log "SetTargetNetId err: $_" } Log 'Activate config...' try { $sm.ActivateConfiguration(); Log 'ActivateConfiguration OK' } catch { Log "ActivateConfiguration err: $_" } Start-Sleep -Seconds 10 # Find EtherCAT device and select it in solution explorer try { $io = $sm.LookupTreeItem('TIID') if ($io -and $io.ChildCount -ge 1) { $ecat = $io.Child(1) Log ("Found EtherCAT device: " + $ecat.Name) # Select in Solution Explorer $se = $dte.ToolWindows.SolutionExplorer $se.Parent.Activate() Start-Sleep -Seconds 2 function Find-Node($items) { if ($null -eq $items) { return $null } foreach ($it in $items) { try { if ($it.Name -like '*EtherCAT*') { return $it } } catch {} try { $sub = Find-Node $it.UIHierarchyItems; if ($sub) { return $sub } } catch {} } return $null } $node = Find-Node $se.UIHierarchyItems if ($node) { $node.Select(1) Log "Selected node: $($node.Name)" Start-Sleep -Seconds 3 } else { Log "WARN: Could not select EtherCAT node in UI" } } } catch { Log "Tree selection err: $($_.Exception.Message)" } # Try scan command # 扫 = U+626B = 25131, 描 = U+63CF = 25551 $sao = [char]25131 $miao = [char]25551 $cmdScan = "TwinCAT.$sao$miao" Log "Execute scan command: [$cmdScan]" try { $dte.ExecuteCommand($cmdScan); Log 'Scan command OK' } catch { Log "Scan command err: $($_.Exception.Message)" } Log '' Log '=== XAE window open - 60s for observation ===' Start-Sleep -Seconds 60 try { $dte.Quit() } catch {} Log '=== Demo done ==='