Reorganize repo: compartmentalize scripts by client/project

Move 150+ scripts from root and scripts/ into client/project directories:
- clients/dataforth/scripts/ (110 files: AD2, sync, SSH, DB, DOS scripts)
- clients/bg-builders/scripts/ (14 files: Lesley mgmt, Exchange, termination)
- clients/internal-infrastructure/scripts/ (10 files: GDAP, Gitea, backups)
- projects/msp-tools/scripts/ (9 files: CIPP, MSP onboarding, Datto)
- projects/gururmm-agent/scripts/ (3 files: API test, JWT, record counts)
- clients/glaztech/scripts/ (1 file: CentraStage removal)

Also reorganized:
- VPN scripts → infrastructure/vpn-configs/
- Retrieved API/JS files → api/
- Forum posts → projects/community-forum/forum-posts/
- SSH docs → clients/internal-infrastructure/docs/
- NWTOC/CTONW docs → projects/wrightstown-smarthome/docs/
- ACG website files → projects/internal/acg-website-2025/
- Dataforth docs → clients/dataforth/docs/
- schema-retrieved.sql → docs/database/

Deleted 24 tmp_*.ps1 one-off debug scripts (preserved in git history).
Root reduced from 220+ files to 62 items (docs + directories only).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-20 17:15:07 -07:00
parent 98ea867d2c
commit 5cbd49ce24
207 changed files with 49 additions and 547 deletions

View File

@@ -0,0 +1,204 @@
# Sync Script Update Summary
**Date:** 2026-01-19
**File Modified:** \\192.168.0.6\C$\Shares\test\scripts\Sync-FromNAS.ps1
**Change:** Added DEPLOY.BAT to root-level sync
---
## Change Made
Added DEPLOY.BAT sync to match existing UPDATE.BAT sync pattern.
### Code Added (Lines 304-325)
```powershell
# Sync DEPLOY.BAT (root level utility)
Write-Log "Syncing DEPLOY.BAT..."
$deployBatLocal = "$AD2_TEST_PATH\DEPLOY.BAT"
if (Test-Path $deployBatLocal) {
$deployBatRemote = "$NAS_DATA_PATH/DEPLOY.BAT"
if ($DryRun) {
Write-Log " [DRY RUN] Would push: DEPLOY.BAT -> $deployBatRemote"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $deployBatLocal -RemotePath $deployBatRemote
if ($success) {
Write-Log " Pushed: DEPLOY.BAT"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push DEPLOY.BAT"
$errorCount++
}
}
} else {
Write-Log " WARNING: DEPLOY.BAT not found at $deployBatLocal"
}
```
---
## File Locations
### AD2 (Source)
- C:\Shares\test\UPDATE.BAT
- C:\Shares\test\DEPLOY.BAT
### NAS (Destination via Sync)
- /data/test/UPDATE.BAT (accessible as T:\UPDATE.BAT from DOS)
- /data/test/DEPLOY.BAT (accessible as T:\DEPLOY.BAT from DOS)
### COMMON/ProdSW (Also Synced)
- T:\COMMON\ProdSW\UPDATE.BAT (backup copy)
- T:\COMMON\ProdSW\DEPLOY.BAT (deployment script)
- T:\COMMON\ProdSW\NWTOC.BAT
- T:\COMMON\ProdSW\CTONW.BAT
- T:\COMMON\ProdSW\STAGE.BAT
- T:\COMMON\ProdSW\REBOOT.BAT
- T:\COMMON\ProdSW\CHECKUPD.BAT
---
## Purpose
### UPDATE.BAT at Root (T:\UPDATE.BAT)
- **Purpose:** Quick access backup utility from any DOS machine
- **Usage:** Can run `T:\UPDATE` from any machine without changing directory
- **Function:** Backs up C: drive to T:\%MACHINE%\BACKUP\
### DEPLOY.BAT at Root (T:\DEPLOY.BAT)
- **Purpose:** One-time deployment installer accessible from boot
- **Usage:** Run `T:\DEPLOY` to install update system on new/re-imaged machines
- **Function:** Installs all batch files, sets MACHINE variable, configures AUTOEXEC.BAT
**Benefit:** Both utilities are accessible from T: drive root, making them easy to find and run without navigating to COMMON\ProdSW\
---
## Sync Verification
**Sync Run:** 2026-01-19 12:55:14
**Result:** [OK] SUCCESS
```
2026-01-19 12:55:40 : Syncing UPDATE.BAT...
2026-01-19 12:55:41 : Pushed: UPDATE.BAT
2026-01-19 12:55:41 : Syncing DEPLOY.BAT...
2026-01-19 12:55:43 : Pushed: DEPLOY.BAT
```
Both files successfully pushed to NAS root directory.
---
## Sync Schedule
- **Frequency:** Every 15 minutes
- **Scheduled Task:** Windows Task Scheduler on AD2
- **Script:** C:\Shares\test\scripts\Sync-FromNAS.ps1
- **Log:** C:\Shares\test\scripts\sync-from-nas.log
- **Status:** C:\Shares\test\_SYNC_STATUS.txt
---
## Files Now Available on DOS Machines
### From Root (T:\)
```
T:\UPDATE.BAT - Quick backup utility
T:\DEPLOY.BAT - One-time deployment installer
```
### From COMMON (T:\COMMON\ProdSW\)
```
T:\COMMON\ProdSW\NWTOC.BAT - Download updates
T:\COMMON\ProdSW\CTONW.BAT - Upload changes (v1.2)
T:\COMMON\ProdSW\UPDATE.BAT - Backup utility (copy)
T:\COMMON\ProdSW\STAGE.BAT - Stage system files
T:\COMMON\ProdSW\REBOOT.BAT - Apply staged updates
T:\COMMON\ProdSW\CHECKUPD.BAT - Check for updates
T:\COMMON\ProdSW\DEPLOY.BAT - Deployment installer (copy)
```
---
## Deployment Workflow
### New Machine Setup
1. Boot DOS machine with network access
2. Map T: drive: `NET USE T: \\D2TESTNAS\test /YES`
3. Run deployment: `T:\DEPLOY`
4. Follow prompts to enter machine name (e.g., TS-4R)
5. Reboot machine
6. Run initial download: `C:\BAT\NWTOC`
### Quick Backup from Root
```
T:\UPDATE
```
No need to CD to COMMON\ProdSW first.
---
## Testing Recommendations
### Test Root Access
From any DOS machine with T: drive mapped:
```batch
T:
DIR UPDATE.BAT
DIR DEPLOY.BAT
```
Both files should be visible at T: root.
### Test Deployment
On test machine (or VM):
```batch
T:\DEPLOY
```
Should run deployment installer successfully.
### Test Quick Backup
```batch
T:\UPDATE
```
Should back up C: drive to network.
---
## Maintenance Notes
### Updating Scripts
1. Edit files in D:\ClaudeTools\
2. Run: `powershell -File D:\ClaudeTools\copy-root-files-to-ad2.ps1`
3. Files copied to AD2 root: C:\Shares\test\
4. Next sync (within 15 min) pushes to NAS root
5. Files available at T:\ on DOS machines
### Monitoring Sync
```powershell
# Check sync log
Get-Content \\192.168.0.6\C$\Shares\test\scripts\sync-from-nas.log -Tail 50
# Check sync status
Get-Content \\192.168.0.6\C$\Shares\test\_SYNC_STATUS.txt
```
---
## Change History
| Date | Change | By |
|------|--------|-----|
| 2026-01-19 | Added DEPLOY.BAT to root-level sync | Claude Code |
| 2026-01-19 | UPDATE.BAT already syncing to root | (Existing) |
---
**Status:** [OK] COMPLETE AND TESTED
**Next Sync:** Automatic (every 15 minutes)
**Files Available:** T:\UPDATE.BAT and T:\DEPLOY.BAT

View File

@@ -0,0 +1,158 @@
# Check if notifications@dataforth.com is a shared mailbox and authentication options
# This determines how the website should authenticate
Write-Host "[OK] Checking mailbox configuration..." -ForegroundColor Green
Write-Host ""
# Check if connected to Exchange Online
$Session = Get-PSSession | Where-Object { $_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" }
if (-not $Session) {
Write-Host "[WARNING] Not connected to Exchange Online, connecting..." -ForegroundColor Yellow
Connect-ExchangeOnline -UserPrincipalName sysadmin@dataforth.com -ShowBanner:$false
}
Write-Host "================================================================"
Write-Host "1. MAILBOX TYPE"
Write-Host "================================================================"
$Mailbox = Get-Mailbox -Identity notifications@dataforth.com
Write-Host "[OK] Mailbox Details:"
Write-Host " Primary SMTP: $($Mailbox.PrimarySmtpAddress)"
Write-Host " Display Name: $($Mailbox.DisplayName)"
Write-Host " Type: $($Mailbox.RecipientTypeDetails)" -ForegroundColor Cyan
Write-Host " Alias: $($Mailbox.Alias)"
Write-Host ""
if ($Mailbox.RecipientTypeDetails -eq "SharedMailbox") {
Write-Host "[CRITICAL] This is a SHARED MAILBOX" -ForegroundColor Red
Write-Host " Shared mailboxes CANNOT authenticate directly!" -ForegroundColor Red
Write-Host ""
Write-Host "Options for website authentication:" -ForegroundColor Yellow
Write-Host " 1. Use a regular user account with 'Send As' permissions"
Write-Host " 2. Convert to regular mailbox (requires license)"
Write-Host " 3. Use Microsoft Graph API with OAuth"
$IsShared = $true
} elseif ($Mailbox.RecipientTypeDetails -eq "UserMailbox") {
Write-Host "[OK] This is a USER MAILBOX" -ForegroundColor Green
Write-Host " Can authenticate directly with SMTP AUTH" -ForegroundColor Green
$IsShared = $false
} else {
Write-Host "[WARNING] Mailbox type: $($Mailbox.RecipientTypeDetails)" -ForegroundColor Yellow
$IsShared = $false
}
Write-Host ""
Write-Host "================================================================"
Write-Host "2. SMTP AUTH STATUS"
Write-Host "================================================================"
$CASMailbox = Get-CASMailbox -Identity notifications@dataforth.com
Write-Host "[OK] Client Access Settings:"
Write-Host " SMTP AUTH Disabled: $($CASMailbox.SmtpClientAuthenticationDisabled)"
if ($CASMailbox.SmtpClientAuthenticationDisabled -eq $true) {
Write-Host " [ERROR] SMTP AUTH is DISABLED!" -ForegroundColor Red
if (-not $IsShared) {
Write-Host " [FIX] To enable: Set-CASMailbox -Identity notifications@dataforth.com -SmtpClientAuthenticationDisabled `$false" -ForegroundColor Yellow
}
} else {
Write-Host " [OK] SMTP AUTH is ENABLED" -ForegroundColor Green
}
Write-Host ""
Write-Host "================================================================"
Write-Host "3. LICENSE STATUS"
Write-Host "================================================================"
# Check licenses via Get-MsolUser or Microsoft Graph
try {
$MsolUser = Get-MsolUser -UserPrincipalName notifications@dataforth.com -ErrorAction SilentlyContinue
if ($MsolUser) {
Write-Host "[OK] License Status:"
Write-Host " Licensed: $($MsolUser.IsLicensed)"
if ($MsolUser.IsLicensed) {
Write-Host " Licenses: $($MsolUser.Licenses.AccountSkuId -join ', ')"
}
} else {
Write-Host "[WARNING] Could not check licenses via MSOnline module" -ForegroundColor Yellow
}
} catch {
Write-Host "[WARNING] MSOnline module not available" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "================================================================"
Write-Host "4. SEND AS PERMISSIONS (if shared mailbox)"
Write-Host "================================================================"
if ($IsShared) {
$SendAsPermissions = Get-RecipientPermission -Identity notifications@dataforth.com | Where-Object { $_.Trustee -ne "NT AUTHORITY\SELF" }
if ($SendAsPermissions) {
Write-Host "[OK] Users/Groups with 'Send As' permission:"
foreach ($Perm in $SendAsPermissions) {
Write-Host " - $($Perm.Trustee) ($($Perm.AccessRights))" -ForegroundColor Cyan
}
Write-Host ""
Write-Host "[SOLUTION] The website can authenticate using one of these accounts" -ForegroundColor Green
Write-Host " with 'Send As' permission, then send as notifications@dataforth.com" -ForegroundColor Green
} else {
Write-Host "[WARNING] No 'Send As' permissions configured" -ForegroundColor Yellow
Write-Host " Grant permission: Add-RecipientPermission -Identity notifications@dataforth.com -Trustee <user> -AccessRights SendAs" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "================================================================"
Write-Host "RECOMMENDATIONS FOR WEBSITE AUTHENTICATION"
Write-Host "================================================================"
if ($IsShared) {
Write-Host ""
Write-Host "[OPTION 1] Use a service account with Send As permission" -ForegroundColor Cyan
Write-Host " 1. Create/use existing user account (e.g., sysadmin@dataforth.com)"
Write-Host " 2. Grant Send As permission:"
Write-Host " Add-RecipientPermission -Identity notifications@dataforth.com -Trustee sysadmin@dataforth.com -AccessRights SendAs"
Write-Host " 3. Website config:"
Write-Host " - SMTP Server: smtp.office365.com"
Write-Host " - Port: 587"
Write-Host " - Username: sysadmin@dataforth.com"
Write-Host " - Password: <sysadmin password>"
Write-Host " - From Address: notifications@dataforth.com"
Write-Host ""
Write-Host "[OPTION 2] Convert to regular mailbox (requires license)" -ForegroundColor Cyan
Write-Host " Set-Mailbox -Identity notifications@dataforth.com -Type Regular"
Write-Host " Then assign a license and enable SMTP AUTH"
Write-Host ""
Write-Host "[OPTION 3] Use Microsoft Graph API (OAuth - modern auth)" -ForegroundColor Cyan
Write-Host " Most secure but requires application changes"
} else {
Write-Host ""
Write-Host "[SOLUTION] This is a regular mailbox - can authenticate directly" -ForegroundColor Green
Write-Host ""
Write-Host "Website SMTP Configuration:"
Write-Host " - SMTP Server: smtp.office365.com"
Write-Host " - Port: 587 (STARTTLS)"
Write-Host " - Username: notifications@dataforth.com"
Write-Host " - Password: <account password>"
Write-Host " - Authentication: Required"
Write-Host " - SSL/TLS: Yes"
Write-Host ""
if ($CASMailbox.SmtpClientAuthenticationDisabled -eq $false) {
Write-Host "[OK] SMTP AUTH is enabled - credentials should work" -ForegroundColor Green
Write-Host ""
Write-Host "If still failing, check:" -ForegroundColor Yellow
Write-Host " - Correct password in website config"
Write-Host " - Firewall allowing outbound port 587"
Write-Host " - Run Test-DataforthSMTP.ps1 to verify credentials"
} else {
Write-Host "[ERROR] SMTP AUTH is DISABLED - must enable first!" -ForegroundColor Red
Write-Host "Run: Set-CASMailbox -Identity notifications@dataforth.com -SmtpClientAuthenticationDisabled `$false" -ForegroundColor Yellow
}
}
Write-Host ""

View File

@@ -0,0 +1,124 @@
# Get Exchange Online logs for notifications@dataforth.com
# This script retrieves message traces and mailbox audit logs
Write-Host "[OK] Checking Exchange Online connection..." -ForegroundColor Green
# Check if connected to Exchange Online
$Session = Get-PSSession | Where-Object { $_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" }
if (-not $Session) {
Write-Host "[WARNING] Not connected to Exchange Online" -ForegroundColor Yellow
Write-Host " Connecting now..." -ForegroundColor Yellow
Write-Host ""
try {
Connect-ExchangeOnline -UserPrincipalName sysadmin@dataforth.com -ShowBanner:$false
Write-Host "[OK] Connected to Exchange Online" -ForegroundColor Green
} catch {
Write-Host "[ERROR] Failed to connect to Exchange Online" -ForegroundColor Red
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
}
Write-Host ""
Write-Host "================================================================"
Write-Host "1. Checking SMTP AUTH status"
Write-Host "================================================================"
$CASMailbox = Get-CASMailbox -Identity notifications@dataforth.com
Write-Host "[OK] SMTP AUTH Status:"
Write-Host " SmtpClientAuthenticationDisabled: $($CASMailbox.SmtpClientAuthenticationDisabled)"
if ($CASMailbox.SmtpClientAuthenticationDisabled -eq $true) {
Write-Host "[ERROR] SMTP AUTH is DISABLED for this mailbox!" -ForegroundColor Red
Write-Host " To enable: Set-CASMailbox -Identity notifications@dataforth.com -SmtpClientAuthenticationDisabled `$false" -ForegroundColor Yellow
} else {
Write-Host "[OK] SMTP AUTH is enabled" -ForegroundColor Green
}
Write-Host ""
Write-Host "================================================================"
Write-Host "2. Checking message trace (last 7 days)"
Write-Host "================================================================"
$StartDate = (Get-Date).AddDays(-7)
$EndDate = Get-Date
Write-Host "[OK] Searching for messages from notifications@dataforth.com..."
$Messages = Get-MessageTrace -SenderAddress notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate
if ($Messages) {
Write-Host "[OK] Found $($Messages.Count) messages sent in the last 7 days" -ForegroundColor Green
Write-Host ""
$Messages | Select-Object -First 10 | Format-Table Received, RecipientAddress, Subject, Status, Size -AutoSize
$FailedMessages = $Messages | Where-Object { $_.Status -ne "Delivered" }
if ($FailedMessages) {
Write-Host ""
Write-Host "[WARNING] Found $($FailedMessages.Count) failed/pending messages:" -ForegroundColor Yellow
$FailedMessages | Format-Table Received, RecipientAddress, Subject, Status -AutoSize
}
} else {
Write-Host "[WARNING] No messages found in the last 7 days" -ForegroundColor Yellow
Write-Host " This suggests emails are not reaching Exchange Online" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "================================================================"
Write-Host "3. Checking mailbox audit logs"
Write-Host "================================================================"
Write-Host "[OK] Checking for authentication events..."
$AuditLogs = Search-MailboxAuditLog -Identity notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate -ShowDetails
if ($AuditLogs) {
Write-Host "[OK] Found $($AuditLogs.Count) audit events" -ForegroundColor Green
$AuditLogs | Select-Object -First 10 | Format-Table LastAccessed, Operation, LogonType, ClientIPAddress -AutoSize
} else {
Write-Host "[OK] No mailbox audit events found" -ForegroundColor Green
}
Write-Host ""
Write-Host "================================================================"
Write-Host "4. Checking for failed authentication attempts (Unified Audit Log)"
Write-Host "================================================================"
Write-Host "[OK] Searching for failed logins..."
$AuditRecords = Search-UnifiedAuditLog -UserIds notifications@dataforth.com -StartDate $StartDate -EndDate $EndDate -Operations UserLoginFailed,MailboxLogin -ResultSize 100
if ($AuditRecords) {
Write-Host "[WARNING] Found $($AuditRecords.Count) authentication events" -ForegroundColor Yellow
Write-Host ""
foreach ($Record in $AuditRecords | Select-Object -First 5) {
$AuditData = $Record.AuditData | ConvertFrom-Json
Write-Host " [EVENT] $($Record.CreationDate)"
Write-Host " Operation: $($Record.Operations)"
Write-Host " Client IP: $($AuditData.ClientIP)"
Write-Host " Result: $($AuditData.ResultStatus)"
if ($AuditData.LogonError) {
Write-Host " Error: $($AuditData.LogonError)" -ForegroundColor Red
}
Write-Host ""
}
} else {
Write-Host "[OK] No failed authentication attempts found" -ForegroundColor Green
}
Write-Host ""
Write-Host "================================================================"
Write-Host "SUMMARY"
Write-Host "================================================================"
Write-Host "Review the logs above to identify the issue."
Write-Host ""
Write-Host "Common issues:"
Write-Host " - SMTP AUTH disabled (check section 1)"
Write-Host " - Wrong credentials (check section 4 for failed logins)"
Write-Host " - No messages reaching Exchange (check section 2)"
Write-Host " - Firewall blocking connection"
Write-Host " - App needs app-specific password (if MFA enabled)"

View File

@@ -0,0 +1,140 @@
# Reset password for notifications@dataforth.com in on-premises AD
# For hybrid environments with Azure AD Connect password sync
param(
[string]$DomainController = "192.168.0.27", # AD1 (primary DC)
[string]$NewPassword = "%5cfI:G71)}=g4ZS"
)
Write-Host "[OK] Resetting password in on-premises Active Directory..." -ForegroundColor Green
Write-Host " Domain Controller: $DomainController (AD1)" -ForegroundColor Cyan
Write-Host ""
# Credentials for remote connection
$AdminUser = "INTRANET\sysadmin"
$AdminPassword = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($AdminUser, $AdminPassword)
Write-Host "[OK] Connecting to $DomainController via PowerShell remoting..." -ForegroundColor Green
try {
# Execute on remote DC
Invoke-Command -ComputerName $DomainController -Credential $Credential -ScriptBlock {
param($NewPass, $UserName)
Import-Module ActiveDirectory
# Find the user account
Write-Host "[OK] Searching for user in Active Directory..."
$User = Get-ADUser -Filter "UserPrincipalName -eq '$UserName'" -Properties PasswordNeverExpires, PasswordLastSet
if (-not $User) {
Write-Host "[ERROR] User not found in Active Directory!" -ForegroundColor Red
return
}
Write-Host "[OK] Found user: $($User.Name) ($($User.UserPrincipalName))"
Write-Host " Current PasswordNeverExpires: $($User.PasswordNeverExpires)"
Write-Host " Last Password Set: $($User.PasswordLastSet)"
Write-Host ""
# Reset password
Write-Host "[OK] Resetting password..." -ForegroundColor Green
$SecurePassword = ConvertTo-SecureString $NewPass -AsPlainText -Force
Set-ADAccountPassword -Identity $User.SamAccountName -NewPassword $SecurePassword -Reset
Write-Host "[SUCCESS] Password reset successfully!" -ForegroundColor Green
# Set password to never expire
Write-Host "[OK] Setting password to never expire..." -ForegroundColor Green
Set-ADUser -Identity $User.SamAccountName -PasswordNeverExpires $true -ChangePasswordAtLogon $false
Write-Host "[SUCCESS] Password set to never expire!" -ForegroundColor Green
# Verify
$UpdatedUser = Get-ADUser -Identity $User.SamAccountName -Properties PasswordNeverExpires, PasswordLastSet
Write-Host ""
Write-Host "[OK] Verification:"
Write-Host " PasswordNeverExpires: $($UpdatedUser.PasswordNeverExpires)"
Write-Host " PasswordLastSet: $($UpdatedUser.PasswordLastSet)"
# Force Azure AD Connect sync (if available)
Write-Host ""
Write-Host "[OK] Checking for Azure AD Connect..." -ForegroundColor Green
if (Get-Command Start-ADSyncSyncCycle -ErrorAction SilentlyContinue) {
Write-Host "[OK] Triggering Azure AD Connect sync..." -ForegroundColor Green
Start-ADSyncSyncCycle -PolicyType Delta
Write-Host "[OK] Sync triggered - password will sync to Azure AD in ~3 minutes" -ForegroundColor Green
} else {
Write-Host "[WARNING] Azure AD Connect not found on this server" -ForegroundColor Yellow
Write-Host " Password will sync automatically within 30 minutes" -ForegroundColor Yellow
Write-Host " Or manually trigger sync on AAD Connect server" -ForegroundColor Yellow
}
} -ArgumentList $NewPassword, "notifications@dataforth.com"
Write-Host ""
Write-Host "================================================================"
Write-Host "PASSWORD RESET COMPLETE"
Write-Host "================================================================"
Write-Host "New Password: $NewPassword" -ForegroundColor Yellow
Write-Host ""
Write-Host "[OK] Password policy: NEVER EXPIRES (set in AD)" -ForegroundColor Green
Write-Host "[OK] Azure AD Connect will sync this change automatically" -ForegroundColor Green
Write-Host ""
Write-Host "================================================================"
Write-Host "NEXT STEPS"
Write-Host "================================================================"
Write-Host "1. Wait 3-5 minutes for Azure AD Connect to sync" -ForegroundColor Cyan
Write-Host ""
Write-Host "2. Update website SMTP configuration:" -ForegroundColor Cyan
Write-Host " - Username: notifications@dataforth.com"
Write-Host " - Password: $NewPassword" -ForegroundColor Yellow
Write-Host ""
Write-Host "3. Test SMTP authentication:" -ForegroundColor Cyan
Write-Host " D:\ClaudeTools\Test-DataforthSMTP.ps1"
Write-Host ""
Write-Host "4. Verify authentication succeeds:" -ForegroundColor Cyan
Write-Host " D:\ClaudeTools\Get-DataforthEmailLogs.ps1"
Write-Host ""
# Save credentials
$CredPath = "D:\ClaudeTools\dataforth-notifications-FINAL-PASSWORD.txt"
@"
Dataforth Notifications Account - PASSWORD RESET (HYBRID AD)
Reset Date: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Username: notifications@dataforth.com
Password: $NewPassword
Password Policy:
- Set in: On-Premises Active Directory (INTRANET domain)
- Never Expires: YES
- Synced to Azure AD: Via Azure AD Connect
SMTP Configuration for Website:
- Server: smtp.office365.com
- Port: 587
- TLS: Yes
- Username: notifications@dataforth.com
- Password: $NewPassword
Note: Allow 3-5 minutes for password to sync to Azure AD before testing.
DO NOT COMMIT TO GIT OR SHARE PUBLICLY
"@ | Out-File -FilePath $CredPath -Encoding UTF8
Write-Host "[OK] Credentials saved to: $CredPath" -ForegroundColor Green
} catch {
Write-Host "[ERROR] Failed to reset password: $($_.Exception.Message)" -ForegroundColor Red
Write-Host ""
Write-Host "Troubleshooting:" -ForegroundColor Yellow
Write-Host "- Ensure you're on the Dataforth VPN or network" -ForegroundColor Yellow
Write-Host "- Verify AD1 (192.168.0.27) is accessible" -ForegroundColor Yellow
Write-Host "- Check WinRM is enabled on AD1" -ForegroundColor Yellow
Write-Host ""
Write-Host "Alternative: RDP to AD1 and run locally:" -ForegroundColor Cyan
Write-Host " Set-ADAccountPassword -Identity notifications -Reset -NewPassword (ConvertTo-SecureString '$NewPassword' -AsPlainText -Force)" -ForegroundColor Gray
Write-Host " Set-ADUser -Identity notifications -PasswordNeverExpires `$true -ChangePasswordAtLogon `$false" -ForegroundColor Gray
}

View File

@@ -0,0 +1,105 @@
# Reset password for notifications@dataforth.com and set to never expire
# Using Microsoft Graph PowerShell (modern approach)
Write-Host "[OK] Resetting password for notifications@dataforth.com..." -ForegroundColor Green
Write-Host ""
# Check if Microsoft.Graph module is installed
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Users)) {
Write-Host "[WARNING] Microsoft.Graph.Users module not installed" -ForegroundColor Yellow
Write-Host " Installing now..." -ForegroundColor Yellow
Install-Module Microsoft.Graph.Users -Scope CurrentUser -Force
}
# Connect to Microsoft Graph
Write-Host "[OK] Connecting to Microsoft Graph..." -ForegroundColor Green
Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All" -TenantId "7dfa3ce8-c496-4b51-ab8d-bd3dcd78b584"
# Generate a strong random password
Add-Type -AssemblyName System.Web
$NewPassword = [System.Web.Security.Membership]::GeneratePassword(16, 4)
Write-Host "[OK] Generated new password: $NewPassword" -ForegroundColor Cyan
Write-Host " SAVE THIS PASSWORD - you'll need it for the website config" -ForegroundColor Yellow
Write-Host ""
# Reset the password
$PasswordProfile = @{
Password = $NewPassword
ForceChangePasswordNextSignIn = $false
}
try {
Update-MgUser -UserId "notifications@dataforth.com" -PasswordProfile $PasswordProfile
Write-Host "[SUCCESS] Password reset successfully!" -ForegroundColor Green
} catch {
Write-Host "[ERROR] Failed to reset password: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
# Set password to never expire
Write-Host "[OK] Setting password to never expire..." -ForegroundColor Green
try {
Update-MgUser -UserId "notifications@dataforth.com" -PasswordPolicies "DisablePasswordExpiration"
Write-Host "[SUCCESS] Password set to never expire!" -ForegroundColor Green
} catch {
Write-Host "[ERROR] Failed to set password policy: $($_.Exception.Message)" -ForegroundColor Red
}
# Verify the settings
Write-Host ""
Write-Host "================================================================"
Write-Host "Verifying Configuration"
Write-Host "================================================================"
$User = Get-MgUser -UserId "notifications@dataforth.com" -Property UserPrincipalName,PasswordPolicies,LastPasswordChangeDateTime
Write-Host "[OK] User: $($User.UserPrincipalName)"
Write-Host " Password Policies: $($User.PasswordPolicies)"
Write-Host " Last Password Change: $($User.LastPasswordChangeDateTime)"
if ($User.PasswordPolicies -contains "DisablePasswordExpiration") {
Write-Host " [OK] Password will never expire" -ForegroundColor Green
} else {
Write-Host " [WARNING] Password expiration policy not confirmed" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "================================================================"
Write-Host "NEXT STEPS"
Write-Host "================================================================"
Write-Host "1. Update the website SMTP configuration with:" -ForegroundColor Cyan
Write-Host " - Username: notifications@dataforth.com"
Write-Host " - Password: $NewPassword" -ForegroundColor Yellow
Write-Host ""
Write-Host "2. Test SMTP authentication:"
Write-Host " D:\ClaudeTools\Test-DataforthSMTP.ps1"
Write-Host ""
Write-Host "3. Monitor for successful sends:"
Write-Host " Get-MessageTrace -SenderAddress notifications@dataforth.com -StartDate (Get-Date).AddHours(-1)"
Write-Host ""
# Save credentials to a secure file for reference
$CredPath = "D:\ClaudeTools\dataforth-notifications-creds.txt"
@"
Dataforth Notifications Account Credentials
Generated: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Username: notifications@dataforth.com
Password: $NewPassword
SMTP Configuration for Website:
- Server: smtp.office365.com
- Port: 587
- TLS: Yes
- Username: notifications@dataforth.com
- Password: $NewPassword
DO NOT COMMIT TO GIT OR SHARE PUBLICLY
"@ | Out-File -FilePath $CredPath -Encoding UTF8
Write-Host "[OK] Credentials saved to: $CredPath" -ForegroundColor Green
Write-Host " (Keep this file secure!)" -ForegroundColor Yellow
Disconnect-MgGraph

View File

@@ -0,0 +1,431 @@
# Sync-AD2-NAS.ps1 (formerly Sync-FromNAS.ps1)
# Bidirectional sync between AD2 and NAS (D2TESTNAS)
#
# PULL (NAS → AD2): Test results (LOGS/*.DAT, Reports/*.TXT) → Database import
# PUSH (AD2 → NAS): Software updates (ProdSW/*, TODO.BAT) → DOS machines
#
# Run: powershell -ExecutionPolicy Bypass -File C:\Shares\test\scripts\Sync-FromNAS.ps1
# Scheduled: Every 15 minutes via Windows Task Scheduler
param(
[switch]$DryRun, # Show what would be done without doing it
[switch]$Verbose, # Extra output
[int]$MaxAgeMinutes = 1440 # Default: files from last 24 hours (was 60 min, too aggressive)
)
# ============================================================================
# Configuration
# ============================================================================
$NAS_IP = "192.168.0.9"
$NAS_USER = "root"
$NAS_PASSWORD = "Paper123!@#-nas"
$NAS_HOSTKEY = "SHA256:5CVIPlqjLPxO8n48PKLAP99nE6XkEBAjTkaYmJAeOdA"
$NAS_DATA_PATH = "/data/test"
$AD2_TEST_PATH = "C:\Shares\test"
$AD2_HISTLOGS_PATH = "C:\Shares\test\Ate\HISTLOGS"
$SSH = "C:\Program Files\OpenSSH\ssh.exe" # Changed from PLINK to OpenSSH
$SCP = "C:\Program Files\OpenSSH\scp.exe" # Changed from PSCP to OpenSSH
$LOG_FILE = "C:\Shares\test\scripts\sync-from-nas.log"
$STATUS_FILE = "C:\Shares\test\_SYNC_STATUS.txt"
$LOG_TYPES = @("5BLOG", "7BLOG", "8BLOG", "DSCLOG", "SCTLOG", "VASLOG", "PWRLOG", "HVLOG")
# Database import configuration
$IMPORT_SCRIPT = "C:\Shares\testdatadb\database\import.js"
$NODE_PATH = "node"
# ============================================================================
# Functions
# ============================================================================
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logLine = "$timestamp : $Message"
Add-Content -Path $LOG_FILE -Value $logLine
if ($Verbose) { Write-Host $logLine }
}
function Invoke-NASCommand {
param([string]$Command)
$result = & $SSH -i "C:\Users\sysadmin\.ssh\id_ed25519" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new $Command 2>&1
return $result
}
function Copy-FromNAS {
param(
[string]$RemotePath,
[string]$LocalPath
)
# Ensure local directory exists
$localDir = Split-Path -Parent $LocalPath
if (-not (Test-Path $localDir)) {
New-Item -ItemType Directory -Path $localDir -Force | Out-Null
}
$result = & $SCP -O -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" "${NAS_USER}@${NAS_IP}:$RemotePath" $LocalPath 2>&1 if ($LASTEXITCODE -ne 0) {
$errorMsg = $result | Out-String
Write-Log " SCP PUSH ERROR (exit $LASTEXITCODE): $errorMsg"
}
return $LASTEXITCODE -eq 0
}
function Remove-FromNAS {
param([string]$RemotePath)
Invoke-NASCommand "rm -f '$RemotePath'" | Out-Null
}
function Copy-ToNAS {
param(
[string]$LocalPath,
[string]$RemotePath
)
# Ensure remote directory exists
$remoteDir = Split-Path -Parent $RemotePath
Invoke-NASCommand "mkdir -p '$remoteDir'" | Out-Null
$result = & $SCP -O -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" $LocalPath "${NAS_USER}@${NAS_IP}:$RemotePath" 2>&1
if ($LASTEXITCODE -ne 0) {
$errorMsg = $result | Out-String
Write-Log " SCP PUSH ERROR (exit $LASTEXITCODE): $errorMsg"
}
return $LASTEXITCODE -eq 0
}
function Get-FileHash256 {
param([string]$FilePath)
if (Test-Path $FilePath) {
return (Get-FileHash -Path $FilePath -Algorithm SHA256).Hash
}
return $null
}
function Import-ToDatabase {
param([string[]]$FilePaths)
if ($FilePaths.Count -eq 0) { return }
Write-Log "Importing $($FilePaths.Count) file(s) to database..."
# Build argument list
$args = @("$IMPORT_SCRIPT", "--file") + $FilePaths
try {
$output = & $NODE_PATH $args 2>&1
foreach ($line in $output) {
Write-Log " [DB] $line"
}
Write-Log "Database import complete"
} catch {
Write-Log "ERROR: Database import failed: $_"
}
}
# ============================================================================
# Main Script
# ============================================================================
Write-Log "=========================================="
Write-Log "Starting sync from NAS"
Write-Log "Max age: $MaxAgeMinutes minutes"
if ($DryRun) { Write-Log "DRY RUN - no changes will be made" }
$errorCount = 0
$syncedFiles = 0
$skippedFiles = 0
$syncedDatFiles = @() # Track DAT files for database import
# Find all DAT files on NAS modified within the time window
Write-Log "Finding DAT files on NAS..."
$findCommand = "find $NAS_DATA_PATH/TS-*/LOGS -name '*.DAT' -type f -mmin -$MaxAgeMinutes 2>/dev/null"
$datFiles = Invoke-NASCommand $findCommand
if (-not $datFiles -or $datFiles.Count -eq 0) {
Write-Log "No new DAT files found on NAS"
} else {
Write-Log "Found $($datFiles.Count) DAT file(s) to process"
foreach ($remoteFile in $datFiles) {
$remoteFile = $remoteFile.Trim()
if ([string]::IsNullOrWhiteSpace($remoteFile)) { continue }
# Parse the path: /data/test/TS-XX/LOGS/7BLOG/file.DAT
if ($remoteFile -match "/data/test/(TS-[^/]+)/LOGS/([^/]+)/(.+\.DAT)$") {
$station = $Matches[1]
$logType = $Matches[2]
$fileName = $Matches[3]
Write-Log "Processing: $station/$logType/$fileName"
# Destination 1: Per-station folder (preserves structure)
$stationDest = Join-Path $AD2_TEST_PATH "$station\LOGS\$logType\$fileName"
# Destination 2: Aggregated HISTLOGS folder
$histlogsDest = Join-Path $AD2_HISTLOGS_PATH "$logType\$fileName"
if ($DryRun) {
Write-Log " [DRY RUN] Would copy to: $stationDest"
$syncedFiles++
} else {
# Copy to station folder only (skip HISTLOGS to avoid duplicates)
$success1 = Copy-FromNAS -RemotePath $remoteFile -LocalPath $stationDest
if ($success1) {
Write-Log " Copied to station folder"
# Remove from NAS after successful sync
Remove-FromNAS -RemotePath $remoteFile
Write-Log " Removed from NAS"
# Track for database import
$syncedDatFiles += $stationDest
$syncedFiles++
} else {
Write-Log " ERROR: Failed to copy from NAS"
$errorCount++
}
}
} else {
Write-Log " Skipping (unexpected path format): $remoteFile"
$skippedFiles++
}
}
}
# Find and sync TXT report files
Write-Log "Finding TXT reports on NAS..."
$findReportsCommand = "find $NAS_DATA_PATH/TS-*/Reports -name '*.TXT' -type f -mmin -$MaxAgeMinutes 2>/dev/null"
$txtFiles = Invoke-NASCommand $findReportsCommand
if ($txtFiles -and $txtFiles.Count -gt 0) {
Write-Log "Found $($txtFiles.Count) TXT report(s) to process"
foreach ($remoteFile in $txtFiles) {
$remoteFile = $remoteFile.Trim()
if ([string]::IsNullOrWhiteSpace($remoteFile)) { continue }
if ($remoteFile -match "/data/test/(TS-[^/]+)/Reports/(.+\.TXT)$") {
$station = $Matches[1]
$fileName = $Matches[2]
Write-Log "Processing report: $station/$fileName"
# Destination: Per-station Reports folder
$reportDest = Join-Path $AD2_TEST_PATH "$station\Reports\$fileName"
if ($DryRun) {
Write-Log " [DRY RUN] Would copy to: $reportDest"
$syncedFiles++
} else {
$success = Copy-FromNAS -RemotePath $remoteFile -LocalPath $reportDest
if ($success) {
Write-Log " Copied report"
Remove-FromNAS -RemotePath $remoteFile
Write-Log " Removed from NAS"
$syncedFiles++
} else {
Write-Log " ERROR: Failed to copy report"
$errorCount++
}
}
}
}
}
# ============================================================================
# Import synced DAT files to database
# ============================================================================
if (-not $DryRun -and $syncedDatFiles.Count -gt 0) {
Import-ToDatabase -FilePaths $syncedDatFiles
}
# ============================================================================
# PUSH: AD2 → NAS (Software Updates for DOS Machines)
# ============================================================================
Write-Log "--- AD2 to NAS Sync (Software Updates) ---"
$pushedFiles = 0
# Sync COMMON/ProdSW (batch files for all stations)
# AD2 uses _COMMON, NAS uses COMMON - handle both
$commonSources = @(
@{ Local = "$AD2_TEST_PATH\_COMMON\ProdSW"; Remote = "$NAS_DATA_PATH/COMMON/ProdSW" },
@{ Local = "$AD2_TEST_PATH\COMMON\ProdSW"; Remote = "$NAS_DATA_PATH/COMMON/ProdSW" }
)
foreach ($source in $commonSources) {
if (Test-Path $source.Local) {
Write-Log "Syncing COMMON ProdSW from: $($source.Local)"
$commonFiles = Get-ChildItem -Path $source.Local -File -ErrorAction SilentlyContinue
foreach ($file in $commonFiles) {
$remotePath = "$($source.Remote)/$($file.Name)"
if ($DryRun) {
Write-Log " [DRY RUN] Would push: $($file.Name) -> $remotePath"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $file.FullName -RemotePath $remotePath
if ($success) {
Write-Log " Pushed: $($file.Name)"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push $($file.Name)"
$errorCount++
}
}
}
}
}
# Sync UPDATE.BAT (root level utility)
Write-Log "Syncing UPDATE.BAT..."
$updateBatLocal = "$AD2_TEST_PATH\UPDATE.BAT"
if (Test-Path $updateBatLocal) {
$updateBatRemote = "$NAS_DATA_PATH/UPDATE.BAT"
if ($DryRun) {
Write-Log " [DRY RUN] Would push: UPDATE.BAT -> $updateBatRemote"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $updateBatLocal -RemotePath $updateBatRemote
if ($success) {
Write-Log " Pushed: UPDATE.BAT"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push UPDATE.BAT"
$errorCount++
}
}
} else {
Write-Log " WARNING: UPDATE.BAT not found at $updateBatLocal"
}
# Sync DEPLOY.BAT (root level utility)
Write-Log "Syncing DEPLOY.BAT..."
$deployBatLocal = "$AD2_TEST_PATH\DEPLOY.BAT"
if (Test-Path $deployBatLocal) {
$deployBatRemote = "$NAS_DATA_PATH/DEPLOY.BAT"
if ($DryRun) {
Write-Log " [DRY RUN] Would push: DEPLOY.BAT -> $deployBatRemote"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $deployBatLocal -RemotePath $deployBatRemote
if ($success) {
Write-Log " Pushed: DEPLOY.BAT"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push DEPLOY.BAT"
$errorCount++
}
}
} else {
Write-Log " WARNING: DEPLOY.BAT not found at $deployBatLocal"
}
# Sync per-station ProdSW folders
Write-Log "Syncing station-specific ProdSW folders..."
$stationFolders = Get-ChildItem -Path $AD2_TEST_PATH -Directory -Filter "TS-*" -ErrorAction SilentlyContinue
foreach ($station in $stationFolders) {
$prodSwPath = Join-Path $station.FullName "ProdSW"
if (Test-Path $prodSwPath) {
# Get all files in ProdSW (including subdirectories)
$prodSwFiles = Get-ChildItem -Path $prodSwPath -File -Recurse -ErrorAction SilentlyContinue
foreach ($file in $prodSwFiles) {
# Calculate relative path from ProdSW folder
$relativePath = $file.FullName.Substring($prodSwPath.Length + 1).Replace('\', '/')
$remotePath = "$NAS_DATA_PATH/$($station.Name)/ProdSW/$relativePath"
if ($DryRun) {
Write-Log " [DRY RUN] Would push: $($station.Name)/ProdSW/$relativePath"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $file.FullName -RemotePath $remotePath
if ($success) {
Write-Log " Pushed: $($station.Name)/ProdSW/$relativePath"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push $($station.Name)/ProdSW/$relativePath"
$errorCount++
}
}
}
}
# Check for TODO.BAT (one-time task file)
$todoBatPath = Join-Path $station.FullName "TODO.BAT"
if (Test-Path $todoBatPath) {
$remoteTodoPath = "$NAS_DATA_PATH/$($station.Name)/TODO.BAT"
Write-Log "Found TODO.BAT for $($station.Name)"
if ($DryRun) {
Write-Log " [DRY RUN] Would push TODO.BAT -> $remoteTodoPath"
$pushedFiles++
} else {
$success = Copy-ToNAS -LocalPath $todoBatPath -RemotePath $remoteTodoPath
if ($success) {
Write-Log " Pushed TODO.BAT to NAS"
# Remove from AD2 after successful push (one-shot mechanism)
Remove-Item -Path $todoBatPath -Force
Write-Log " Removed TODO.BAT from AD2 (pushed to NAS)"
$pushedFiles++
} else {
Write-Log " ERROR: Failed to push TODO.BAT"
$errorCount++
}
}
}
}
Write-Log "AD2 to NAS sync: $pushedFiles file(s) pushed"
# ============================================================================
# Update Status File
# ============================================================================
$status = if ($errorCount -eq 0) { "OK" } else { "ERRORS" }
$statusContent = @"
AD2 <-> NAS Bidirectional Sync Status
======================================
Timestamp: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Status: $status
PULL (NAS -> AD2 - Test Results):
Files Pulled: $syncedFiles
Files Skipped: $skippedFiles
DAT Files Imported to DB: $($syncedDatFiles.Count)
PUSH (AD2 -> NAS - Software Updates):
Files Pushed: $pushedFiles
Errors: $errorCount
"@
Set-Content -Path $STATUS_FILE -Value $statusContent
Write-Log "=========================================="
Write-Log "Sync complete: PULL=$syncedFiles, PUSH=$pushedFiles, Errors=$errorCount"
Write-Log "=========================================="
# Exit with error code if there were failures
if ($errorCount -gt 0) {
exit 1
} else {
exit 0
}

View File

@@ -0,0 +1,69 @@
# Test SMTP Authentication for notifications@dataforth.com
# This script tests SMTP authentication to verify credentials work
param(
[string]$Password = $(Read-Host -Prompt "Enter password for notifications@dataforth.com" -AsSecureString | ConvertFrom-SecureString)
)
$SMTPServer = "smtp.office365.com"
$SMTPPort = 587
$Username = "notifications@dataforth.com"
Write-Host "[OK] Testing SMTP authentication..." -ForegroundColor Green
Write-Host " Server: $SMTPServer"
Write-Host " Port: $SMTPPort"
Write-Host " Username: $Username"
Write-Host ""
try {
# Create secure password
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($Username, $SecurePassword)
# Create SMTP client
$SMTPClient = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = $Credential
# Create test message
$MailMessage = New-Object System.Net.Mail.MailMessage
$MailMessage.From = $Username
$MailMessage.To.Add($Username)
$MailMessage.Subject = "SMTP Test - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$MailMessage.Body = "This is a test message to verify SMTP authentication."
Write-Host "[OK] Sending test email..." -ForegroundColor Green
$SMTPClient.Send($MailMessage)
Write-Host "[SUCCESS] SMTP authentication successful!" -ForegroundColor Green
Write-Host " Test email sent successfully." -ForegroundColor Green
Write-Host ""
Write-Host "[OK] The credentials work correctly." -ForegroundColor Green
Write-Host " If the website is still failing, check:" -ForegroundColor Yellow
Write-Host " - Website SMTP configuration" -ForegroundColor Yellow
Write-Host " - Firewall rules blocking port 587" -ForegroundColor Yellow
Write-Host " - IP address restrictions in M365" -ForegroundColor Yellow
} catch {
Write-Host "[ERROR] SMTP authentication failed!" -ForegroundColor Red
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor Red
Write-Host ""
if ($_.Exception.Message -like "*authentication*") {
Write-Host "[ISSUE] Authentication credentials are incorrect" -ForegroundColor Yellow
Write-Host " - Verify the password is correct" -ForegroundColor Yellow
Write-Host " - Check if MFA requires an app password" -ForegroundColor Yellow
} elseif ($_.Exception.Message -like "*5.7.57*") {
Write-Host "[ISSUE] SMTP AUTH is disabled for this tenant or user" -ForegroundColor Yellow
Write-Host " Run: Set-CASMailbox -Identity notifications@dataforth.com -SmtpClientAuthenticationDisabled `$false" -ForegroundColor Yellow
} elseif ($_.Exception.Message -like "*connection*") {
Write-Host "[ISSUE] Connection problem" -ForegroundColor Yellow
Write-Host " - Check firewall rules" -ForegroundColor Yellow
Write-Host " - Verify port 587 is accessible" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "================================================================"
Write-Host "Next: Check Exchange Online logs for more details"
Write-Host "================================================================"

View File

@@ -0,0 +1,34 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..."
try {
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Mounted as AD2: drive"
Write-Host "`n[OK] Listing root directories..."
Get-ChildItem AD2:\ -Directory | Where-Object Name -match "database|testdata|test.*db" | Format-Table Name, FullName
Write-Host "`n[OK] Reading Sync-FromNAS.ps1..."
if (Test-Path "AD2:\Shares\test\scripts\Sync-FromNAS.ps1") {
$scriptContent = Get-Content "AD2:\Shares\test\scripts\Sync-FromNAS.ps1" -Raw
$scriptContent | Out-File -FilePath "D:\ClaudeTools\Sync-FromNAS-retrieved.ps1" -Encoding UTF8
Write-Host "[OK] Script retrieved and saved"
Write-Host "`n[INFO] Searching for database references in script..."
$scriptContent | Select-String -Pattern "(database|sql|sqlite|mysql|postgres|\.db|\.mdb|\.accdb)" -AllMatches | Select-Object -First 20
} else {
Write-Host "[ERROR] Sync-FromNAS.ps1 not found"
}
Write-Host "`n[OK] Checking for database files in Shares\test..."
Get-ChildItem "AD2:\Shares\test" -Recurse -Include "*.db","*.mdb","*.accdb","*.sqlite" -ErrorAction SilentlyContinue | Select-Object -First 10 | Format-Table Name, FullName
} catch {
Write-Host "[ERROR] Failed to mount share: $_"
} finally {
if (Test-Path AD2:) {
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Unmounted AD2 drive"
}
}

View File

@@ -0,0 +1,14 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Adding AD2 SSH Key to NAS..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Getting public key from AD2..." -ForegroundColor Yellow
$pubKey = Get-Content "$env:USERPROFILE\.ssh\id_ed25519.pub"
Write-Host " Key: $($pubKey.Substring(0, 60))..." -ForegroundColor Gray
# Return the key to the main script
return $pubKey
}

View File

@@ -0,0 +1,77 @@
# Add AD2 sync key to NAS using WinRM through AD2
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Adding AD2 Public Key to NAS ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$pubKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP8rc4OBRmMvpXa4UC7D9vtRbGQn19CXCc/IW50fnyCV AD2-NAS-Sync"
$nasIP = "192.168.0.9"
Write-Host "[1] Using plink to add key to NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Use existing plink with password to add the key
$plinkPath = "C:\Program Files\PuTTY\plink.exe"
# Create authorized_keys directory and add key
$commands = @(
"mkdir -p ~/.ssh",
"chmod 700 ~/.ssh",
"echo '$pubKey' >> ~/.ssh/authorized_keys",
"chmod 600 ~/.ssh/authorized_keys",
"echo '[OK] Key added successfully'",
"tail -1 ~/.ssh/authorized_keys"
)
foreach ($cmd in $commands) {
Write-Host " Running: $cmd" -ForegroundColor Gray
# Note: This uses the existing plink setup with stored credentials
& $plinkPath -batch root@$nasIP $cmd 2>&1
}
Write-Host ""
Write-Host "[2] Testing key-based authentication" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$sshPath = "C:\Program Files\OpenSSH\ssh.exe"
$keyPath = "C:\Shares\test\scripts\.ssh\id_ed25519_nas"
# Test connection with key
$testResult = & $sshPath -i $keyPath -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=C:\Shares\test\scripts\.ssh\known_hosts root@$nasIP "echo '[SUCCESS] Key authentication working!' && hostname" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "[SUCCESS] SSH key authentication working!" -ForegroundColor Green
Write-Host $testResult -ForegroundColor White
} else {
Write-Host "[ERROR] Key authentication failed" -ForegroundColor Red
Write-Host $testResult -ForegroundColor Red
}
Write-Host ""
Write-Host "[3] Testing SCP transfer with key" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Create test file
$testFile = "C:\Shares\test\scripts\openssh-test-$(Get-Date -Format 'HHmmss').txt"
"OpenSSH SCP Test - $(Get-Date)" | Out-File -FilePath $testFile -Encoding ASCII
$scpPath = "C:\Program Files\OpenSSH\scp.exe"
# Test SCP with verbose output
$scpResult = & $scpPath -v -i $keyPath -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=C:\Shares\test\scripts\.ssh\known_hosts $testFile root@${nasIP}:/data/test/scripts/ 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "[SUCCESS] SCP transfer with key authentication working!" -ForegroundColor Green
# Clean up test file
Remove-Item -Path $testFile -Force
} else {
Write-Host "[ERROR] SCP transfer failed" -ForegroundColor Red
Write-Host "Error output:" -ForegroundColor Red
$scpResult | ForEach-Object { Write-Host " $_" -ForegroundColor Red }
}
}
Write-Host ""
Write-Host "=== Key Setup Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,53 @@
# Check DEPLOY.BAT and UPDATE.BAT on AD2
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "[INFO] Connecting to AD2..."
New-PSDrive -Name TEMP_AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $Cred -ErrorAction Stop | Out-Null
Write-Host "[INFO] Checking DEPLOY.BAT and UPDATE.BAT..."
Write-Host ""
$DeployFile = Get-Item "TEMP_AD2:\Shares\test\DEPLOY.BAT" -ErrorAction SilentlyContinue
$UpdateFile = Get-Item "TEMP_AD2:\Shares\test\UPDATE.BAT" -ErrorAction SilentlyContinue
if ($DeployFile) {
Write-Host "[OK] DEPLOY.BAT found on AD2"
Write-Host " Last Modified: $($DeployFile.LastWriteTime)"
Write-Host " Size: $($DeployFile.Length) bytes"
# Check line endings
$Content = Get-Content "TEMP_AD2:\Shares\test\DEPLOY.BAT" -Raw
if ($Content -match "`r`n") {
Write-Host " Line Endings: CRLF (DOS-compatible) [OK]"
} elseif ($Content -match "`n") {
Write-Host " Line Endings: LF only [WARNING]"
}
} else {
Write-Host "[ERROR] DEPLOY.BAT not found on AD2"
}
Write-Host ""
if ($UpdateFile) {
Write-Host "[OK] UPDATE.BAT found on AD2"
Write-Host " Last Modified: $($UpdateFile.LastWriteTime)"
Write-Host " Size: $($UpdateFile.Length) bytes"
# Check line endings
$Content = Get-Content "TEMP_AD2:\Shares\test\UPDATE.BAT" -Raw
if ($Content -match "`r`n") {
Write-Host " Line Endings: CRLF (DOS-compatible) [OK]"
} elseif ($Content -match "`n") {
Write-Host " Line Endings: LF only [WARNING]"
}
} else {
Write-Host "[ERROR] UPDATE.BAT not found on AD2"
}
Remove-PSDrive TEMP_AD2
Write-Host ""
Write-Host "[INFO] Note: Files sync to NAS every 15 minutes via AD2's scheduled task"

View File

@@ -0,0 +1,20 @@
# Check AD2 sync log to verify NAS sync status
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "[INFO] Connecting to AD2 to check sync log..."
try {
$LogContent = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\sync-from-nas.log' -Tail 30
}
Write-Host "[OK] Sync log retrieved:"
Write-Host ""
$LogContent | ForEach-Object { Write-Host $_ }
} catch {
Write-Host "[ERROR] Failed to connect to AD2: $_"
}

View File

@@ -0,0 +1,38 @@
# Verify BAT files are on the NAS
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Checking BAT Files on NAS ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$SSH = "C:\Program Files\OpenSSH\ssh.exe"
$NAS_IP = "192.168.0.9"
$NAS_USER = "admin"
Write-Host "[1] Listing root BAT files on NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$result = & $SSH -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" "${NAS_USER}@${NAS_IP}" "ls -lh /volume1/test/*.BAT 2>/dev/null" 2>&1
if ($LASTEXITCODE -eq 0) {
$result | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
} else {
Write-Host "[INFO] No BAT files found or connection issue" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[2] Listing COMMON/DOS files on NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$result = & $SSH -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" "${NAS_USER}@${NAS_IP}" "ls -lh /volume1/test/COMMON/DOS/*.BAT 2>/dev/null" 2>&1
if ($LASTEXITCODE -eq 0) {
$result | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
} else {
Write-Host "[INFO] No files in COMMON/DOS or directory doesn't exist" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "=== Check Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,30 @@
# Check for error logs on AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Checking for WAL files..." -ForegroundColor Green
$dbFolder = "AD2:\Shares\testdatadb\database"
$walFiles = Get-ChildItem $dbFolder -Filter "*.wal" -ErrorAction SilentlyContinue
$shmFiles = Get-ChildItem $dbFolder -Filter "*.shm" -ErrorAction SilentlyContinue
if ($walFiles -or $shmFiles) {
Write-Host "[FOUND] WAL files exist:" -ForegroundColor Green
$walFiles | ForEach-Object { Write-Host " $_" -ForegroundColor Cyan }
$shmFiles | ForEach-Object { Write-Host " $_" -ForegroundColor Cyan }
} else {
Write-Host "[INFO] No WAL files found" -ForegroundColor Yellow
}
Write-Host "`n[OK] Checking deployed api.js..." -ForegroundColor Green
$apiContent = Get-Content "AD2:\Shares\testdatadb\routes\api.js" -Raw
if ($apiContent -match "readonly: true" -and $apiContent -match "journal_mode = WAL") {
Write-Host "[ERROR] CONFLICT DETECTED!" -ForegroundColor Red
Write-Host " Cannot set WAL mode on readonly database!" -ForegroundColor Red
Write-Host " This is causing the database query errors" -ForegroundColor Red
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,69 @@
# Check database performance and optimization status
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
# Get server.js content to check timeout settings
Write-Host "[OK] Checking server.js configuration..." -ForegroundColor Green
$serverJs = Get-Content "AD2:\Shares\testdatadb\server.js" -Raw
if ($serverJs -match "timeout") {
Write-Host "[FOUND] Timeout configuration in server.js" -ForegroundColor Yellow
$serverJs -split "`n" | Where-Object { $_ -match "timeout" } | ForEach-Object {
Write-Host " $_" -ForegroundColor Cyan
}
} else {
Write-Host "[INFO] No explicit timeout configuration found" -ForegroundColor Cyan
}
# Check if better-sqlite3 is configured for performance
if ($serverJs -match "pragma") {
Write-Host "[FOUND] SQLite PRAGMA settings:" -ForegroundColor Green
$serverJs -split "`n" | Where-Object { $_ -match "pragma" } | ForEach-Object {
Write-Host " $_" -ForegroundColor Cyan
}
} else {
Write-Host "[WARNING] No PRAGMA performance settings found in server.js" -ForegroundColor Yellow
Write-Host " Consider adding: PRAGMA journal_mode = WAL, PRAGMA synchronous = NORMAL" -ForegroundColor Yellow
}
# Check routes/api.js for query optimization
Write-Host "`n[OK] Checking API routes..." -ForegroundColor Green
if (Test-Path "AD2:\Shares\testdatadb\routes\api.js") {
$apiJs = Get-Content "AD2:\Shares\testdatadb\routes\api.js" -Raw
# Check for LIMIT clauses
$hasLimit = $apiJs -match "LIMIT"
if ($hasLimit) {
Write-Host "[OK] Found LIMIT clauses in queries (good for performance)" -ForegroundColor Green
} else {
Write-Host "[WARNING] No LIMIT clauses found - queries may return too many results" -ForegroundColor Yellow
}
# Check for index usage
$hasIndexHints = $apiJs -match "INDEXED BY" -or $apiJs -match "USE INDEX"
if ($hasIndexHints) {
Write-Host "[OK] Found index hints in queries" -ForegroundColor Green
} else {
Write-Host "[INFO] No explicit index hints (relying on automatic optimization)" -ForegroundColor Cyan
}
}
# Check database file fragmentation
Write-Host "`n[OK] Checking database file stats..." -ForegroundColor Green
$dbFile = Get-Item "AD2:\Shares\testdatadb\database\testdata.db"
Write-Host " File size: $([math]::Round($dbFile.Length/1MB,2)) MB" -ForegroundColor Cyan
Write-Host " Last accessed: $($dbFile.LastAccessTime)" -ForegroundColor Cyan
Write-Host " Last modified: $($dbFile.LastWriteTime)" -ForegroundColor Cyan
# Suggestion to run VACUUM
$daysSinceModified = (Get-Date) - $dbFile.LastWriteTime
if ($daysSinceModified.TotalDays -gt 7) {
Write-Host "`n[SUGGESTION] Database hasn't been modified in $([math]::Round($daysSinceModified.TotalDays,1)) days" -ForegroundColor Yellow
Write-Host " Consider running VACUUM to optimize database file" -ForegroundColor Yellow
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,72 @@
# Check Node.js server status and database access on AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Checking Node.js server status..." -ForegroundColor Green
# Check if Node.js process is running
$nodeProcs = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Process node -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, StartTime, @{Name='Memory(MB)';Expression={[math]::Round($_.WorkingSet64/1MB,2)}}
}
if ($nodeProcs) {
Write-Host "[FOUND] Node.js process(es) running:" -ForegroundColor Green
$nodeProcs | Format-Table -AutoSize
} else {
Write-Host "[WARNING] No Node.js process found - server may not be running" -ForegroundColor Yellow
}
# Check database file
Write-Host "`n[OK] Checking database file..." -ForegroundColor Green
$dbInfo = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$dbPath = "C:\Shares\testdatadb\database\testdata.db"
if (Test-Path $dbPath) {
$file = Get-Item $dbPath
[PSCustomObject]@{
Exists = $true
Size = [math]::Round($file.Length/1MB,2)
LastWrite = $file.LastWriteTime
Readable = $true
}
} else {
[PSCustomObject]@{
Exists = $false
}
}
}
if ($dbInfo.Exists) {
Write-Host "[OK] Database file found" -ForegroundColor Green
Write-Host " Size: $($dbInfo.Size) MB" -ForegroundColor Cyan
Write-Host " Last Modified: $($dbInfo.LastWrite)" -ForegroundColor Cyan
} else {
Write-Host "[ERROR] Database file not found!" -ForegroundColor Red
}
# Check for server log file
Write-Host "`n[OK] Checking for server logs..." -ForegroundColor Green
$logs = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logPath = "C:\Shares\testdatadb\server.log"
if (Test-Path $logPath) {
Get-Content $logPath -Tail 20
} else {
Write-Output "[INFO] No server.log file found"
}
}
if ($logs) {
Write-Host "[OK] Recent server logs:" -ForegroundColor Green
$logs | ForEach-Object { Write-Host " $_" }
}
# Try to test port 3000
Write-Host "`n[OK] Testing port 3000..." -ForegroundColor Green
$portTest = Test-NetConnection -ComputerName 192.168.0.6 -Port 3000 -WarningAction SilentlyContinue
if ($portTest.TcpTestSucceeded) {
Write-Host "[OK] Port 3000 is open and accessible" -ForegroundColor Green
} else {
Write-Host "[ERROR] Port 3000 is not accessible - server may not be running" -ForegroundColor Red
}
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,77 @@
# Simple check of database server via SMB
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Checking database file..." -ForegroundColor Green
$dbPath = "AD2:\Shares\testdatadb\database\testdata.db"
if (Test-Path $dbPath) {
$dbFile = Get-Item $dbPath
Write-Host "[OK] Database file exists" -ForegroundColor Green
Write-Host " Size: $([math]::Round($dbFile.Length/1MB,2)) MB" -ForegroundColor Cyan
Write-Host " Last Modified: $($dbFile.LastWriteTime)" -ForegroundColor Cyan
# Check if file is locked
try {
$stream = [System.IO.File]::Open($dbFile.FullName, 'Open', 'Read', 'Read')
$stream.Close()
Write-Host " [OK] Database file is accessible (not locked)" -ForegroundColor Green
} catch {
Write-Host " [WARNING] Database file may be locked: $($_.Exception.Message)" -ForegroundColor Yellow
}
} else {
Write-Host "[ERROR] Database file not found!" -ForegroundColor Red
}
# Check server.js file
Write-Host "`n[OK] Checking server files..." -ForegroundColor Green
$serverPath = "AD2:\Shares\testdatadb\server.js"
if (Test-Path $serverPath) {
Write-Host "[OK] server.js exists" -ForegroundColor Green
} else {
Write-Host "[ERROR] server.js not found!" -ForegroundColor Red
}
# Check package.json
$packagePath = "AD2:\Shares\testdatadb\package.json"
if (Test-Path $packagePath) {
Write-Host "[OK] package.json exists" -ForegroundColor Green
$package = Get-Content $packagePath -Raw | ConvertFrom-Json
Write-Host " Dependencies:" -ForegroundColor Cyan
$package.dependencies.PSObject.Properties | ForEach-Object {
Write-Host " - $($_.Name): $($_.Value)" -ForegroundColor Cyan
}
}
# Check for any error log files
Write-Host "`n[OK] Checking for error logs..." -ForegroundColor Green
$logFiles = Get-ChildItem "AD2:\Shares\testdatadb\*.log" -ErrorAction SilentlyContinue
if ($logFiles) {
Write-Host "[FOUND] Log files:" -ForegroundColor Green
$logFiles | ForEach-Object {
Write-Host " $($_.Name) - $([math]::Round($_.Length/1KB,2)) KB - Modified: $($_.LastWriteTime)" -ForegroundColor Cyan
if ($_.Length -lt 10KB) {
Write-Host " Last 10 lines:" -ForegroundColor Yellow
Get-Content $_.FullName -Tail 10 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}
}
} else {
Write-Host "[INFO] No log files found" -ForegroundColor Cyan
}
# Test port 3000
Write-Host "`n[OK] Testing port 3000 connectivity..." -ForegroundColor Green
$portTest = Test-NetConnection -ComputerName 192.168.0.6 -Port 3000 -WarningAction SilentlyContinue -InformationLevel Quiet
if ($portTest) {
Write-Host "[OK] Port 3000 is OPEN" -ForegroundColor Green
} else {
Write-Host "[ERROR] Port 3000 is CLOSED - Server not running or firewall blocking" -ForegroundColor Red
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,74 @@
# Comprehensive DOS 6.22 compatibility checker
# Scans all BAT files for incompatible commands
$BATFiles = Get-ChildItem *.BAT | Where-Object { $_.Name -notlike "*_FROM_*" -and $_.Name -notlike "*_TEST*" -and $_.Name -notlike "*_VERIFY*" -and $_.Name -notlike "*_CHECK*" -and $_.Name -notlike "*_MONITOR*" }
Write-Host "========================================" -ForegroundColor Red
Write-Host "DOS 6.22 COMPATIBILITY CHECK" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
Write-Host ""
$TotalIssues = 0
# DOS 6.22 INCOMPATIBLE patterns
$IncompatiblePatterns = @(
@{Pattern='SET\s+/P'; Description='SET /P (interactive input) - NOT in DOS 6.22'},
@{Pattern='SET\s+/A'; Description='SET /A (arithmetic) - NOT in DOS 6.22'},
@{Pattern='IF\s+/I'; Description='IF /I (case-insensitive) - NOT in DOS 6.22'},
@{Pattern='FOR\s+/F'; Description='FOR /F (parse files) - NOT in DOS 6.22'},
@{Pattern='FOR\s+/L'; Description='FOR /L (loop) - NOT in DOS 6.22'},
@{Pattern='FOR\s+/D'; Description='FOR /D (directories) - NOT in DOS 6.22'},
@{Pattern='FOR\s+/R'; Description='FOR /R (recursive) - NOT in DOS 6.22'},
@{Pattern='GOTO\s+:EOF'; Description='GOTO :EOF - NOT in DOS 6.22 (use GOTO END)'},
@{Pattern='%COMPUTERNAME%'; Description='%COMPUTERNAME% - NOT in DOS 6.22'},
@{Pattern='%USERNAME%'; Description='%USERNAME% - NOT in DOS 6.22'},
@{Pattern='%USERPROFILE%'; Description='%USERPROFILE% - NOT in DOS 6.22'},
@{Pattern='&&'; Description='&& operator - NOT in DOS 6.22'},
@{Pattern='\|\|'; Description='|| operator - NOT in DOS 6.22'},
@{Pattern='\\NUL(?!\s|$)'; Description='\NUL as filename - INVALID (use \*.* for directory test)'},
@{Pattern='XCOPY.*\/Q'; Description='XCOPY /Q (quiet mode) - NOT in DOS 6.22'},
@{Pattern='IF.*\('; Description='IF ( ... ) multi-line blocks - NOT in DOS 6.22 (use GOTO labels)'},
@{Pattern='\)\s*ELSE\s*\('; Description=') ELSE ( clause - NOT in DOS 6.22 (use GOTO labels)'},
@{Pattern='^PAUSE\s+'; Description='PAUSE message - NOT in DOS 6.22 (use ECHO then PAUSE)'},
@{Pattern='\|.*\|.*>>'; Description='Double pipe with redirect (|..|..>>) - NOT reliable in DOS 6.22 (use temp files)'},
@{Pattern='CHOICE\s+/[A-Z]'; Description='CHOICE with options - Check if CHOICE.COM available'},
@{Pattern='START\s+'; Description='START command - NOT in DOS 6.22'}
)
foreach ($File in $BATFiles) {
Write-Host "Checking: $($File.Name)" -ForegroundColor Cyan
$Content = Get-Content $File.FullName
$FileIssues = 0
foreach ($Pattern in $IncompatiblePatterns) {
$LineNum = 0
foreach ($Line in $Content) {
$LineNum++
if ($Line -match $Pattern.Pattern) {
if ($FileIssues -eq 0) {
Write-Host ""
}
Write-Host " [ERROR] Line $LineNum : $($Pattern.Description)" -ForegroundColor Red
Write-Host " > $Line" -ForegroundColor Yellow
$FileIssues++
$TotalIssues++
}
}
}
if ($FileIssues -eq 0) {
Write-Host " [OK] No incompatibilities found" -ForegroundColor Green
}
Write-Host ""
}
Write-Host "========================================" -ForegroundColor Red
Write-Host "TOTAL ISSUES FOUND: $TotalIssues" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Red
if ($TotalIssues -gt 0) {
Write-Host ""
Write-Host "ACTION REQUIRED: Fix all incompatibilities before deployment" -ForegroundColor Red
}

View File

@@ -0,0 +1,86 @@
# Check and fix DOS line endings for batch files
Write-Host "=== Checking DOS Batch File Line Endings ===" -ForegroundColor Cyan
Write-Host ""
# Find all .bat files (excluding git/node_modules)
$batFiles = Get-ChildItem -Recurse -Filter "*.bat" | Where-Object {
$_.FullName -notlike "*\.git\*" -and
$_.FullName -notlike "*\node_modules\*"
}
Write-Host "Found $($batFiles.Count) batch files to check:" -ForegroundColor Yellow
Write-Host ""
$needsConversion = @()
foreach ($file in $batFiles) {
$bytes = [System.IO.File]::ReadAllBytes($file.FullName)
$hasCRLF = $false
$hasLF = $false
for ($i = 0; $i -lt $bytes.Length - 1; $i++) {
if ($bytes[$i] -eq 13 -and $bytes[$i+1] -eq 10) {
# Found CRLF (0x0D 0x0A)
$hasCRLF = $true
break
}
if ($bytes[$i] -eq 10 -and ($i -eq 0 -or $bytes[$i-1] -ne 13)) {
# Found LF without CR
$hasLF = $true
break
}
}
$relativePath = $file.FullName.Replace((Get-Location).Path + "\", "")
if ($hasCRLF) {
Write-Host "[OK] $relativePath" -ForegroundColor Green
Write-Host " CRLF (DOS format)" -ForegroundColor Gray
} elseif ($hasLF) {
Write-Host "[FAIL] $relativePath" -ForegroundColor Red
Write-Host " LF only (Unix format) - NEEDS CONVERSION" -ForegroundColor Red
$needsConversion += $file
} else {
Write-Host "[INFO] $relativePath" -ForegroundColor Yellow
Write-Host " No line endings detected (empty or single line)" -ForegroundColor Gray
}
Write-Host ""
}
if ($needsConversion.Count -gt 0) {
Write-Host "=== Files Needing Conversion: $($needsConversion.Count) ===" -ForegroundColor Red
Write-Host ""
foreach ($file in $needsConversion) {
Write-Host " - $($file.Name)" -ForegroundColor Red
}
Write-Host ""
Write-Host "Convert to DOS format? (Y/N)" -ForegroundColor Yellow
$response = Read-Host
if ($response -eq 'Y' -or $response -eq 'y') {
Write-Host ""
Write-Host "Converting files..." -ForegroundColor Yellow
foreach ($file in $needsConversion) {
try {
$content = Get-Content $file.FullName -Raw
$dosContent = $content -replace "`r?`n", "`r`n"
[System.IO.File]::WriteAllText($file.FullName, $dosContent, [System.Text.Encoding]::ASCII)
Write-Host " [OK] $($file.Name)" -ForegroundColor Green
} catch {
Write-Host " [ERROR] $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "=== Conversion Complete ===" -ForegroundColor Green
} else {
Write-Host ""
Write-Host "Conversion skipped." -ForegroundColor Yellow
}
} else {
Write-Host "=== All Files OK ===" -ForegroundColor Green
Write-Host "All batch files have proper DOS (CRLF) line endings." -ForegroundColor Green
}

View File

@@ -0,0 +1,50 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Checking COMMON vs _COMMON on AD2" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "=== Checking if _COMMON and COMMON are junctioned ===" -ForegroundColor Yellow
Write-Host ""
# Check _COMMON
$underCommon = Get-Item "C:\Shares\test\_COMMON" -Force
Write-Host "_COMMON:" -ForegroundColor Cyan
Write-Host " Type: $($underCommon.Attributes)" -ForegroundColor White
if ($underCommon.LinkType) {
Write-Host " LinkType: $($underCommon.LinkType)" -ForegroundColor Green
Write-Host " Target: $($underCommon.Target)" -ForegroundColor Green
} else {
Write-Host " LinkType: Not a link/junction" -ForegroundColor Yellow
}
Write-Host ""
# Check COMMON
$common = Get-Item "C:\Shares\test\COMMON" -Force
Write-Host "COMMON:" -ForegroundColor Cyan
Write-Host " Type: $($common.Attributes)" -ForegroundColor White
if ($common.LinkType) {
Write-Host " LinkType: $($common.LinkType)" -ForegroundColor Green
Write-Host " Target: $($common.Target)" -ForegroundColor Green
} else {
Write-Host " LinkType: Not a link/junction" -ForegroundColor Yellow
}
Write-Host ""
# Compare file counts
Write-Host "=== File Counts ===" -ForegroundColor Yellow
$underCount = (Get-ChildItem "C:\Shares\test\_COMMON\ProdSW" -File -ErrorAction SilentlyContinue | Measure-Object).Count
$commonCount = (Get-ChildItem "C:\Shares\test\COMMON\ProdSW" -File -ErrorAction SilentlyContinue | Measure-Object).Count
Write-Host "_COMMON\ProdSW: $underCount files" -ForegroundColor White
Write-Host "COMMON\ProdSW: $commonCount files" -ForegroundColor White
if ($underCount -ne $commonCount) {
Write-Host "WARNING: File counts differ!" -ForegroundColor Red
} else {
Write-Host "File counts match" -ForegroundColor Green
}
}

View File

@@ -0,0 +1,55 @@
# Check the absolute latest log entries for SCP PUSH ERROR messages
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "=== Latest Log Analysis ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "[1] Log file size and last modified" -ForegroundColor Yellow
$logInfo = Get-Item $logFile
Write-Host "Size: $([math]::Round($logInfo.Length / 1MB, 2)) MB" -ForegroundColor Gray
Write-Host "Last Modified: $($logInfo.LastWriteTime)" -ForegroundColor Gray
Write-Host ""
Write-Host "[2] Last 50 lines of log" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Get-Content $logFile -Tail 50 | ForEach-Object {
if ($_ -match "SCP PUSH ERROR|SCP ERROR") {
Write-Host $_ -ForegroundColor Red
} elseif ($_ -match "ERROR") {
Write-Host $_ -ForegroundColor Yellow
} elseif ($_ -match "Starting sync|Sync complete") {
Write-Host $_ -ForegroundColor Cyan
} else {
Write-Host $_ -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "[3] Searching entire log for 'SCP PUSH ERROR'" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$scpErrors = Get-Content $logFile | Select-String -Pattern "SCP PUSH ERROR"
if ($scpErrors) {
Write-Host "[SUCCESS] Found $($scpErrors.Count) detailed SCP error(s)!" -ForegroundColor Green
Write-Host ""
Write-Host "First 10 occurrences:" -ForegroundColor Cyan
$scpErrors | Select-Object -First 10 | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
} else {
Write-Host "[INFO] No 'SCP PUSH ERROR' messages found in entire log file" -ForegroundColor Yellow
Write-Host "This means either:" -ForegroundColor Gray
Write-Host " 1. No sync has run since the fix was applied" -ForegroundColor Gray
Write-Host " 2. No errors occurred (all files pushed successfully)" -ForegroundColor Gray
Write-Host " 3. The fix hasn't taken effect yet" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "=== Analysis Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,53 @@
# Check line endings in BAT files
Write-Host "[INFO] Checking line endings..."
Write-Host ""
# Check original
$Original = Get-Content "DEPLOY.BAT" -Raw
$HasCRLF_Original = $Original -match "`r`n"
$HasLF_Original = $Original -match "[^`r]`n"
Write-Host "DEPLOY.BAT (Original):"
if ($HasCRLF_Original) {
Write-Host " [OK] Contains CRLF (DOS-compatible)"
} elseif ($HasLF_Original) {
Write-Host " [WARNING] Contains LF only (Unix format)"
} else {
Write-Host " [UNKNOWN] No line breaks detected"
}
Write-Host ""
# Check NAS copy
if (Test-Path "DEPLOY_FROM_NAS.BAT") {
$FromNAS = Get-Content "DEPLOY_FROM_NAS.BAT" -Raw
$HasCRLF_NAS = $FromNAS -match "`r`n"
$HasLF_NAS = $FromNAS -match "[^`r]`n"
Write-Host "DEPLOY_FROM_NAS.BAT (From NAS):"
if ($HasCRLF_NAS) {
Write-Host " [OK] Contains CRLF (DOS-compatible)"
} elseif ($HasLF_NAS) {
Write-Host " [ERROR] Contains LF only (Unix format - DOS won't work!)"
} else {
Write-Host " [UNKNOWN] No line breaks detected"
}
# Compare file sizes
$OrigSize = (Get-Item "DEPLOY.BAT").Length
$NASSize = (Get-Item "DEPLOY_FROM_NAS.BAT").Length
Write-Host ""
Write-Host "File Sizes:"
Write-Host " Original: $OrigSize bytes"
Write-Host " From NAS: $NASSize bytes"
if ($OrigSize -ne $NASSize) {
Write-Host " [WARNING] Size mismatch - line endings may have been converted"
} else {
Write-Host " [OK] Sizes match"
}
} else {
Write-Host "[ERROR] DEPLOY_FROM_NAS.BAT not found"
}

View File

@@ -0,0 +1,89 @@
# Check for new test data files that need importing
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Test Data Import Status Check" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan
Write-Host "[1/4] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
# Check database last modified time
Write-Host "`n[2/4] Checking database status..." -ForegroundColor Green
$dbFile = Get-Item "AD2:\Shares\testdatadb\database\testdata.db"
Write-Host " Database last modified: $($dbFile.LastWriteTime)" -ForegroundColor Cyan
Write-Host " Database size: $([math]::Round($dbFile.Length/1MB,2)) MB" -ForegroundColor Cyan
# Check for new DAT files in test folders
Write-Host "`n[3/4] Checking for new test data files..." -ForegroundColor Green
$logTypes = @("8BLOG", "DSCLOG", "7BLOG", "5BLOG", "PWRLOG", "VASLOG", "SCTLOG", "HVLOG", "RMSLOG")
$testStations = @("TS-1L", "TS-3R", "TS-4L", "TS-4R", "TS-8R", "TS-10L", "TS-11L")
$newFiles = @()
$cutoffTime = $dbFile.LastWriteTime
foreach ($station in $testStations) {
foreach ($logType in $logTypes) {
$path = "AD2:\Shares\test\$station\LOGS\$logType"
if (Test-Path $path) {
$files = Get-ChildItem $path -Filter "*.DAT" -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt $cutoffTime }
if ($files) {
foreach ($file in $files) {
$newFiles += [PSCustomObject]@{
Station = $station
LogType = $logType
FileName = $file.Name
Size = [math]::Round($file.Length/1KB, 2)
Modified = $file.LastWriteTime
Path = $file.FullName
}
}
}
}
}
}
if ($newFiles.Count -gt 0) {
Write-Host " [FOUND] $($newFiles.Count) new files since last import:" -ForegroundColor Yellow
$newFiles | Format-Table Station, LogType, FileName, @{Name='Size(KB)';Expression={$_.Size}}, Modified -AutoSize | Out-String | Write-Host
} else {
Write-Host " [OK] No new files found - database is up to date" -ForegroundColor Green
}
# Check sync script log
Write-Host "`n[4/4] Checking sync log..." -ForegroundColor Green
$syncLog = "AD2:\Shares\test\scripts\sync-from-nas.log"
if (Test-Path $syncLog) {
Write-Host " [OK] Sync log exists" -ForegroundColor Green
$logFile = Get-Item $syncLog
Write-Host " Last modified: $($logFile.LastWriteTime)" -ForegroundColor Cyan
Write-Host " Last 10 log entries:" -ForegroundColor Cyan
$lastLines = Get-Content $syncLog -Tail 10
$lastLines | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
} else {
Write-Host " [WARNING] Sync log not found at: $syncLog" -ForegroundColor Yellow
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "Summary" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
if ($newFiles.Count -gt 0) {
Write-Host "[ACTION REQUIRED] Import new files:" -ForegroundColor Yellow
Write-Host " cd C:\Shares\testdatadb" -ForegroundColor Cyan
Write-Host " node database\import.js" -ForegroundColor Cyan
Write-Host "`n Or wait for automatic import (runs every 15 minutes)" -ForegroundColor Gray
} else {
Write-Host "[OK] Database is current - no import needed" -ForegroundColor Green
}
Write-Host "========================================`n" -ForegroundColor Cyan

View File

@@ -0,0 +1,101 @@
# Check if OpenSSH client is available on AD2
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Checking OpenSSH Client Availability ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] OpenSSH Client Installation Status" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Check if OpenSSH client is installed
$sshClient = Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Client*'
if ($sshClient) {
Write-Host "OpenSSH Client:" -ForegroundColor White
Write-Host " Name: $($sshClient.Name)" -ForegroundColor White
Write-Host " State: $($sshClient.State)" -ForegroundColor $(if ($sshClient.State -eq 'Installed') { "Green" } else { "Yellow" })
} else {
Write-Host "OpenSSH Client capability not found" -ForegroundColor Red
}
Write-Host ""
Write-Host "[2] Available SSH Commands" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Check for ssh.exe
$sshPath = Get-Command ssh.exe -ErrorAction SilentlyContinue
if ($sshPath) {
Write-Host "[OK] ssh.exe found: $($sshPath.Source)" -ForegroundColor Green
$sshVersion = & ssh.exe -V 2>&1
Write-Host " Version: $sshVersion" -ForegroundColor Gray
} else {
Write-Host "[MISSING] ssh.exe not found" -ForegroundColor Red
}
# Check for scp.exe
$scpPath = Get-Command scp.exe -ErrorAction SilentlyContinue
if ($scpPath) {
Write-Host "[OK] scp.exe found: $($scpPath.Source)" -ForegroundColor Green
} else {
Write-Host "[MISSING] scp.exe not found" -ForegroundColor Red
}
# Check for sftp.exe
$sftpPath = Get-Command sftp.exe -ErrorAction SilentlyContinue
if ($sftpPath) {
Write-Host "[OK] sftp.exe found: $($sftpPath.Source)" -ForegroundColor Green
} else {
Write-Host "[MISSING] sftp.exe not found" -ForegroundColor Red
}
Write-Host ""
Write-Host "[3] Current PuTTY Tools" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Check existing PuTTY tools
$pscpPath = "C:\Program Files\PuTTY\pscp.exe"
$plinkPath = "C:\Program Files\PuTTY\plink.exe"
if (Test-Path $pscpPath) {
Write-Host "[CURRENT] pscp.exe: $pscpPath" -ForegroundColor Cyan
$pscpVersion = & $pscpPath -V 2>&1 | Select-Object -First 1
Write-Host " $pscpVersion" -ForegroundColor Gray
}
if (Test-Path $plinkPath) {
Write-Host "[CURRENT] plink.exe: $plinkPath" -ForegroundColor Cyan
}
Write-Host ""
Write-Host "[4] Test SCP Transfer (if available)" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
if ($scpPath) {
# Create a test file
$testFile = "C:\Shares\test\scripts\openssh-test.txt"
"OpenSSH SCP Test - $(Get-Date)" | Out-File -FilePath $testFile -Encoding ASCII
Write-Host "Created test file: $testFile" -ForegroundColor White
Write-Host "Ready to test SCP transfer to NAS" -ForegroundColor Green
Write-Host ""
Write-Host "Test command would be:" -ForegroundColor Yellow
Write-Host " scp -v $testFile root@192.168.0.9:/data/test/scripts/" -ForegroundColor Gray
Write-Host ""
Write-Host "Benefits vs PuTTY pscp:" -ForegroundColor Cyan
Write-Host " - Native error messages" -ForegroundColor White
Write-Host " - SSH key support (no passwords in scripts)" -ForegroundColor White
Write-Host " - Verbose logging with -v flag" -ForegroundColor White
Write-Host " - Better batch mode handling" -ForegroundColor White
Write-Host " - StrictHostKeyChecking=accept-new (auto-accept on first connect)" -ForegroundColor White
} else {
Write-Host "OpenSSH client not available - would need to install" -ForegroundColor Red
Write-Host ""
Write-Host "Install command:" -ForegroundColor Yellow
Write-Host " Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "=== Check Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,33 @@
# Check for any remaining PLINK/PSCP references
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Checking for PLINK/PSCP References ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$content = Get-Content $scriptPath
Write-Host "[1] Scanning for PLINK references" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
for ($i = 0; $i -lt $content.Count; $i++) {
if ($content[$i] -match 'PLINK|PSCP' -and $content[$i] -notmatch '^\s*#') {
Write-Host "Line $($i+1): $($content[$i])" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "[2] Showing variable definitions" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
for ($i = 0; $i -lt $content.Count; $i++) {
if ($content[$i] -match '^\$SCP\s*=|^\$SSH\s*=|^\$PLINK\s*=|^\$PSCP\s*=') {
Write-Host "Line $($i+1): $($content[$i])" -ForegroundColor Cyan
}
}
}
Write-Host ""
Write-Host "=== Scan Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,15 @@
# Check PSCP usage in AD2 sync script
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "[INFO] Checking PSCP usage in Sync-FromNAS.ps1..."
$PSCPLines = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' | Select-String -Pattern 'pscp|plink' -Context 1
}
Write-Host ""
Write-Host "[INFO] PSCP/PLINK usage found:"
$PSCPLines | ForEach-Object { Write-Host $_ }

View File

@@ -0,0 +1,21 @@
# Check SCP command details in sync script
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "[INFO] Finding SCP commands in Sync-FromNAS.ps1..."
$SCPCommands = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' | Select-String -Pattern '\$SCP ' -Context 0
}
Write-Host ""
Write-Host "[INFO] SCP commands found:"
$SCPCommands | ForEach-Object { Write-Host $_ }
Write-Host ""
Write-Host "[INFO] Analysis:"
Write-Host "OpenSSH scp can convert line endings in text mode."
Write-Host "Solution: Add -O flag to use legacy SCP protocol (binary mode)"
Write-Host "Or: Add -T flag to disable pseudo-terminal"

View File

@@ -0,0 +1,60 @@
# Check for detailed SCP error messages in the log
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "=== Checking for SCP Error Details ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "[1] Looking for 'SCP ERROR' messages in recent log" -ForegroundColor Yellow
$scpErrors = Get-Content $logFile -Tail 200 | Select-String -Pattern "SCP ERROR"
if ($scpErrors) {
Write-Host "[FOUND] $($scpErrors.Count) detailed SCP error(s):" -ForegroundColor Green
Write-Host "=" * 80 -ForegroundColor Gray
$scpErrors | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
} else {
Write-Host "[NOT FOUND] No 'SCP ERROR' messages in recent log" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[2] Checking for generic ERROR messages" -ForegroundColor Yellow
$genericErrors = Get-Content $logFile -Tail 100 | Select-String -Pattern "^\s*\d{4}-\d{2}-\d{2}.*ERROR: Failed to" | Select-Object -First 5
if ($genericErrors) {
Write-Host "[FOUND] Generic error messages (without details):" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$genericErrors | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
}
Write-Host ""
Write-Host "[3] Checking Copy-ToNAS function in script" -ForegroundColor Yellow
$scriptContent = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1" -Raw
if ($scriptContent -match 'function Copy-ToNAS') {
Write-Host "[INFO] Looking at Copy-ToNAS function..." -ForegroundColor Cyan
$lines = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$inFunction = $false
$lineNum = 0
foreach ($line in $lines) {
$lineNum++
if ($line -match 'function Copy-ToNAS') {
$inFunction = $true
}
if ($inFunction) {
Write-Host "Line $lineNum : $line" -ForegroundColor Gray
if ($line -match '^\}' -and $inFunction) {
break
}
}
}
}
}

View File

@@ -0,0 +1,59 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Checking SSH Configuration on AD2..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Checking private key..." -ForegroundColor Yellow
$keyFile = "$env:USERPROFILE\.ssh\id_ed25519"
if (Test-Path $keyFile) {
$keyContent = Get-Content $keyFile -Raw
if ($keyContent -match "ENCRYPTED") {
Write-Host " [WARNING] Private key is ENCRYPTED (requires passphrase)" -ForegroundColor Red
} else {
Write-Host " [OK] Private key appears to be unencrypted" -ForegroundColor Green
}
Write-Host " First line: $(($keyContent -split "`n")[0])" -ForegroundColor Gray
}
Write-Host ""
Write-Host "[2] Checking SSH config..." -ForegroundColor Yellow
$sshConfig = "$env:USERPROFILE\.ssh\config"
if (Test-Path $sshConfig) {
Write-Host " SSH config exists:" -ForegroundColor Green
Get-Content $sshConfig | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
} else {
Write-Host " No SSH config file" -ForegroundColor Gray
}
Write-Host ""
Write-Host "[3] Checking authorized_keys (what this machine authorizes)..." -ForegroundColor Yellow
$authKeys = "$env:USERPROFILE\.ssh\authorized_keys"
if (Test-Path $authKeys) {
$keyCount = (Get-Content $authKeys | Where-Object { $_ -notmatch "^#" -and $_ -ne "" }).Count
Write-Host " $keyCount authorized keys found" -ForegroundColor White
}
Write-Host ""
Write-Host "[4] Checking public key..." -ForegroundColor Yellow
$pubKey = "$env:USERPROFILE\.ssh\id_ed25519.pub"
if (Test-Path $pubKey) {
$pubContent = Get-Content $pubKey
Write-Host " Public key: $($pubContent.Substring(0, [Math]::Min(50, $pubContent.Length)))..." -ForegroundColor Gray
}
Write-Host ""
Write-Host "[5] Checking SSH agent..." -ForegroundColor Yellow
$sshAgent = Get-Service ssh-agent -ErrorAction SilentlyContinue
if ($sshAgent) {
Write-Host " SSH Agent service: $($sshAgent.Status)" -ForegroundColor $(if ($sshAgent.Status -eq "Running") { "Green" } else { "Yellow" })
} else {
Write-Host " SSH Agent service not found" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[6] Testing if key is loaded in agent..." -ForegroundColor Yellow
$sshAdd = & "C:\Program Files\OpenSSH\ssh-add.exe" -l 2>&1
Write-Host " ssh-add -l result: $sshAdd" -ForegroundColor Gray
}

View File

@@ -0,0 +1,17 @@
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "=== Recent Sync Activity ===" -ForegroundColor Cyan
Write-Host ""
Get-Content "C:\Shares\test\scripts\sync-from-nas.log" -Tail 50 | Where-Object {
$_ -match "\.BAT|Sync complete|Starting sync|pushed"
} | ForEach-Object {
if ($_ -match "\.BAT") {
Write-Host $_ -ForegroundColor Green
} else {
Write-Host $_ -ForegroundColor Cyan
}
}
}

View File

@@ -0,0 +1,50 @@
# Check the sync script implementation
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Analyzing Sync Script ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
Write-Host "[1] Script Push Implementation" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Find the push/pscp commands
$content = Get-Content $scriptPath
$inPushSection = $false
$lineNum = 0
foreach ($line in $content) {
$lineNum++
# Look for PUSH section or pscp commands
if ($line -match 'PUSH|pscp|Push files|Push File|ERROR.*push') {
Write-Host "$lineNum : $line" -ForegroundColor White
$inPushSection = $true
} elseif ($inPushSection -and $line.Trim() -eq "") {
$inPushSection = $false
} elseif ($inPushSection) {
Write-Host "$lineNum : $line" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "[2] Check for Failed File Patterns" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Check if one of the failing files exists on NAS
Write-Host "Attempting SSH to NAS to check file presence..." -ForegroundColor Yellow
# Try to connect to NAS and check
$nasCheck = & plink.exe -batch root@192.168.0.9 "ls -la /data/test/TS-11L/ProdSW/HVDATA/hvin.dat 2>&1" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "File EXISTS on NAS:" -ForegroundColor Green
Write-Host $nasCheck -ForegroundColor White
} else {
Write-Host "File check result:" -ForegroundColor Red
Write-Host $nasCheck -ForegroundColor Red
}
}

View File

@@ -0,0 +1,19 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "=== Sync Status File ===" -ForegroundColor Cyan
if (Test-Path "C:\Shares\test\_SYNC_STATUS.txt") {
Get-Content "C:\Shares\test\_SYNC_STATUS.txt"
} else {
Write-Host "Status file not found" -ForegroundColor Red
}
Write-Host ""
Write-Host "=== Last 30 lines of Sync Log ===" -ForegroundColor Cyan
if (Test-Path "C:\Shares\test\scripts\sync-from-nas.log") {
Get-Content "C:\Shares\test\scripts\sync-from-nas.log" | Select-Object -Last 30
} else {
Write-Host "Log file not found" -ForegroundColor Red
}
}

View File

@@ -0,0 +1,34 @@
# Check for and clean up WAL files
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Checking for WAL/SHM files..." -ForegroundColor Green
$dbFolder = "AD2:\Shares\testdatadb\database"
$walFile = Get-Item "$dbFolder\testdata.db-wal" -ErrorAction SilentlyContinue
$shmFile = Get-Item "$dbFolder\testdata.db-shm" -ErrorAction SilentlyContinue
if ($walFile) {
Write-Host "[FOUND] testdata.db-wal ($([math]::Round($walFile.Length/1KB,2)) KB)" -ForegroundColor Yellow
Write-Host "[ACTION] Delete this file? (Y/N)" -ForegroundColor Yellow
} else {
Write-Host "[OK] No WAL file found" -ForegroundColor Green
}
if ($shmFile) {
Write-Host "[FOUND] testdata.db-shm ($([math]::Round($shmFile.Length/1KB,2)) KB)" -ForegroundColor Yellow
} else {
Write-Host "[OK] No SHM file found" -ForegroundColor Green
}
# Check database file integrity
Write-Host "`n[OK] Checking database file..." -ForegroundColor Green
$dbFile = Get-Item "$dbFolder\testdata.db"
Write-Host " Size: $([math]::Round($dbFile.Length/1MB,2)) MB" -ForegroundColor Cyan
Write-Host " Modified: $($dbFile.LastWriteTime)" -ForegroundColor Cyan
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,49 @@
@echo off
REM Check if old database at 172.16.3.20 is accessible
echo ==========================================
echo Checking Old Database (Jupiter 172.16.3.20)
echo ==========================================
echo.
echo [1] Testing connectivity to Jupiter...
plink -batch guru@172.16.3.20 "echo 'Connected successfully'" 2>nul
if errorlevel 1 (
echo ERROR: Cannot connect to Jupiter ^(172.16.3.20^)
echo.
echo Possible issues:
echo - Server is down
echo - Network issue
echo - SSH not accessible
echo.
goto :end
)
echo Connected successfully
echo.
echo [2] Checking if MariaDB Docker container is running...
plink -batch guru@172.16.3.20 "docker ps --filter 'name=mariadb' --format '{{.Names}} - {{.Status}}'" 2>nul
echo.
echo [3] Checking database connectivity...
plink -batch guru@172.16.3.20 "docker exec mariadb mysql -u claudetools -pCT_e8fcd5a3952030a79ed6debae6c954ed -D claudetools -e \"SELECT VERSION();\" 2>/dev/null" 2>nul
if errorlevel 1 (
echo ERROR: Cannot connect to database
goto :end
)
echo.
echo [4] Checking for conversation_contexts data...
plink -batch guru@172.16.3.20 "docker exec mariadb mysql -u claudetools -pCT_e8fcd5a3952030a79ed6debae6c954ed -D claudetools -e \"SELECT COUNT(*) as context_count FROM conversation_contexts;\" 2>/dev/null" 2>nul
echo.
echo [5] Checking for other data...
plink -batch guru@172.16.3.20 "docker exec mariadb mysql -u claudetools -pCT_e8fcd5a3952030a79ed6debae6c954ed -D claudetools -e \"SELECT TABLE_NAME, TABLE_ROWS FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'claudetools' AND TABLE_ROWS > 0 ORDER BY TABLE_ROWS DESC LIMIT 10;\" 2>/dev/null" 2>nul
echo.
:end
echo ==========================================
echo Check Complete
echo ==========================================
pause

View File

@@ -0,0 +1,41 @@
# Convert all batch files to DOS format (CRLF) automatically
Write-Host "=== Converting Batch Files to DOS Format ===" -ForegroundColor Cyan
Write-Host ""
# Find all .bat files (excluding git/node_modules)
$batFiles = Get-ChildItem -Recurse -Filter "*.bat" | Where-Object {
$_.FullName -notlike "*\.git\*" -and
$_.FullName -notlike "*\node_modules\*"
}
Write-Host "Converting $($batFiles.Count) batch files..." -ForegroundColor Yellow
Write-Host ""
$converted = 0
$errors = 0
foreach ($file in $batFiles) {
try {
# Read file content
$content = Get-Content $file.FullName -Raw
# Normalize to DOS line endings (CRLF)
$dosContent = $content -replace "`r?`n", "`r`n"
# Write back with ASCII encoding (DOS compatible)
[System.IO.File]::WriteAllText($file.FullName, $dosContent, [System.Text.Encoding]::ASCII)
Write-Host "[OK] $($file.Name)" -ForegroundColor Green
$converted++
} catch {
Write-Host "[ERROR] $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
$errors++
}
}
Write-Host ""
Write-Host "=== Conversion Complete ===" -ForegroundColor Green
Write-Host "Converted: $converted files" -ForegroundColor Green
if ($errors -gt 0) {
Write-Host "Errors: $errors files" -ForegroundColor Red
}

View File

@@ -0,0 +1,10 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred | Out-Null
Copy-Item -Path "D:\ClaudeTools\install-from-temp.ps1" -Destination "AD2:\Temp\install-from-temp.ps1" -Force
Write-Host "[OK] Script copied to C:\Temp\install-from-temp.ps1"
Remove-PSDrive -Name AD2

View File

@@ -0,0 +1,19 @@
# Copy installation script to AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[INFO] Copying installation script to AD2..."
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred | Out-Null
Copy-Item -Path "D:\ClaudeTools\install-agent-on-ad2.ps1" -Destination "AD2:\Temp\install-agent-on-ad2.ps1" -Force
Write-Host "[OK] Script copied to C:\Temp\install-agent-on-ad2.ps1"
Remove-PSDrive -Name AD2
Write-Host ""
Write-Host "[INFO] Installation script is ready on AD2"
Write-Host "Please run the following on AD2 (as Administrator):"
Write-Host "powershell -ExecutionPolicy Bypass -File C:\Temp\install-agent-on-ad2.ps1"

View File

@@ -0,0 +1,46 @@
# Copy UPDATE.BAT and DEPLOY.BAT to AD2 root for sync
$Source = "D:\ClaudeTools"
$Destination = "\\192.168.0.6\C$\Shares\test"
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "Connecting to AD2..."
New-PSDrive -Name TEMP_AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $Cred | Out-Null
Write-Host "[OK] Connected to AD2"
Write-Host ""
# Copy UPDATE.BAT and DEPLOY.BAT to root of test
Write-Host "Copying UPDATE.BAT to AD2 root..."
Copy-Item "$Source\UPDATE.BAT" "TEMP_AD2:\Shares\test\UPDATE.BAT" -Force
Write-Host " [OK] UPDATE.BAT -> C:\Shares\test\UPDATE.BAT"
Write-Host "Copying DEPLOY.BAT to AD2 root..."
Copy-Item "$Source\DEPLOY.BAT" "TEMP_AD2:\Shares\test\DEPLOY.BAT" -Force
Write-Host " [OK] DEPLOY.BAT -> C:\Shares\test\DEPLOY.BAT"
# Verify files exist
Write-Host ""
Write-Host "Verifying files on AD2:"
if (Test-Path "TEMP_AD2:\Shares\test\UPDATE.BAT") {
$size = (Get-Item "TEMP_AD2:\Shares\test\UPDATE.BAT").Length
Write-Host " [OK] UPDATE.BAT exists ($size bytes)"
}
if (Test-Path "TEMP_AD2:\Shares\test\DEPLOY.BAT") {
$size = (Get-Item "TEMP_AD2:\Shares\test\DEPLOY.BAT").Length
Write-Host " [OK] DEPLOY.BAT exists ($size bytes)"
}
# Show last sync status
Write-Host ""
Write-Host "=========================================="
Write-Host "Last Sync Status:"
Write-Host "=========================================="
Get-Content "TEMP_AD2:\Shares\test\_SYNC_STATUS.txt"
Write-Host ""
Write-Host "[INFO] Files are now in place for next sync (runs every 15 minutes)"
Write-Host "[INFO] Next sync will push UPDATE.BAT and DEPLOY.BAT to NAS root (T:\)"
Remove-PSDrive TEMP_AD2

View File

@@ -0,0 +1,10 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred | Out-Null
Copy-Item -Path "D:\ClaudeTools\stop-and-install-agent.ps1" -Destination "AD2:\Temp\stop-and-install-agent.ps1" -Force
Write-Host "[OK] Updated script copied to C:\Temp\stop-and-install-agent.ps1"
Remove-PSDrive -Name AD2

View File

@@ -0,0 +1,71 @@
# Copy DOS batch files to AD2
# Destination: \\AD2\test\COMMON\ProdSW
$Source = "D:\ClaudeTools"
$Destination = "\\192.168.0.6\C$\Shares\test\COMMON\ProdSW"
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
# Files to copy
$Files = @(
"NWTOC.BAT",
"CTONW.BAT",
"UPDATE.BAT",
"STAGE.BAT",
"REBOOT.BAT",
"CHECKUPD.BAT",
"DEPLOY.BAT"
)
Write-Host "Connecting to AD2..."
# Test connection first
try {
New-PSDrive -Name TEMP_AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $Cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Connected to AD2 C$ share"
# Copy to both COMMON and _COMMON locations (sync script checks both)
$destinations = @(
"TEMP_AD2:\Shares\test\COMMON\ProdSW",
"TEMP_AD2:\Shares\test\_COMMON\ProdSW"
)
foreach ($destBase in $destinations) {
Write-Host ""
Write-Host "Checking: $destBase"
# Create directory if it doesn't exist
if (-not (Test-Path $destBase)) {
Write-Host " Creating directory: $destBase"
New-Item -ItemType Directory -Path $destBase -Force | Out-Null
}
Write-Host " [OK] Destination exists"
# Copy each file
foreach ($file in $Files) {
$sourcePath = Join-Path $Source $file
$destPath = Join-Path $destBase $file
if (Test-Path $sourcePath) {
Write-Host " Copying: $file"
Copy-Item -Path $sourcePath -Destination $destPath -Force
Write-Host " [OK] $file copied"
} else {
Write-Host " [ERROR] Source file not found: $sourcePath"
}
}
}
Write-Host ""
Write-Host "[SUCCESS] All files copied to AD2"
Write-Host "Files copied to both COMMON and _COMMON"
Write-Host "Files will sync to NAS within 15 minutes"
Remove-PSDrive TEMP_AD2
} catch {
Write-Host "[ERROR] Failed to connect to AD2: $_"
exit 1
}

View File

@@ -0,0 +1,100 @@
# Manually copy fixed BAT files from AD2 to NAS immediately
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Copying BAT Files to NAS ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$SCP = "C:\Program Files\OpenSSH\scp.exe"
$NAS_IP = "192.168.0.9"
$NAS_USER = "admin"
Write-Host "[1] Copying root-level BAT files to NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$rootFiles = @(
"DEPLOY.BAT",
"NWTOC.BAT",
"CTONW.BAT",
"UPDATE.BAT",
"STAGE.BAT",
"CHECKUPD.BAT",
"REBOOT.BAT",
"DOSTEST.BAT"
)
$successCount = 0
$errorCount = 0
foreach ($file in $rootFiles) {
$localPath = "C:\Shares\test\$file"
$remotePath = "/volume1/test/$file"
if (Test-Path $localPath) {
Write-Host "Copying $file..." -ForegroundColor Cyan
$result = & $SCP -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes $localPath "${NAS_USER}@${NAS_IP}:$remotePath" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] $file" -ForegroundColor Green
$successCount++
} else {
Write-Host " [ERROR] $file - $result" -ForegroundColor Red
$errorCount++
}
} else {
Write-Host " [SKIP] $file - not found" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "[2] Creating COMMON/DOS directory on NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# SSH to NAS and create directory
$SSH = "C:\Program Files\OpenSSH\ssh.exe"
$mkdirResult = & $SSH -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes "${NAS_USER}@${NAS_IP}" "mkdir -p /volume1/test/COMMON/DOS" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host "[OK] Directory created/verified" -ForegroundColor Green
} else {
Write-Host "[WARNING] Directory creation: $mkdirResult" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[3] Copying DOS system files to NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$dosFiles = @("AUTOEXEC.BAT", "STARTNET.BAT")
foreach ($file in $dosFiles) {
$localPath = "C:\Shares\test\COMMON\DOS\$file"
$remotePath = "/volume1/test/COMMON/DOS/$file"
if (Test-Path $localPath) {
Write-Host "Copying $file..." -ForegroundColor Cyan
$result = & $SCP -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="C:\Shares\test\scripts\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes $localPath "${NAS_USER}@${NAS_IP}:$remotePath" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] $file" -ForegroundColor Green
$successCount++
} else {
Write-Host " [ERROR] $file - $result" -ForegroundColor Red
$errorCount++
}
} else {
Write-Host " [SKIP] $file - not found" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host "Summary: $successCount successful, $errorCount errors" -ForegroundColor Cyan
}
Write-Host ""
Write-Host "=== Copy Complete ===" -ForegroundColor Cyan
Write-Host "[INFO] Files are now available on NAS at /volume1/test/" -ForegroundColor Green
Write-Host "[INFO] DOS machines can access via T:\ drive" -ForegroundColor Green

View File

@@ -0,0 +1,58 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Creating SSH wrapper script on AD2..." -ForegroundColor Cyan
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
# Create a local test script that will run SSH without PowerShell remoting overhead
$testScript = @'
@echo off
REM SSH Test Script - Run locally on AD2
echo Testing SSH from AD2 to NAS...
echo.
echo [1] Testing hostname...
C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=5 -o BatchMode=yes -o StrictHostKeyChecking=no root@192.168.0.9 "hostname"
if %ERRORLEVEL% EQU 0 (
echo [OK] SSH Works!
) else (
echo [ERROR] SSH Failed with exit code: %ERRORLEVEL%
)
echo.
echo [2] Testing find command...
C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=10 -o BatchMode=yes -o StrictHostKeyChecking=no root@192.168.0.9 "find /data/test/TS-4R/LOGS -name '*.DAT' -type f 2>/dev/null | head -3"
echo.
echo [3] Running sync script manually...
powershell.exe -ExecutionPolicy Bypass -File "C:\Shares\test\scripts\Sync-FromNAS.ps1"
'@
$scriptPath = "C:\Temp\test-ssh-local.bat"
New-Item -Path "C:\Temp" -ItemType Directory -Force | Out-Null
$testScript | Out-File -FilePath $scriptPath -Encoding ASCII -Force
Write-Host "[OK] Created test script at: $scriptPath" -ForegroundColor Green
Write-Host ""
Write-Host "Now running the script locally..." -ForegroundColor Yellow
# Run it using Task Scheduler to execute in local context
$action = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c $scriptPath > C:\Temp\ssh-test-output.txt 2>&1"
$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(5)
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "TestSSH-Temp" -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM" -Force | Out-Null
Write-Host "Waiting for task to complete..." -ForegroundColor Yellow
Start-Sleep -Seconds 15
if (Test-Path "C:\Temp\ssh-test-output.txt") {
Write-Host ""
Write-Host "========== OUTPUT ==========" -ForegroundColor Cyan
Get-Content "C:\Temp\ssh-test-output.txt"
Write-Host "=============================" -ForegroundColor Cyan
}
# Cleanup
Unregister-ScheduledTask -TaskName "TestSSH-Temp" -Confirm:$false -ErrorAction SilentlyContinue
}

View File

@@ -0,0 +1,14 @@
Dataforth Notifications Account Credentials
Generated: 2026-01-27 10:57:03
Username: notifications@dataforth.com
Password: %5cfI:G71)}=g4ZS
SMTP Configuration for Website:
- Server: smtp.office365.com
- Port: 587
- TLS: Yes
- Username: notifications@dataforth.com
- Password: %5cfI:G71)}=g4ZS
DO NOT COMMIT TO GIT OR SHARE PUBLICLY

View File

@@ -0,0 +1,101 @@
# AD2 Automation Demo
# Demonstrates efficient WinRM operations vs individual SSH commands
Write-Host "=== AD2 Automation Demo ===" -ForegroundColor Cyan
Write-Host "Using WinRM for efficient remote operations`n"
# Setup credentials (read-only service account)
$password = ConvertTo-SecureString "vG!UCAD>=#gIk}1A3=:{+DV3" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\ClaudeTools-ReadOnly", $password)
# Example 1: Get AD User Summary
Write-Host "[1] Active Directory User Summary" -ForegroundColor Yellow
try {
$userStats = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$allUsers = Get-ADUser -Filter * -Properties Enabled, LastLogonDate
@{
Total = $allUsers.Count
Enabled = ($allUsers | Where-Object Enabled -eq $true).Count
Disabled = ($allUsers | Where-Object Enabled -eq $false).Count
RecentLogin = ($allUsers | Where-Object { $_.LastLogonDate -gt (Get-Date).AddDays(-30) }).Count
}
}
Write-Host " Total Users: $($userStats.Total)" -ForegroundColor Green
Write-Host " Enabled: $($userStats.Enabled)" -ForegroundColor Green
Write-Host " Disabled: $($userStats.Disabled)" -ForegroundColor Green
Write-Host " Active (30 days): $($userStats.RecentLogin)" -ForegroundColor Green
} catch {
Write-Host " [ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
# Example 2: Get Computer Inventory
Write-Host "`n[2] Active Directory Computer Inventory" -ForegroundColor Yellow
try {
$computerStats = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$allComputers = Get-ADComputer -Filter * -Properties OperatingSystem, LastLogonDate
@{
Total = $allComputers.Count
Windows = ($allComputers | Where-Object { $_.OperatingSystem -like "*Windows*" }).Count
Servers = ($allComputers | Where-Object { $_.OperatingSystem -like "*Server*" }).Count
Active = ($allComputers | Where-Object { $_.LastLogonDate -gt (Get-Date).AddDays(-30) }).Count
}
}
Write-Host " Total Computers: $($computerStats.Total)" -ForegroundColor Green
Write-Host " Windows Systems: $($computerStats.Windows)" -ForegroundColor Green
Write-Host " Servers: $($computerStats.Servers)" -ForegroundColor Green
Write-Host " Active (30 days): $($computerStats.Active)" -ForegroundColor Green
} catch {
Write-Host " [ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
# Example 3: Check Sync Status
Write-Host "`n[3] Dataforth Sync Status" -ForegroundColor Yellow
try {
$syncStatus = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$statusFile = "C:\Shares\test\_SYNC_STATUS.txt"
if (Test-Path $statusFile) {
Get-Content $statusFile -Tail 5
} else {
"Status file not found"
}
}
Write-Host " Last Sync Status:" -ForegroundColor Green
$syncStatus | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
} catch {
Write-Host " [ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
# Example 4: List Recent Logs
Write-Host "`n[4] Recent Sync Logs" -ForegroundColor Yellow
try {
$logInfo = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
if (Test-Path $logFile) {
$file = Get-Item $logFile
@{
Size = [math]::Round($file.Length / 1KB, 2)
LastModified = $file.LastWriteTime
LastLines = (Get-Content $logFile -Tail 3)
}
} else {
@{ Error = "Log file not found" }
}
}
if ($logInfo.Error) {
Write-Host " [WARNING] $($logInfo.Error)" -ForegroundColor Yellow
} else {
Write-Host " Log Size: $($logInfo.Size) KB" -ForegroundColor Green
Write-Host " Last Modified: $($logInfo.LastModified)" -ForegroundColor Green
Write-Host " Recent Activity:" -ForegroundColor Green
$logInfo.LastLines | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}
} catch {
Write-Host " [ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host "`n=== Demo Complete ===" -ForegroundColor Cyan
Write-Host "All operations completed in a single WinRM session!" -ForegroundColor Green

View File

@@ -0,0 +1,69 @@
# Deploy GuruRMM Agent to AD2 (Simplified - No WinRM)
# This script just copies the binary - service management done manually
$ErrorActionPreference = "Stop"
Write-Host "[INFO] Starting GuruRMM agent deployment to AD2 (SMB only)..."
# Credentials
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
# Paths
$localBinary = "D:\ClaudeTools\projects\msp-tools\guru-rmm\agent\target\release\gururmm-agent.exe"
$remotePath = "\\192.168.0.6\C$\Program Files\GuruRMM"
$remoteAgent = "$remotePath\gururmm-agent.exe"
$remoteBackup = "$remotePath\gururmm-agent.exe.backup"
# Connect to AD2
Write-Host "[INFO] Connecting to AD2 via SMB..."
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred | Out-Null
Write-Host "[OK] Connected to AD2"
# Check if agent directory exists
if (Test-Path "AD2:\Program Files\GuruRMM") {
Write-Host "[OK] GuruRMM directory found"
} else {
Write-Host "[WARNING] GuruRMM directory not found - creating..."
New-Item -Path "AD2:\Program Files\GuruRMM" -ItemType Directory | Out-Null
}
# Check for existing agent
if (Test-Path $remoteAgent) {
$existingAgent = Get-Item $remoteAgent
Write-Host "[OK] Found existing agent:"
Write-Host " Size: $([math]::Round($existingAgent.Length / 1MB, 2)) MB"
Write-Host " Modified: $($existingAgent.LastWriteTime)"
# Backup existing agent
Write-Host "[INFO] Backing up existing agent..."
Copy-Item -Path $remoteAgent -Destination $remoteBackup -Force
Write-Host "[OK] Backup created: gururmm-agent.exe.backup"
} else {
Write-Host "[INFO] No existing agent found - this will be a fresh install"
}
# Copy new agent
Write-Host "[INFO] Copying new agent to AD2..."
$localInfo = Get-Item $localBinary
Write-Host " Source size: $([math]::Round($localInfo.Length / 1MB, 2)) MB"
Copy-Item -Path $localBinary -Destination $remoteAgent -Force
Write-Host "[OK] Agent copied successfully"
# Verify copy
$copiedAgent = Get-Item $remoteAgent
Write-Host "[OK] Verification:"
Write-Host " Size: $([math]::Round($copiedAgent.Length / 1MB, 2)) MB"
Write-Host " Modified: $($copiedAgent.LastWriteTime)"
# Cleanup
Remove-PSDrive -Name AD2
Write-Host ""
Write-Host "[SUCCESS] File deployment complete!"
Write-Host ""
Write-Host "IMPORTANT: Manual service management required:"
Write-Host "1. Connect to AD2: ssh INTRANET\\\\sysadmin@192.168.0.6"
Write-Host "2. Stop service: Stop-Service gururmm-agent"
Write-Host "3. Start service: Start-Service gururmm-agent"
Write-Host "4. Check status: Get-Service gururmm-agent"
Write-Host ""

View File

@@ -0,0 +1,113 @@
# Deploy GuruRMM Agent to AD2
# This script deploys the newly built agent with Claude Code integration
$ErrorActionPreference = "Stop"
Write-Host "[INFO] Starting GuruRMM agent deployment to AD2..."
# Credentials
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
# Paths
$localBinary = "D:\ClaudeTools\projects\msp-tools\guru-rmm\agent\target\release\gururmm-agent.exe"
$remotePath = "\\192.168.0.6\C$\Program Files\GuruRMM"
$remoteAgent = "$remotePath\gururmm-agent.exe"
$remoteBackup = "$remotePath\gururmm-agent.exe.backup"
# Connect to AD2
Write-Host "[INFO] Connecting to AD2 via SMB..."
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred | Out-Null
Write-Host "[OK] Connected to AD2"
# Check if agent directory exists
if (Test-Path "AD2:\Program Files\GuruRMM") {
Write-Host "[OK] GuruRMM directory found"
} else {
Write-Host "[WARNING] GuruRMM directory not found - creating..."
New-Item -Path "AD2:\Program Files\GuruRMM" -ItemType Directory | Out-Null
}
# Check for existing agent
if (Test-Path $remoteAgent) {
$existingAgent = Get-Item $remoteAgent
Write-Host "[OK] Found existing agent:"
Write-Host " Size: $([math]::Round($existingAgent.Length / 1MB, 2)) MB"
Write-Host " Modified: $($existingAgent.LastWriteTime)"
} else {
Write-Host "[INFO] No existing agent found - this will be a fresh install"
}
# Stop the service
Write-Host "[INFO] Stopping gururmm-agent service on AD2..."
try {
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
if ($service.Status -eq "Running") {
Stop-Service -Name "gururmm-agent" -Force
Write-Host "[OK] Service stopped"
} else {
Write-Host "[INFO] Service already stopped"
}
} else {
Write-Host "[WARNING] Service not found - may need to be installed"
}
}
} catch {
Write-Host "[WARNING] Could not stop service via WinRM: $_"
Write-Host "[INFO] Continuing with deployment..."
}
# Backup existing agent
if (Test-Path $remoteAgent) {
Write-Host "[INFO] Backing up existing agent..."
Copy-Item -Path $remoteAgent -Destination $remoteBackup -Force
Write-Host "[OK] Backup created: gururmm-agent.exe.backup"
}
# Copy new agent
Write-Host "[INFO] Copying new agent to AD2..."
$localInfo = Get-Item $localBinary
Write-Host " Source size: $([math]::Round($localInfo.Length / 1MB, 2)) MB"
Copy-Item -Path $localBinary -Destination $remoteAgent -Force
Write-Host "[OK] Agent copied successfully"
# Verify copy
$copiedAgent = Get-Item $remoteAgent
Write-Host "[OK] Verification:"
Write-Host " Size: $([math]::Round($copiedAgent.Length / 1MB, 2)) MB"
Write-Host " Modified: $($copiedAgent.LastWriteTime)"
# Start the service
Write-Host "[INFO] Starting gururmm-agent service on AD2..."
try {
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
Start-Service -Name "gururmm-agent"
Start-Sleep -Seconds 2
$service = Get-Service -Name "gururmm-agent"
if ($service.Status -eq "Running") {
Write-Host "[OK] Service started successfully"
} else {
Write-Host "[WARNING] Service not running - status: $($service.Status)"
}
} else {
Write-Host "[WARNING] Service not found - manual installation may be required"
}
}
} catch {
Write-Host "[WARNING] Could not start service via WinRM: $_"
Write-Host "[INFO] You may need to start the service manually"
}
# Cleanup
Remove-PSDrive -Name AD2
Write-Host ""
Write-Host "[SUCCESS] Deployment complete!"
Write-Host ""
Write-Host "Next steps:"
Write-Host "1. Verify agent reconnected to GuruRMM server"
Write-Host "2. Test Claude task execution"
Write-Host ""

View File

@@ -0,0 +1,41 @@
# Deploy FIXED Database API to AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "========================================" -ForegroundColor Red
Write-Host "EMERGENCY FIX - Database API" -ForegroundColor Red
Write-Host "========================================`n" -ForegroundColor Red
# Step 1: Mount AD2 share
Write-Host "[1/3] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host " [OK] Share mounted" -ForegroundColor Green
# Step 2: Deploy fixed api.js (already have backup from before)
Write-Host "`n[2/3] Deploying FIXED api.js..." -ForegroundColor Green
$fixedContent = Get-Content "D:\ClaudeTools\api-js-fixed.js" -Raw
$fixedContent | Set-Content "AD2:\Shares\testdatadb\routes\api.js" -Encoding UTF8
Write-Host " [OK] Fixed api.js deployed" -ForegroundColor Green
Write-Host " [FIXED] Removed WAL mode pragma (conflicts with readonly)" -ForegroundColor Yellow
Write-Host " [FIXED] Removed synchronous pragma (requires write access)" -ForegroundColor Yellow
Write-Host " [KEPT] Cache size: 64MB" -ForegroundColor Green
Write-Host " [KEPT] Memory-mapped I/O: 256MB" -ForegroundColor Green
Write-Host " [KEPT] Timeout: 10 seconds" -ForegroundColor Green
# Step 3: Verify deployment
Write-Host "`n[3/3] Verifying deployment..." -ForegroundColor Green
$deployedFile = Get-Item "AD2:\Shares\testdatadb\routes\api.js"
Write-Host " [OK] File size: $($deployedFile.Length) bytes" -ForegroundColor Green
Write-Host " [OK] Modified: $($deployedFile.LastWriteTime)" -ForegroundColor Green
# Cleanup
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n========================================" -ForegroundColor Green
Write-Host "Fix Deployed Successfully" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host "`n[ACTION REQUIRED] Restart Node.js Server:" -ForegroundColor Yellow
Write-Host " 1. Stop: taskkill /F /IM node.exe" -ForegroundColor Cyan
Write-Host " 2. Start: cd C:\Shares\testdatadb && node server.js" -ForegroundColor Cyan
Write-Host "`nThe database should now work correctly!" -ForegroundColor Green
Write-Host "========================================`n" -ForegroundColor Green

View File

@@ -0,0 +1,57 @@
# Deploy Database Performance Optimizations to AD2 (SMB only)
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Test Database Performance Optimization" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan
# Step 1: Mount AD2 share
Write-Host "[1/4] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host " [OK] Share mounted" -ForegroundColor Green
# Step 2: Backup existing api.js
Write-Host "`n[2/4] Backing up existing api.js..." -ForegroundColor Green
$timestamp = Get-Date -Format "yyyy-MM-dd-HHmmss"
$backupPath = "AD2:\Shares\testdatadb\routes\api.js.backup-$timestamp"
Copy-Item "AD2:\Shares\testdatadb\routes\api.js" $backupPath
Write-Host " [OK] Backup created: api.js.backup-$timestamp" -ForegroundColor Green
# Step 3: Deploy optimized api.js
Write-Host "`n[3/4] Deploying optimized api.js..." -ForegroundColor Green
$optimizedContent = Get-Content "D:\ClaudeTools\api-js-optimized.js" -Raw
$optimizedContent | Set-Content "AD2:\Shares\testdatadb\routes\api.js" -Encoding UTF8
Write-Host " [OK] Optimized api.js deployed" -ForegroundColor Green
# Step 4: Verify deployment
Write-Host "`n[4/4] Verifying deployment..." -ForegroundColor Green
$deployedFile = Get-Item "AD2:\Shares\testdatadb\routes\api.js"
Write-Host " [OK] File size: $($deployedFile.Length) bytes" -ForegroundColor Green
Write-Host " [OK] Modified: $($deployedFile.LastWriteTime)" -ForegroundColor Green
# Cleanup
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "Deployment Complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "[OK] Backup created" -ForegroundColor Green
Write-Host "[OK] Optimized code deployed" -ForegroundColor Green
Write-Host "`nOptimizations Applied:" -ForegroundColor Cyan
Write-Host " - Connection timeout: 10 seconds" -ForegroundColor Cyan
Write-Host " - WAL mode: Enabled (better concurrency)" -ForegroundColor Cyan
Write-Host " - Cache size: 64MB" -ForegroundColor Cyan
Write-Host " - Memory-mapped I/O: 256MB" -ForegroundColor Cyan
Write-Host " - Synchronous mode: NORMAL (faster, safe)" -ForegroundColor Cyan
Write-Host "`n[ACTION REQUIRED] Restart Node.js Server:" -ForegroundColor Yellow
Write-Host " 1. Connect to AD2 (SSH or RDP)" -ForegroundColor Yellow
Write-Host " 2. Stop existing Node.js process:" -ForegroundColor Yellow
Write-Host " taskkill /F /IM node.exe" -ForegroundColor Cyan
Write-Host " 3. Start server:" -ForegroundColor Yellow
Write-Host " cd C:\Shares\testdatadb" -ForegroundColor Cyan
Write-Host " node server.js" -ForegroundColor Cyan
Write-Host "`nWeb Interface: http://192.168.0.6:3000" -ForegroundColor Green
Write-Host "`nRollback (if needed):" -ForegroundColor Yellow
Write-Host " Copy-Item C:\Shares\testdatadb\routes\api.js.backup-$timestamp C:\Shares\testdatadb\routes\api.js" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

View File

@@ -0,0 +1,107 @@
# Deploy Database Performance Optimizations to AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Test Database Performance Optimization" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan
# Step 1: Mount AD2 share
Write-Host "[1/6] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host " [OK] Share mounted" -ForegroundColor Green
# Step 2: Backup existing api.js
Write-Host "`n[2/6] Backing up existing api.js..." -ForegroundColor Green
$timestamp = Get-Date -Format "yyyy-MM-dd-HHmmss"
$backupPath = "AD2:\Shares\testdatadb\routes\api.js.backup-$timestamp"
Copy-Item "AD2:\Shares\testdatadb\routes\api.js" $backupPath
Write-Host " [OK] Backup created: api.js.backup-$timestamp" -ForegroundColor Green
# Step 3: Deploy optimized api.js
Write-Host "`n[3/6] Deploying optimized api.js..." -ForegroundColor Green
$optimizedContent = Get-Content "D:\ClaudeTools\api-js-optimized.js" -Raw
$optimizedContent | Set-Content "AD2:\Shares\testdatadb\routes\api.js" -Encoding UTF8
Write-Host " [OK] Optimized api.js deployed" -ForegroundColor Green
# Step 4: Stop Node.js server
Write-Host "`n[4/6] Stopping Node.js server..." -ForegroundColor Yellow
try {
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$nodeProcs = Get-Process node -ErrorAction SilentlyContinue
if ($nodeProcs) {
$nodeProcs | ForEach-Object {
Write-Host " Stopping process ID: $($_.Id)"
Stop-Process -Id $_.Id -Force
}
Start-Sleep -Seconds 2
Write-Host " [OK] Node.js processes stopped"
} else {
Write-Host " [INFO] No Node.js process found"
}
} -ErrorAction Stop
} catch {
Write-Host " [WARNING] Could not stop via WinRM: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " [ACTION] You may need to stop the server manually on AD2" -ForegroundColor Yellow
}
# Step 5: Start Node.js server
Write-Host "`n[5/6] Starting Node.js server..." -ForegroundColor Green
try {
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Set-Location "C:\Shares\testdatadb"
# Start Node.js in background
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "node"
$startInfo.Arguments = "server.js"
$startInfo.WorkingDirectory = "C:\Shares\testdatadb"
$startInfo.UseShellExecute = $false
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$startInfo.CreateNoWindow = $true
$process = [System.Diagnostics.Process]::Start($startInfo)
Start-Sleep -Seconds 3
if (!$process.HasExited) {
Write-Host " [OK] Server started (PID: $($process.Id))"
} else {
Write-Host " [ERROR] Server failed to start"
}
} -ErrorAction Stop
} catch {
Write-Host " [WARNING] Could not start via WinRM: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " [ACTION] Please start manually: cd C:\Shares\testdatadb && node server.js" -ForegroundColor Yellow
}
# Step 6: Test connectivity
Write-Host "`n[6/6] Testing server connectivity..." -ForegroundColor Green
Start-Sleep -Seconds 2
$portTest = Test-NetConnection -ComputerName 192.168.0.6 -Port 3000 -WarningAction SilentlyContinue -InformationLevel Quiet
if ($portTest) {
Write-Host " [OK] Port 3000 is accessible" -ForegroundColor Green
} else {
Write-Host " [ERROR] Port 3000 is not accessible - server may not have started" -ForegroundColor Red
}
# Cleanup
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "Deployment Summary" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "[OK] Backup created" -ForegroundColor Green
Write-Host "[OK] Optimized code deployed" -ForegroundColor Green
Write-Host "`nOptimizations Applied:" -ForegroundColor Cyan
Write-Host " - Connection timeout: 10 seconds" -ForegroundColor Cyan
Write-Host " - WAL mode: Enabled (better concurrency)" -ForegroundColor Cyan
Write-Host " - Cache size: 64MB" -ForegroundColor Cyan
Write-Host " - Memory-mapped I/O: 256MB" -ForegroundColor Cyan
Write-Host " - Synchronous mode: NORMAL (faster, safe)" -ForegroundColor Cyan
Write-Host "`nWeb Interface: http://192.168.0.6:3000" -ForegroundColor Green
Write-Host "`nNext Steps (Optional):" -ForegroundColor Yellow
Write-Host " - Run VACUUM to optimize database" -ForegroundColor Yellow
Write-Host " - Test queries via web interface" -ForegroundColor Yellow
Write-Host "========================================`n" -ForegroundColor Cyan

View File

@@ -0,0 +1,17 @@
# Deploy and run test query on AD2
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Copying test script to AD2..." -ForegroundColor Green
Copy-Item "D:\ClaudeTools\test-query.js" "AD2:\Shares\testdatadb\test-query.js" -Force
Write-Host "[OK] Test script deployed" -ForegroundColor Green
Write-Host "`n[ACTION] Run on AD2:" -ForegroundColor Yellow
Write-Host " cd C:\Shares\testdatadb" -ForegroundColor Cyan
Write-Host " node test-query.js" -ForegroundColor Cyan
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,27 @@
Import-Module Posh-SSH
$secPassword = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $secPassword)
$session = New-SSHSession -ComputerName 192.168.0.6 -Credential $cred -AcceptKey -Force -ConnectionTimeout 30
Write-Output "[OK] Connected to AD2"
$portCheck = @'
powershell -Command "foreach ($p in @(22,445,3389,5985)) { $t = New-Object System.Net.Sockets.TcpClient; $r = $t.BeginConnect('192.168.0.149', $p, $null, $null); $w = $r.AsyncWaitHandle.WaitOne(2000, $false); if ($w -and $t.Connected) { Write-Output \"$p : Open\"; $t.Close() } else { Write-Output \"$p : Closed\"; $t.Close() } }"
'@
Write-Output "`n=== Port Check 192.168.0.149 ==="
$result = Invoke-SSHCommand -SessionId $session.SessionId -Command $portCheck -TimeOut 30
Write-Output $result.Output
# If 445 is open, try PsExec-style via SMB to check creds
# If 5985 not open, try enabling WinRM via scheduled task
$cmd = @'
powershell -Command "Invoke-Command -ComputerName DESKTOP-Q33I5H1 -Credential (New-Object PSCredential('INTRANET\sysadmin',(ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force))) -ScriptBlock { cmdkey /list } -ErrorAction SilentlyContinue 2>&1"
'@
Write-Output "`n=== WinRM attempt ==="
$r2 = Invoke-SSHCommand -SessionId $session.SessionId -Command $cmd -TimeOut 30
Write-Output $r2.Output
if ($r2.Error) { Write-Output $r2.Error }
Remove-SSHSession -SessionId $session.SessionId | Out-Null

View File

@@ -0,0 +1,62 @@
$secPassword = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $secPassword)
# Query lockout events from AD1 via AD2 (same subnet hop)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -Authentication Negotiate -ScriptBlock {
# Query AD1's event log from AD2 (both on same subnet)
Write-Output "=== Lockout Events (4740) from AD1 ==="
try {
$lockouts = Get-WinEvent -ComputerName AD1 -FilterHashtable @{LogName='Security'; Id=4740; StartTime=(Get-Date).AddDays(-7)} -ErrorAction Stop |
Where-Object { $_.Properties[0].Value -eq 'jlohr' } |
Select-Object -First 30
foreach ($e in $lockouts) {
Write-Output "$($e.TimeCreated) | Caller: $($e.Properties[1].Value)"
}
if (-not $lockouts) { Write-Output " None found" }
} catch { Write-Output " ERROR: $_" }
Write-Output "`n=== Kerberos Failures (4771) from AD1 ==="
try {
$k = Get-WinEvent -ComputerName AD1 -FilterHashtable @{LogName='Security'; Id=4771; StartTime=(Get-Date).AddDays(-3)} -ErrorAction Stop |
Where-Object { $_.Properties[0].Value -eq 'jlohr' } |
Select-Object -First 30
foreach ($e in $k) {
Write-Output "$($e.TimeCreated) | IP: $($e.Properties[6].Value) | Status: $($e.Properties[4].Value)"
}
if (-not $k) { Write-Output " None found" }
} catch { Write-Output " ERROR: $_" }
Write-Output "`n=== NTLM Failures (4776) from AD1 ==="
try {
$n = Get-WinEvent -ComputerName AD1 -FilterHashtable @{LogName='Security'; Id=4776; StartTime=(Get-Date).AddDays(-3)} -ErrorAction Stop |
Where-Object { $_.Properties[1].Value -eq 'jlohr' -and $_.Properties[2].Value -ne 0 } |
Select-Object -First 30
foreach ($e in $n) {
Write-Output "$($e.TimeCreated) | Workstation: $($e.Properties[0].Value) | Error: $($e.Properties[2].Value)"
}
if (-not $n) { Write-Output " None found" }
} catch { Write-Output " ERROR: $_" }
Write-Output "`n=== Logon Failures (4625) from AD1 ==="
try {
$f = Get-WinEvent -ComputerName AD1 -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddDays(-3)} -ErrorAction Stop |
Where-Object { $_.Properties[5].Value -eq 'jlohr' } |
Select-Object -First 30
foreach ($e in $f) {
Write-Output "$($e.TimeCreated) | Source: $($e.Properties[13].Value) ($($e.Properties[19].Value)) | Type: $($e.Properties[10].Value) | Reason: $($e.Properties[8].Value)"
}
if (-not $f) { Write-Output " None found" }
} catch { Write-Output " ERROR: $_" }
# Also check AD2's own logs
Write-Output "`n=== Lockout Events (4740) from AD2 ==="
try {
$l2 = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4740; StartTime=(Get-Date).AddDays(-7)} -ErrorAction Stop |
Where-Object { $_.Properties[0].Value -eq 'jlohr' } |
Select-Object -First 30
foreach ($e in $l2) {
Write-Output "$($e.TimeCreated) | Caller: $($e.Properties[1].Value)"
}
if (-not $l2) { Write-Output " None found" }
} catch { Write-Output " ERROR: $_" }
} -ErrorAction Stop

View File

@@ -0,0 +1,27 @@
$secPassword = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $secPassword)
Write-Output "Testing Negotiate auth..."
try {
$result = Invoke-Command -ComputerName 192.168.0.27 -Credential $cred -Authentication Negotiate -ScriptBlock { hostname } -ErrorAction Stop
Write-Output "[OK] Negotiate: $result"
} catch {
Write-Output "[FAIL] Negotiate: $_"
}
Write-Output "`nTesting Default auth..."
try {
$result = Invoke-Command -ComputerName 192.168.0.27 -Credential $cred -ScriptBlock { hostname } -ErrorAction Stop
Write-Output "[OK] Default: $result"
} catch {
Write-Output "[FAIL] Default: $_"
}
Write-Output "`nTesting with SessionOption..."
try {
$so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$result = Invoke-Command -ComputerName 192.168.0.27 -Credential $cred -Authentication Negotiate -SessionOption $so -ScriptBlock { hostname } -ErrorAction Stop
Write-Output "[OK] SessionOption: $result"
} catch {
Write-Output "[FAIL] SessionOption: $_"
}

View File

@@ -0,0 +1,18 @@
# Diagnose D2TESTNAS SSH connection issues
Write-Host "[INFO] Testing SSH connection to D2TESTNAS (192.168.0.9)..."
Write-Host ""
# Try SSH with verbose output
$Output = & ssh -v root@192.168.0.9 "echo 'Connection successful'" 2>&1
Write-Host "[INFO] SSH Output:"
$Output | ForEach-Object { Write-Host $_ }
Write-Host ""
Write-Host "[INFO] If key authentication is failing, you can:"
Write-Host " 1. Access web interface: http://192.168.0.9/"
Write-Host " User: admin, Password: Paper123!@#-nas"
Write-Host " 2. Check SSH service status"
Write-Host " 3. Verify authorized_keys file"
Write-Host " 4. Restart SSH service if needed"

View File

@@ -0,0 +1,61 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Sync Diagnostic Report" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Checking Sync Task Status..." -ForegroundColor Yellow
$task = Get-ScheduledTask -TaskName "Sync-FromNAS" -ErrorAction SilentlyContinue
if ($task) {
Write-Host " State: $($task.State)" -ForegroundColor White
$taskInfo = Get-ScheduledTaskInfo -TaskName "Sync-FromNAS"
Write-Host " Last Run: $($taskInfo.LastRunTime)" -ForegroundColor White
Write-Host " Last Result: 0x$($taskInfo.LastTaskResult.ToString('X'))" -ForegroundColor White
Write-Host " Next Run: $($taskInfo.NextRunTime)" -ForegroundColor White
}
Write-Host ""
Write-Host "[2] Checking for Running Sync Processes..." -ForegroundColor Yellow
$syncProcs = Get-Process -Name pwsh,powershell -ErrorAction SilentlyContinue |
Where-Object { $_.CommandLine -like "*Sync-FromNAS*" }
if ($syncProcs) {
Write-Host " Found $($syncProcs.Count) running sync process(es)" -ForegroundColor Red
$syncProcs | ForEach-Object {
Write-Host " PID $($_.Id): Started $($_.StartTime)" -ForegroundColor White
}
} else {
Write-Host " No sync processes running" -ForegroundColor Green
}
Write-Host ""
Write-Host "[3] Checking commonSources Configuration..." -ForegroundColor Yellow
$syncScript = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1" -Raw
if ($syncScript -match '\$commonSources\s*=\s*@\((.*?)\)') {
Write-Host " Found commonSources config:" -ForegroundColor White
Write-Host $matches[0] -ForegroundColor Gray
}
Write-Host ""
Write-Host "[4] Last 10 Sync Log Entries..." -ForegroundColor Yellow
if (Test-Path "C:\Shares\test\scripts\sync-from-nas.log") {
Get-Content "C:\Shares\test\scripts\sync-from-nas.log" | Select-Object -Last 10 |
ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}
Write-Host ""
Write-Host "[5] Testing SSH Connection to NAS..." -ForegroundColor Yellow
$sshTest = ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "echo OK" 2>&1
if ($sshTest -eq "OK") {
Write-Host " SSH connection: OK" -ForegroundColor Green
} else {
Write-Host " SSH connection: FAILED - $sshTest" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Diagnostic Complete" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

View File

@@ -0,0 +1,53 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..."
try {
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Mounted as AD2: drive"
Write-Host "`n[OK] Exploring C:\Shares\testdatadb folder structure..."
if (Test-Path "AD2:\Shares\testdatadb") {
Write-Host "`n=== Folder Structure ==="
Get-ChildItem "AD2:\Shares\testdatadb" -Recurse -Depth 3 | Select-Object FullName, Length, LastWriteTime | Format-Table -AutoSize
Write-Host "`n=== Database Files ==="
Get-ChildItem "AD2:\Shares\testdatadb" -Recurse -Include "*.db","*.sqlite","*.json","*.sql","*.mdb","package.json","*.md","README*" | Select-Object FullName, Length
Write-Host "`n=== import.js Contents (First 100 lines) ==="
if (Test-Path "AD2:\Shares\testdatadb\database\import.js") {
Get-Content "AD2:\Shares\testdatadb\database\import.js" -TotalCount 100
} else {
Write-Host "[WARNING] import.js not found"
}
Write-Host "`n=== package.json Contents ==="
if (Test-Path "AD2:\Shares\testdatadb\database\package.json") {
Get-Content "AD2:\Shares\testdatadb\database\package.json"
} elseif (Test-Path "AD2:\Shares\testdatadb\package.json") {
Get-Content "AD2:\Shares\testdatadb\package.json"
} else {
Write-Host "[INFO] No package.json found"
}
Write-Host "`n=== README or Documentation ==="
$readmeFiles = Get-ChildItem "AD2:\Shares\testdatadb" -Recurse -Include "README*","*.md" -ErrorAction SilentlyContinue
foreach ($readme in $readmeFiles) {
Write-Host "`n--- $($readme.FullName) ---"
Get-Content $readme.FullName -TotalCount 50
}
} else {
Write-Host "[ERROR] C:\Shares\testdatadb folder not found"
Write-Host "`n[INFO] Listing C:\Shares contents..."
Get-ChildItem "AD2:\Shares" -Directory | Format-Table Name, FullName
}
} catch {
Write-Host "[ERROR] Failed to access AD2: $_"
} finally {
if (Test-Path AD2:) {
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Unmounted AD2 drive"
}
}

View File

@@ -0,0 +1,28 @@
# Find where the generic ERROR messages are logged
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$content = Get-Content $scriptPath
Write-Host "=== Finding ERROR Log Statements ===" -ForegroundColor Cyan
Write-Host ""
for ($i = 0; $i -lt $content.Count; $i++) {
if ($content[$i] -match 'Write-Log.*ERROR.*Failed to (push|pull)') {
Write-Host "Line $($i+1): $($content[$i])" -ForegroundColor Red
# Show context (3 lines before and after)
Write-Host ""
Write-Host "Context:" -ForegroundColor Yellow
for ($j = [math]::Max(0, $i-3); $j -le [math]::Min($content.Count-1, $i+3); $j++) {
if ($j -eq $i) {
Write-Host ">>> $($j+1): $($content[$j])" -ForegroundColor Red
} else {
Write-Host " $($j+1): $($content[$j])" -ForegroundColor Gray
}
}
Write-Host ""
}
}
}

View File

@@ -0,0 +1,183 @@
# Fix error logging in Copy-ToNAS function in AD2 Sync-FromNAS.ps1
# Target: 192.168.0.6 (AD2)
# Script: C:\Shares\test\scripts\Sync-FromNAS.ps1
param(
[string]$ComputerName = "192.168.0.6",
[string]$Username = "INTRANET\sysadmin",
[string]$Password = "Paper123!@#",
[string]$ScriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
)
# Create credential object
$securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($Username, $securePassword)
Write-Host "[INFO] Connecting to AD2 ($ComputerName) to fix error logging..." -ForegroundColor Cyan
try {
# Execute remote script block
$result = Invoke-Command -ComputerName $ComputerName -Credential $credential -ScriptBlock {
param($ScriptPath)
$output = @{
Success = $false
Message = ""
Before = ""
After = ""
BackupPath = ""
}
# Check if script exists
if (-not (Test-Path $ScriptPath)) {
$output.Message = "Script not found at $ScriptPath"
return $output
}
# Create backup with timestamp
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupPath = "$ScriptPath.backup_$timestamp"
try {
Copy-Item -Path $ScriptPath -Destination $backupPath -Force
$output.BackupPath = $backupPath
} catch {
$output.Message = "Failed to create backup: $_"
return $output
}
# Read script content
$content = Get-Content -Path $ScriptPath -Raw
$output.Before = $content
# Find and replace the error logging section
# Original pattern (lines 90-91):
# if ($LASTEXITCODE -ne 0) { Write-Log " SCP ERROR (exit ): $result" }
$originalPattern = '\s*if\s*\(\$LASTEXITCODE\s+-ne\s+0\)\s*\{\s*Write-Log\s+"[^"]*SCP ERROR[^"]*"\s*\}'
$replacement = @"
if (`$LASTEXITCODE -ne 0) {
`$errorMsg = `$result | Out-String
Write-Log " SCP PUSH ERROR (exit `$LASTEXITCODE): `$errorMsg"
}
"@
# Perform replacement
$newContent = $content -replace $originalPattern, $replacement
# Verify something changed
if ($newContent -eq $content) {
# Try alternative pattern match
if ($content -match 'Write-Log\s+"[^"]*SCP ERROR[^"]*exit\s*\)[^"]*"\s*\}') {
# Pattern found but not replaced, try more specific replacement
$lines = $content -split "`r?`n"
$newLines = @()
$i = 0
$replaced = $false
while ($i -lt $lines.Count) {
$line = $lines[$i]
# Look for the error logging line in Copy-ToNAS function
if ($line -match '^\s*if\s*\(\$LASTEXITCODE\s+-ne\s+0\)\s*\{.*SCP ERROR.*\}') {
# Replace this line with multi-line version
$indent = ($line -replace '^(\s*).*', '$1')
$newLines += "$indent`if (`$LASTEXITCODE -ne 0) {"
$newLines += "$indent `$errorMsg = `$result | Out-String"
$newLines += "$indent Write-Log `" SCP PUSH ERROR (exit `$LASTEXITCODE): `$errorMsg`""
$newLines += "$indent}"
$replaced = $true
} else {
$newLines += $line
}
$i++
}
if ($replaced) {
$newContent = $newLines -join "`r`n"
} else {
$output.Message = "Could not find the exact error logging pattern to replace"
return $output
}
} else {
$output.Message = "Could not find the error logging pattern in the script"
return $output
}
}
$output.After = $newContent
# Write updated content
try {
Set-Content -Path $ScriptPath -Value $newContent -Force
$output.Success = $true
$output.Message = "Successfully updated error logging in Copy-ToNAS function"
} catch {
$output.Message = "Failed to write updated script: $_"
# Restore backup
Copy-Item -Path $backupPath -Destination $ScriptPath -Force
return $output
}
# Verify syntax by attempting to parse
try {
$errors = $null
$null = [System.Management.Automation.PSParser]::Tokenize($newContent, [ref]$errors)
if ($errors) {
$output.Message = "Syntax validation found errors: $($errors -join '; ')"
$output.Success = $false
# Restore backup
Copy-Item -Path $backupPath -Destination $ScriptPath -Force
}
} catch {
$output.Message = "Syntax validation failed: $_"
$output.Success = $false
# Restore backup
Copy-Item -Path $backupPath -Destination $ScriptPath -Force
}
return $output
} -ArgumentList $ScriptPath
# Display results
if ($result.Success) {
Write-Host "`n[SUCCESS] $($result.Message)" -ForegroundColor Green
Write-Host "[INFO] Backup created at: $($result.BackupPath)" -ForegroundColor Cyan
# Show before/after comparison
Write-Host "`n--- BEFORE ---" -ForegroundColor Yellow
$beforeLines = $result.Before -split "`r?`n"
$startLine = 0
for ($i = 0; $i -lt $beforeLines.Count; $i++) {
if ($beforeLines[$i] -match 'if\s*\(\$LASTEXITCODE\s+-ne\s+0\).*SCP ERROR') {
$startLine = [Math]::Max(0, $i - 2)
break
}
}
$beforeLines[$startLine..([Math]::Min($startLine + 5, $beforeLines.Count - 1))] | ForEach-Object { Write-Host $_ }
Write-Host "`n--- AFTER ---" -ForegroundColor Green
$afterLines = $result.After -split "`r?`n"
$startLine = 0
for ($i = 0; $i -lt $afterLines.Count; $i++) {
if ($afterLines[$i] -match 'if\s*\(\$LASTEXITCODE\s+-ne\s+0\).*\{' -and $afterLines[$i + 1] -match 'errorMsg') {
$startLine = [Math]::Max(0, $i - 2)
break
}
}
$afterLines[$startLine..([Math]::Min($startLine + 7, $afterLines.Count - 1))] | ForEach-Object { Write-Host $_ }
Write-Host "`n[OK] Error logging fix applied successfully" -ForegroundColor Green
} else {
Write-Host "`n[ERROR] $($result.Message)" -ForegroundColor Red
exit 1
}
} catch {
Write-Host "`n[ERROR] Failed to connect or execute on AD2: $_" -ForegroundColor Red
Write-Host "Error Details: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
Write-Host "`n[COMPLETE] AD2 error logging fix completed" -ForegroundColor Cyan

View File

@@ -0,0 +1,28 @@
# Retrieve server.js for analysis
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Retrieving server.js..." -ForegroundColor Green
$serverContent = Get-Content "AD2:\Shares\testdatadb\server.js" -Raw
$outputPath = "D:\ClaudeTools\server-js-retrieved.js"
$serverContent | Set-Content $outputPath -Encoding UTF8
Write-Host "[OK] Saved to: $outputPath" -ForegroundColor Green
Write-Host "[OK] File size: $($(Get-Item $outputPath).Length) bytes" -ForegroundColor Cyan
# Also get routes/api.js
Write-Host "`n[OK] Retrieving routes/api.js..." -ForegroundColor Green
if (Test-Path "AD2:\Shares\testdatadb\routes\api.js") {
$apiContent = Get-Content "AD2:\Shares\testdatadb\routes\api.js" -Raw
$apiOutputPath = "D:\ClaudeTools\api-js-retrieved.js"
$apiContent | Set-Content $apiOutputPath -Encoding UTF8
Write-Host "[OK] Saved to: $apiOutputPath" -ForegroundColor Green
Write-Host "[OK] File size: $($(Get-Item $apiOutputPath).Length) bytes" -ForegroundColor Cyan
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,105 @@
# Get detailed sync error messages
Write-Host "=== Analyzing Sync Error Details ===" -ForegroundColor Cyan
Write-Host ""
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "Looking for detailed error messages..." -ForegroundColor Yellow
Write-Host ""
# Get context around errors (lines before and after ERROR lines)
$content = Get-Content $logFile -Tail 2000
Write-Host "[1] Error Context (last 20 errors with surrounding lines)" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host ""
$errorIndices = @()
for ($i = 0; $i -lt $content.Count; $i++) {
if ($content[$i] -match "ERROR:") {
$errorIndices += $i
}
}
# Show last 20 errors with context
$errorIndices | Select-Object -Last 20 | ForEach-Object {
$index = $_
# Show 2 lines before, the error, and 2 lines after
$start = [Math]::Max(0, $index - 2)
$end = [Math]::Min($content.Count - 1, $index + 2)
for ($i = $start; $i -le $end; $i++) {
if ($i -eq $index) {
Write-Host ">>> $($content[$i])" -ForegroundColor Red
} else {
Write-Host " $($content[$i])" -ForegroundColor Gray
}
}
Write-Host ""
}
Write-Host ""
Write-Host "[2] Checking for specific error messages" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Look for common error patterns in more detail
$sshErrors = $content | Select-String -Pattern "ssh|plink|pscp" -Context 0,1
$permErrors = $content | Select-String -Pattern "denied|permission" -Context 0,1
$fileErrors = $content | Select-String -Pattern "not found|no such|cannot find" -Context 0,1
$networkErrors = $content | Select-String -Pattern "timeout|connection|network" -Context 0,1
if ($sshErrors) {
Write-Host "SSH/Connection Errors:" -ForegroundColor Red
$sshErrors | Select-Object -First 5 | ForEach-Object {
Write-Host " $($_.Line)" -ForegroundColor Red
}
Write-Host ""
}
if ($permErrors) {
Write-Host "Permission Errors:" -ForegroundColor Red
$permErrors | Select-Object -First 5 | ForEach-Object {
Write-Host " $($_.Line)" -ForegroundColor Red
}
Write-Host ""
}
if ($fileErrors) {
Write-Host "File Not Found Errors:" -ForegroundColor Red
$fileErrors | Select-Object -First 5 | ForEach-Object {
Write-Host " $($_.Line)" -ForegroundColor Red
}
Write-Host ""
}
if ($networkErrors) {
Write-Host "Network/Timeout Errors:" -ForegroundColor Red
$networkErrors | Select-Object -First 5 | ForEach-Object {
Write-Host " $($_.Line)" -ForegroundColor Red
}
Write-Host ""
}
Write-Host ""
Write-Host "[3] Checking one of the failing files" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Check if one of the failing files actually exists
$testFile = "C:\Shares\test\TS-11L\ProdSW\HVDATA\hvin.dat"
if (Test-Path $testFile) {
$file = Get-Item $testFile
Write-Host "Sample failing file EXISTS on AD2:" -ForegroundColor Green
Write-Host " Path: $($file.FullName)" -ForegroundColor White
Write-Host " Size: $($file.Length) bytes" -ForegroundColor White
Write-Host " Modified: $($file.LastWriteTime)" -ForegroundColor White
Write-Host ""
Write-Host "This suggests the issue is with the PUSH to NAS, not the source file." -ForegroundColor Yellow
} else {
Write-Host "Sample file does NOT exist: $testFile" -ForegroundColor Red
}
}

View File

@@ -0,0 +1,22 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Retrieving Sync-FromNAS.ps1 from AD2..."
$scriptContent = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content C:\Shares\test\scripts\Sync-FromNAS.ps1 -Raw
}
$scriptContent | Out-File -FilePath "D:\ClaudeTools\Sync-FromNAS-retrieved.ps1" -Encoding UTF8
Write-Host "[OK] Script saved to D:\ClaudeTools\Sync-FromNAS-retrieved.ps1"
Write-Host "`n[OK] Searching for database folder..."
$dbFolders = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-ChildItem C:\ -Directory -ErrorAction SilentlyContinue | Where-Object Name -match "database|testdata|test.*db"
}
if ($dbFolders) {
Write-Host "`nFound folders:"
$dbFolders | Format-Table Name, FullName
} else {
Write-Host "No database folders found in C:\"
}

View File

@@ -0,0 +1,33 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Retrieving database documentation..."
# Get schema.sql
if (Test-Path "AD2:\Shares\testdatadb\database\schema.sql") {
Get-Content "AD2:\Shares\testdatadb\database\schema.sql" -Raw | Out-File "D:\ClaudeTools\schema-retrieved.sql" -Encoding UTF8
Write-Host "[OK] schema.sql retrieved"
}
# Get QUICKSTART.md
if (Test-Path "AD2:\Shares\testdatadb\QUICKSTART.md") {
Get-Content "AD2:\Shares\testdatadb\QUICKSTART.md" -Raw | Out-File "D:\ClaudeTools\QUICKSTART-retrieved.md" -Encoding UTF8
Write-Host "[OK] QUICKSTART.md retrieved"
}
# Get SESSION_NOTES.md
if (Test-Path "AD2:\Shares\testdatadb\SESSION_NOTES.md") {
Get-Content "AD2:\Shares\testdatadb\SESSION_NOTES.md" -Raw | Out-File "D:\ClaudeTools\SESSION_NOTES-retrieved.md" -Encoding UTF8
Write-Host "[OK] SESSION_NOTES.md retrieved"
}
# Get package.json
if (Test-Path "AD2:\Shares\testdatadb\package.json") {
Get-Content "AD2:\Shares\testdatadb\package.json" -Raw | Out-File "D:\ClaudeTools\package-retrieved.json" -Encoding UTF8
Write-Host "[OK] package.json retrieved"
}
Remove-PSDrive -Name AD2
Write-Host "[OK] All files retrieved"

View File

@@ -0,0 +1,64 @@
# Install GuruRMM Agent as Service on AD2
# This script installs the agent as a Windows service
Write-Host "[INFO] Installing GuruRMM agent as service on AD2..."
# Configuration
$serverUrl = "wss://rmm-api.azcomputerguru.com/ws"
$apiKey = "SWIFT-CLOUD-6910" # Main Office site code
$agentPath = "C:\Program Files\GuruRMM\gururmm-agent.exe"
# Check if agent binary exists
if (!(Test-Path $agentPath)) {
Write-Host "[ERROR] Agent binary not found at $agentPath"
exit 1
}
Write-Host "[OK] Agent binary found"
# Check if service already exists
$existingService = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($existingService) {
Write-Host "[WARNING] Service already exists - uninstalling first..."
& $agentPath uninstall
Start-Sleep -Seconds 2
}
# Install the agent as a service
Write-Host "[INFO] Installing agent as service..."
Write-Host " Server URL: $serverUrl"
Write-Host " API Key: $apiKey"
& $agentPath install --server-url $serverUrl --api-key $apiKey
if ($LASTEXITCODE -ne 0) {
Write-Host "[ERROR] Installation failed with exit code: $LASTEXITCODE"
exit 1
}
Start-Sleep -Seconds 2
# Verify service was created
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
Write-Host "[OK] Service created successfully"
Write-Host " Name: $($service.Name)"
Write-Host " Status: $($service.Status)"
Write-Host " Start Type: $($service.StartType)"
# Start the service if not running
if ($service.Status -ne "Running") {
Write-Host "[INFO] Starting service..."
Start-Service -Name "gururmm-agent"
Start-Sleep -Seconds 2
$service = Get-Service -Name "gururmm-agent"
Write-Host "[OK] Service status: $($service.Status)"
}
} else {
Write-Host "[ERROR] Service was not created"
exit 1
}
Write-Host ""
Write-Host "[SUCCESS] GuruRMM agent installed and running on AD2!"

View File

@@ -0,0 +1,74 @@
# Install GuruRMM Agent from temporary location
# This avoids the file-in-use error by running installer from Temp
Write-Host "[INFO] Setting up GuruRMM agent installation..."
$agentPath = "C:\Program Files\GuruRMM\gururmm-agent.exe"
$tempPath = "C:\Temp\gururmm-agent-installer.exe"
$serverUrl = "wss://rmm-api.azcomputerguru.com/ws"
$apiKey = "SWIFT-CLOUD-6910"
# Check source exists
if (!(Test-Path $agentPath)) {
Write-Host "[ERROR] Agent binary not found at $agentPath"
exit 1
}
Write-Host "[OK] Agent binary found"
# Stop any running processes
$processes = Get-Process -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($processes) {
Write-Host "[WARNING] Stopping $($processes.Count) running agent process(es)..."
foreach ($proc in $processes) {
Stop-Process -Id $proc.Id -Force
}
Start-Sleep -Seconds 3
}
# Copy to temp location
Write-Host "[INFO] Copying agent to temporary location..."
Copy-Item -Path $agentPath -Destination $tempPath -Force
Write-Host "[OK] Copied to $tempPath"
# Run installer from temp location
Write-Host "[INFO] Running installer from temporary location..."
Write-Host " Server URL: $serverUrl"
Write-Host " API Key: $apiKey"
& $tempPath install --server-url $serverUrl --api-key $apiKey
if ($LASTEXITCODE -ne 0) {
Write-Host "[ERROR] Installation failed with exit code: $LASTEXITCODE"
Remove-Item -Path $tempPath -Force -ErrorAction SilentlyContinue
exit 1
}
# Clean up temp file
Remove-Item -Path $tempPath -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
# Verify service was created
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
Write-Host "[OK] Service created successfully"
Write-Host " Name: $($service.Name)"
Write-Host " Status: $($service.Status)"
Write-Host " Start Type: $($service.StartType)"
if ($service.Status -ne "Running") {
Write-Host "[INFO] Starting service..."
Start-Service -Name "gururmm-agent"
Start-Sleep -Seconds 2
$service = Get-Service -Name "gururmm-agent"
Write-Host "[OK] Service status: $($service.Status)"
}
} else {
Write-Host "[ERROR] Service was not created"
exit 1
}
Write-Host ""
Write-Host "[SUCCESS] GuruRMM agent with Claude Code integration installed and running!"

View File

@@ -0,0 +1,133 @@
# Investigate Dataforth Sync Errors on AD2
Write-Host "=== Investigating Dataforth Sync Errors ===" -ForegroundColor Cyan
Write-Host ""
# Setup admin credentials for AD2
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "Connecting to AD2 and analyzing sync logs..." -ForegroundColor Yellow
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
$statusFile = "C:\Shares\test\_SYNC_STATUS.txt"
Write-Host "[1] Current Sync Status" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
if (Test-Path $statusFile) {
Get-Content $statusFile
} else {
Write-Host "Status file not found" -ForegroundColor Red
}
Write-Host ""
Write-Host "[2] Log File Information" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
if (Test-Path $logFile) {
$file = Get-Item $logFile
Write-Host "File: $($file.FullName)" -ForegroundColor White
Write-Host "Size: $([math]::Round($file.Length / 1MB, 2)) MB" -ForegroundColor White
Write-Host "Last Modified: $($file.LastWriteTime)" -ForegroundColor White
Write-Host "Lines: $((Get-Content $logFile).Count)" -ForegroundColor White
} else {
Write-Host "Log file not found: $logFile" -ForegroundColor Red
return
}
Write-Host ""
Write-Host "[3] Analyzing Errors (last 1000 lines)" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
# Read last 1000 lines to analyze recent errors
$recentLines = Get-Content $logFile -Tail 1000
# Count error types
$errors = $recentLines | Select-String -Pattern "ERROR|Error|error|FAIL|Failed|failed"
$warnings = $recentLines | Select-String -Pattern "WARNING|Warning|warning"
Write-Host "Total Error Lines (last 1000): $($errors.Count)" -ForegroundColor $(if ($errors.Count -gt 0) { "Red" } else { "Green" })
Write-Host "Total Warning Lines (last 1000): $($warnings.Count)" -ForegroundColor $(if ($warnings.Count -gt 0) { "Yellow" } else { "Green" })
Write-Host ""
if ($errors.Count -gt 0) {
Write-Host "[4] Error Breakdown" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
# Analyze common error patterns
$errorPatterns = @{
"No such file" = "No such file|not found|cannot find"
"Permission denied" = "Permission denied|Access denied|Access is denied"
"Connection" = "Connection|connect|timeout"
"File in use" = "being used|in use|locked"
"SSH/SCP" = "ssh|scp|plink|pscp"
}
foreach ($pattern in $errorPatterns.Keys) {
$count = ($errors | Select-String -Pattern $errorPatterns[$pattern]).Count
if ($count -gt 0) {
Write-Host " $pattern`: $count" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "[5] Sample Errors (last 15)" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
$errors | Select-Object -Last 15 | ForEach-Object {
# Remove timestamp and show just the error
$line = $_.Line -replace '^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+:\s+', ''
Write-Host " $line" -ForegroundColor Red
}
Write-Host ""
}
Write-Host "[6] Recent Sync Activity (last 10 operations)" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
$recentLines | Select-String -Pattern "Pushed:|Pulled:|Deleted:" | Select-Object -Last 10 | ForEach-Object {
Write-Host " $($_.Line)" -ForegroundColor Gray
}
Write-Host ""
Write-Host "[7] Today's Summary" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
$today = Get-Date -Format "yyyy-MM-dd"
$todayLines = $recentLines | Where-Object { $_ -like "*$today*" }
if ($todayLines) {
$todayPush = ($todayLines | Select-String -Pattern "Pushed:").Count
$todayPull = ($todayLines | Select-String -Pattern "Pulled:").Count
$todayDelete = ($todayLines | Select-String -Pattern "Deleted:").Count
$todayErrors = ($todayLines | Select-String -Pattern "ERROR|Error|error|FAIL").Count
Write-Host " Files Pushed: $todayPush" -ForegroundColor Green
Write-Host " Files Pulled: $todayPull" -ForegroundColor Green
Write-Host " Files Deleted: $todayDelete" -ForegroundColor Cyan
Write-Host " Errors: $todayErrors" -ForegroundColor $(if ($todayErrors -gt 0) { "Red" } else { "Green" })
} else {
Write-Host " No activity logged for today ($today)" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[8] Script Status" -ForegroundColor Yellow
Write-Host "=" * 60 -ForegroundColor Gray
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
if (Test-Path $scriptPath) {
$script = Get-Item $scriptPath
Write-Host " Script: $($script.Name)" -ForegroundColor White
Write-Host " Last Modified: $($script.LastWriteTime)" -ForegroundColor White
# Check if scheduled task exists
$task = Get-ScheduledTask -TaskName "Sync-FromNAS" -ErrorAction SilentlyContinue
if ($task) {
Write-Host " Scheduled Task: Enabled" -ForegroundColor Green
Write-Host " Task Status: $($task.State)" -ForegroundColor White
Write-Host " Last Run: $($task.LastRunTime)" -ForegroundColor White
Write-Host " Next Run: $($task.NextRunTime)" -ForegroundColor White
} else {
Write-Host " Scheduled Task: Not found" -ForegroundColor Red
}
}
}
Write-Host ""
Write-Host "=== Investigation Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,35 @@
#!/bin/bash
echo "================================================"
echo "Manually Pushing BAT Files to NAS"
echo "================================================"
echo ""
echo "[1/3] Pushing files to /data/test/COMMON/ProdSW/..."
scp -o StrictHostKeyChecking=no \
D:/ClaudeTools/DEPLOY.BAT \
D:/ClaudeTools/CTONW.BAT \
D:/ClaudeTools/CTONWTXT.BAT \
D:/ClaudeTools/NWTOC.BAT \
D:/ClaudeTools/UPDATE.BAT \
D:/ClaudeTools/CHECKUPD.BAT \
D:/ClaudeTools/STAGE.BAT \
D:/ClaudeTools/REBOOT.BAT \
D:/ClaudeTools/AUTOEXEC.BAT \
root@192.168.0.9:/data/test/COMMON/ProdSW/
echo "[OK] COMMON/ProdSW updated"
echo ""
echo "[2/3] Pushing UPDATE.BAT to /data/test/ root..."
scp -o StrictHostKeyChecking=no D:/ClaudeTools/UPDATE.BAT root@192.168.0.9:/data/test/
echo "[OK] UPDATE.BAT pushed to root"
echo ""
echo "[3/3] Pushing DEPLOY.BAT to /data/test/ root..."
scp -o StrictHostKeyChecking=no D:/ClaudeTools/DEPLOY.BAT root@192.168.0.9:/data/test/
echo "[OK] DEPLOY.BAT pushed to root"
echo ""
echo "================================================"
echo "Manual Push Complete!"
echo "================================================"

View File

@@ -0,0 +1,98 @@
# Monitor the next scheduled sync run to verify the fix
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Monitoring Next Sync Run ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "[1] Current time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
Write-Host "[2] Scheduled task runs every 15 minutes" -ForegroundColor Yellow
Write-Host ""
# Get current log size
$initialSize = (Get-Item $logFile).Length
Write-Host "[3] Waiting for next sync run..." -ForegroundColor Cyan
Write-Host " (watching log file for new entries)" -ForegroundColor Gray
Write-Host ""
# Wait for new log entries (max 16 minutes)
$timeout = 960 # 16 minutes in seconds
$elapsed = 0
$newContent = $null
while ($elapsed -lt $timeout) {
Start-Sleep -Seconds 10
$elapsed += 10
$currentSize = (Get-Item $logFile).Length
if ($currentSize -gt $initialSize) {
# New content detected
Write-Host "[OK] New sync activity detected!" -ForegroundColor Green
Start-Sleep -Seconds 30 # Wait for sync to complete
break
}
# Show progress
$remaining = [math]::Round(($timeout - $elapsed) / 60, 1)
Write-Host " Waiting... ($remaining minutes until timeout)" -ForegroundColor Gray
}
if ($currentSize -eq $initialSize) {
Write-Host "[WARNING] No new sync activity within timeout period" -ForegroundColor Yellow
Write-Host "Showing last 20 lines of existing log:" -ForegroundColor Gray
Get-Content $logFile -Tail 20 | ForEach-Object {
if ($_ -match "ERROR|error") {
Write-Host " $_" -ForegroundColor Red
} else {
Write-Host " $_" -ForegroundColor Gray
}
}
return
}
Write-Host ""
Write-Host "[4] Analyzing new log entries" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Get all content and extract the new portion
$allContent = Get-Content $logFile -Raw
$newBytes = $currentSize - $initialSize
$newContent = $allContent.Substring([math]::Max(0, $allContent.Length - $newBytes - 1000))
# Show new log entries
$newContent -split "`n" | Select-Object -Last 50 | ForEach-Object {
if ($_ -match "SCP ERROR|ERROR.*push|ERROR.*pull") {
Write-Host " $_" -ForegroundColor Red
} elseif ($_ -match "Pushed:|Pulled:") {
Write-Host " $_" -ForegroundColor Green
} elseif ($_ -match "Starting sync|sync complete") {
Write-Host " $_" -ForegroundColor Cyan
} else {
Write-Host " $_" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "[5] Error summary" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$scpErrors = $newContent -split "`n" | Select-String -Pattern "SCP ERROR"
if ($scpErrors) {
Write-Host "[FOUND] SCP errors in this sync run:" -ForegroundColor Red
Write-Host ""
$scpErrors | ForEach-Object {
Write-Host " $_" -ForegroundColor Red
}
} else {
Write-Host "[SUCCESS] No SCP errors found in this sync run!" -ForegroundColor Green
Write-Host "The known_hosts path fix appears to be working." -ForegroundColor Green
}
}
Write-Host ""
Write-Host "=== Monitoring Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,76 @@
# Monitor AD2-to-NAS sync status periodically
param(
[int]$Checks = 5,
[int]$IntervalMinutes = 3
)
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "AD2-to-NAS Sync Monitor" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Checks: $Checks (every $IntervalMinutes minutes)"
Write-Host "Monitoring CRLF preservation on synced files"
Write-Host ""
for ($i = 1; $i -le $Checks; $i++) {
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$Timestamp] Check $i of $Checks" -ForegroundColor Yellow
Write-Host "----------------------------------------"
# Check AD2 sync log (last 10 lines)
try {
$LogTail = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\sync-from-nas.log' -Tail 10
}
Write-Host "[INFO] Recent sync log entries:"
$LogTail | ForEach-Object { Write-Host " $_" }
Write-Host ""
} catch {
Write-Host "[ERROR] Could not read AD2 sync log: $_" -ForegroundColor Red
Write-Host ""
}
# Check NAS file timestamps and CRLF
Write-Host "[INFO] Checking DEPLOY.BAT on NAS..."
$NASInfo = & 'C:\Windows\System32\OpenSSH\ssh.exe' -o BatchMode=yes root@192.168.0.9 'ls -la /data/test/DEPLOY.BAT' 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " $NASInfo"
# Copy and verify CRLF
& 'C:\Windows\System32\OpenSSH\scp.exe' -O root@192.168.0.9:/data/test/DEPLOY.BAT ./DEPLOY_MONITOR.BAT 2>$null
if (Test-Path "DEPLOY_MONITOR.BAT") {
$Content = Get-Content "DEPLOY_MONITOR.BAT" -Raw
$Size = (Get-Item "DEPLOY_MONITOR.BAT").Length
if ($Content -match "`r`n") {
Write-Host " [SUCCESS] CRLF preserved ($Size bytes)" -ForegroundColor Green
} else {
Write-Host " [WARNING] LF only ($Size bytes)" -ForegroundColor Yellow
}
Remove-Item "DEPLOY_MONITOR.BAT" -Force
}
} else {
Write-Host " [ERROR] Could not access NAS" -ForegroundColor Red
}
Write-Host ""
if ($i -lt $Checks) {
Write-Host "Waiting $IntervalMinutes minutes until next check..."
Write-Host ""
Start-Sleep -Seconds ($IntervalMinutes * 60)
}
}
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Monitoring Complete" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

View File

@@ -0,0 +1,70 @@
# Copy fixed batch files to AD2, which will sync to NAS
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Pushing Fixed BAT Files to AD2 ===" -ForegroundColor Cyan
Write-Host ""
# List of fixed batch files
$batFiles = @(
"DEPLOY.BAT",
"NWTOC.BAT",
"CTONW.BAT",
"UPDATE.BAT",
"STAGE.BAT",
"CHECKUPD.BAT",
"REBOOT.BAT",
"AUTOEXEC.BAT",
"STARTNET.BAT",
"DOSTEST.BAT"
)
$localPath = "D:\ClaudeTools"
$pushedCount = 0
$errorCount = 0
foreach ($batFile in $batFiles) {
$localFile = Join-Path $localPath $batFile
if (Test-Path $localFile) {
Write-Host "[FOUND] $batFile" -ForegroundColor Green
# Copy to AD2
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
param($fileName, $content)
# Determine destination based on file type
if ($fileName -match "AUTOEXEC|STARTNET|CONFIG") {
# System files go to COMMON\DOS
$destPath = "C:\Shares\test\COMMON\DOS\$fileName"
} else {
# Utility scripts go to COMMON root or appropriate location
$destPath = "C:\Shares\test\$fileName"
}
# Write the file
$content | Out-File -FilePath $destPath -Encoding ASCII -Force
Write-Host " [OK] Copied to: $destPath" -ForegroundColor Green
return $destPath
} -ArgumentList $batFile, (Get-Content $localFile -Raw)
$pushedCount++
} else {
Write-Host "[MISSING] $batFile - not found at $localFile" -ForegroundColor Yellow
$errorCount++
}
}
Write-Host ""
Write-Host "=== Summary ===" -ForegroundColor Cyan
Write-Host "Files pushed: $pushedCount" -ForegroundColor Green
Write-Host "Files missing: $errorCount" -ForegroundColor Yellow
if ($pushedCount -gt 0) {
Write-Host ""
Write-Host "[INFO] Files copied to AD2" -ForegroundColor Cyan
Write-Host "[INFO] Next sync (every 15 min) will push to NAS" -ForegroundColor Cyan
Write-Host "[INFO] Then accessible from DOS machines at T:\COMMON\" -ForegroundColor Cyan
}

View File

@@ -0,0 +1,59 @@
# Quick sync status check
$Username = "INTRANET\sysadmin"
$Password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Sync Status Check - $(Get-Date -Format 'HH:mm:ss')" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
# Check AD2 sync log
Write-Host "[INFO] Recent sync activity on AD2:"
try {
$LogTail = Invoke-Command -ComputerName 192.168.0.6 -Credential $Cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\sync-from-nas.log' -Tail 15
}
$LogTail | ForEach-Object { Write-Host " $_" }
} catch {
Write-Host " [ERROR] Could not read log: $_" -ForegroundColor Red
}
Write-Host ""
Write-Host "[INFO] Checking DEPLOY.BAT on NAS:"
# Check file on NAS
$NASInfo = & 'C:\Windows\System32\OpenSSH\ssh.exe' -o BatchMode=yes root@192.168.0.9 'ls -lh /data/test/DEPLOY.BAT' 2>&1
Write-Host " $NASInfo"
# Verify CRLF
& 'C:\Windows\System32\OpenSSH\scp.exe' -O root@192.168.0.9:/data/test/DEPLOY.BAT ./DEPLOY_CHECK.BAT 2>$null
if (Test-Path "DEPLOY_CHECK.BAT") {
$Content = Get-Content "DEPLOY_CHECK.BAT" -Raw
$Size = (Get-Item "DEPLOY_CHECK.BAT").Length
$OrigSize = (Get-Item "DEPLOY.BAT").Length
Write-Host ""
Write-Host "[INFO] CRLF Verification:"
Write-Host " Original size: $OrigSize bytes"
Write-Host " NAS copy size: $Size bytes"
if ($Content -match "`r`n") {
Write-Host " [SUCCESS] CRLF preserved!" -ForegroundColor Green
} else {
Write-Host " [WARNING] LF only - CRLF not preserved" -ForegroundColor Yellow
}
if ($Size -eq $OrigSize) {
Write-Host " [OK] Sizes match" -ForegroundColor Green
} else {
Write-Host " [WARNING] Size mismatch" -ForegroundColor Yellow
}
Remove-Item "DEPLOY_CHECK.BAT" -Force
}
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1"
}

View File

@@ -0,0 +1,83 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Recreating Sync-FromNAS Task..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
# Task parameters
$taskName = "Sync-FromNAS"
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$logPath = "C:\Shares\test\scripts\sync-from-nas.log"
$taskUser = "INTRANET\sysadmin"
$taskPassword = 'Paper123!@#'
# Remove existing task if it exists
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "[1] Creating task action..." -ForegroundColor Yellow
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument "-ExecutionPolicy Bypass -NonInteractive -File `"$scriptPath`"" `
-WorkingDirectory "C:\Shares\test\scripts"
Write-Host "[2] Creating task trigger (every 15 minutes)..." -ForegroundColor Yellow
$trigger = New-ScheduledTaskTrigger `
-Once `
-At (Get-Date).AddMinutes(1) `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepetitionDuration ([TimeSpan]::MaxValue)
Write-Host "[3] Creating task settings..." -ForegroundColor Yellow
$settings = New-ScheduledTaskSettingsSet `
-AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-StartWhenAvailable `
-ExecutionTimeLimit (New-TimeSpan -Minutes 30) `
-RestartCount 3 `
-RestartInterval (New-TimeSpan -Minutes 1)
Write-Host "[4] Registering task as $taskUser..." -ForegroundColor Yellow
Register-ScheduledTask `
-TaskName $taskName `
-Action $action `
-Trigger $trigger `
-Settings $settings `
-User $taskUser `
-Password $taskPassword `
-RunLevel Highest `
-Description "Sync test data and software updates between NAS and AD2" `
-Force | Out-Null
Write-Host " [OK] Task created successfully" -ForegroundColor Green
Write-Host ""
Write-Host "[5] Verifying task..." -ForegroundColor Yellow
$task = Get-ScheduledTask -TaskName $taskName
Write-Host " User: $($task.Principal.UserId)" -ForegroundColor White
Write-Host " State: $($task.State)" -ForegroundColor White
Write-Host ""
Write-Host "[6] Starting task now..." -ForegroundColor Yellow
Start-ScheduledTask -TaskName $taskName
Write-Host " Waiting 25 seconds for sync to complete..." -ForegroundColor White
Start-Sleep -Seconds 25
Write-Host ""
Write-Host "[7] Checking results..." -ForegroundColor Yellow
$taskInfo = Get-ScheduledTaskInfo -TaskName $taskName
Write-Host " Last Run: $($taskInfo.LastRunTime)" -ForegroundColor White
Write-Host " Last Result: 0x$($taskInfo.LastTaskResult.ToString('X')) $(if ($taskInfo.LastTaskResult -eq 0) { '(SUCCESS)' } else { '(FAILED)' })" -ForegroundColor $(if ($taskInfo.LastTaskResult -eq 0) { "Green" } else { "Red" })
Write-Host " Next Run: $($taskInfo.NextRunTime)" -ForegroundColor White
Write-Host ""
Write-Host "[8] Last 20 lines of sync log..." -ForegroundColor Yellow
if (Test-Path $logPath) {
Get-Content $logPath | Select-Object -Last 20 | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}
}
Write-Host ""
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Task Recreation Complete" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan

View File

@@ -0,0 +1,46 @@
# Remove redundant ECHO lines before PAUSE
# DOS 6.22 PAUSE already displays "Press any key to continue..."
$BATFiles = Get-ChildItem *.BAT | Where-Object {
$_.Name -notlike "*_FROM_*" -and
$_.Name -notlike "*_TEST*" -and
$_.Name -notlike "*_VERIFY*" -and
$_.Name -notlike "*_CHECK*" -and
$_.Name -notlike "*_MONITOR*"
}
Write-Host "[INFO] Removing redundant ECHO before PAUSE" -ForegroundColor Cyan
Write-Host ""
$TotalRemoved = 0
foreach ($File in $BATFiles) {
Write-Host "Processing: $($File.Name)" -ForegroundColor White
$Content = Get-Content $File.FullName -Raw
# Remove "ECHO Press any key..." lines immediately before PAUSE
# Pattern: ECHO Press any key...\r?\n\s*PAUSE
$OriginalContent = $Content
$Content = $Content -replace 'ECHO Press any key[^\r\n]*\r?\n(\s*)PAUSE', '$1PAUSE'
if ($Content -ne $OriginalContent) {
$RemovedCount = ([regex]::Matches($OriginalContent, 'ECHO Press any key')).Count - ([regex]::Matches($Content, 'ECHO Press any key')).Count
Set-Content $File.FullName $Content -NoNewline
Write-Host " [OK] Removed $RemovedCount redundant ECHO lines" -ForegroundColor Green
$TotalRemoved += $RemovedCount
} else {
Write-Host " [OK] No redundant ECHO lines found" -ForegroundColor Green
}
}
Write-Host ""
Write-Host "[SUCCESS] Removed $TotalRemoved redundant ECHO lines" -ForegroundColor Green
Write-Host ""
Write-Host "DOS 6.22 PAUSE displays:" -ForegroundColor Cyan
Write-Host " 'Press any key to continue . . .'" -ForegroundColor White
Write-Host ""
Write-Host "No need for ECHO before PAUSE unless:" -ForegroundColor Cyan
Write-Host " - Custom message needed (not 'Press any key...')" -ForegroundColor White
Write-Host ""

View File

@@ -0,0 +1,23 @@
# Restart GuruRMM Agent on AD2 via SSH
# Simple approach using SSH to run PowerShell commands
Write-Host "[INFO] Attempting to restart GuruRMM agent on AD2..."
# Try SSH connection (requires VPN to be connected to Dataforth network)
Write-Host "[INFO] Connecting via SSH to 192.168.0.6..."
# Command to run on AD2
$command = "powershell -Command `"Restart-Service gururmm-agent -Force; Start-Sleep -Seconds 2; Get-Service gururmm-agent`""
# Try to execute
try {
# Use native Windows SSH (requires password to be entered manually)
Write-Host "[INFO] Please enter password when prompted: Paper123!@#"
ssh "INTRANET\sysadmin@192.168.0.6" $command
} catch {
Write-Host "[ERROR] SSH connection failed: $_"
Write-Host ""
Write-Host "Alternative: Restart service manually on AD2"
Write-Host "1. RDP to 192.168.0.6"
Write-Host "2. Run: Restart-Service gururmm-agent"
}

View File

@@ -0,0 +1,121 @@
# Restore backup and properly fix the sync script
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Restoring and Fixing Sync Script ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$scriptsDir = "C:\Shares\test\scripts"
Write-Host "[1] Finding most recent backup" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$backups = Get-ChildItem "$scriptsDir\Sync-FromNAS.ps1.backup-*" | Sort-Object LastWriteTime -Descending
$latestBackup = $backups | Select-Object -First 1
if ($latestBackup) {
Write-Host "[OK] Found backup: $($latestBackup.Name)" -ForegroundColor Green
Write-Host " Created: $($latestBackup.LastWriteTime)" -ForegroundColor Gray
# Restore the backup
Copy-Item -Path $latestBackup.FullName -Destination $scriptPath -Force
Write-Host "[OK] Restored backup" -ForegroundColor Green
} else {
Write-Host "[WARNING] No backup found - using current script" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[2] Reading original script to understand structure" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$lines = Get-Content $scriptPath
# Find the PSCP/PLINK lines and the actual function implementations
for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match '^\$PSCP\s*=') {
Write-Host "Line $($i+1): $($lines[$i])" -ForegroundColor Cyan
}
if ($lines[$i] -match '^\$PLINK\s*=') {
Write-Host "Line $($i+1): $($lines[$i])" -ForegroundColor Cyan
}
if ($lines[$i] -match 'PSCP.*-ssh.*-pw') {
Write-Host "Line $($i+1) [PSCP call]: ...$(($lines[$i] -replace '.*(\$PSCP.*)', '$1'))" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "[3] Applying targeted fixes" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Just replace the tool paths and add better error logging
# Don't try to rewrite the functions - just improve what's there
for ($i = 0; $i -lt $lines.Count; $i++) {
# Replace tool paths
if ($lines[$i] -match '^\$PSCP\s*=\s*".*pscp\.exe"') {
$lines[$i] = '$SCP = "C:\Program Files\OpenSSH\scp.exe" # Changed from PSCP to OpenSSH'
Write-Host "[UPDATED] Line $($i+1): Tool path PSCP -> SCP" -ForegroundColor Green
}
if ($lines[$i] -match '^\$PLINK\s*=\s*".*plink\.exe"') {
$lines[$i] = '$SSH = "C:\Program Files\OpenSSH\ssh.exe" # Changed from PLINK to OpenSSH'
Write-Host "[UPDATED] Line $($i+1): Tool path PLINK -> SSH" -ForegroundColor Green
}
# Replace PSCP calls with SCP calls and add verbose flag
if ($lines[$i] -match '\$result\s*=\s*&\s*\$PSCP\s+-ssh\s+-pw\s+\$NAS_PASSWORD\s+-hostkey\s+\$NAS_HOSTKEY') {
# This is a pscp call - replace with scp
if ($lines[$i] -match 'LocalPath.*RemotePath') {
# This is Copy-ToNAS (local first, then remote)
$lines[$i] = ' $result = & $SCP -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$SCRIPTS_DIR\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes $LocalPath "${NAS_USER}@${NAS_IP}:$RemotePath" 2>&1'
Write-Host "[UPDATED] Line $($i+1): Copy-ToNAS PSCP -> SCP" -ForegroundColor Green
} else {
# This is Copy-FromNAS (remote first, then local)
$lines[$i] = ' $result = & $SCP -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$SCRIPTS_DIR\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes "${NAS_USER}@${NAS_IP}:$RemotePath" $LocalPath 2>&1'
Write-Host "[UPDATED] Line $($i+1): Copy-FromNAS PSCP -> SCP" -ForegroundColor Green
}
# Add error logging on the next non-empty line after "return $LASTEXITCODE"
for ($j = $i + 1; $j -lt $lines.Count; $j++) {
if ($lines[$j] -match 'return \$LASTEXITCODE') {
# Insert error logging before the return
$lines[$j] = " if (`$LASTEXITCODE -ne 0) { Write-Log `" SCP ERROR (exit $LASTEXITCODE): `$result`" }`n" + $lines[$j]
Write-Host "[ADDED] Line $($j+1): Error logging" -ForegroundColor Green
break
}
}
}
# Replace PLINK calls with SSH calls
if ($lines[$i] -match '\&\s*\$PLINK\s+-batch') {
$lines[$i] = $lines[$i] -replace '\$PLINK\s+-batch', '$SSH -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$SCRIPTS_DIR\.ssh\known_hosts" -o PreferredAuthentications=password -o PubkeyAuthentication=no -o PasswordAuthentication=yes'
Write-Host "[UPDATED] Line $($i+1): PLINK -> SSH" -ForegroundColor Green
}
}
Write-Host ""
Write-Host "[4] Saving updated script" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Save the modified script
$lines | Out-File -FilePath $scriptPath -Encoding UTF8 -Force
Write-Host "[OK] Script saved" -ForegroundColor Green
Write-Host ""
Write-Host "[5] Testing script syntax" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Test if the script has valid syntax
try {
$null = [System.Management.Automation.PSParser]::Tokenize((Get-Content $scriptPath -Raw), [ref]$null)
Write-Host "[OK] Script syntax is valid" -ForegroundColor Green
} catch {
Write-Host "[ERROR] Script has syntax errors: $($_.Exception.Message)" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "=== Fix Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,15 @@
# Restore original api.js from backup
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Restoring original api.js from backup..." -ForegroundColor Yellow
Copy-Item "AD2:\Shares\testdatadb\routes\api.js.backup-2026-01-21-124402" "AD2:\Shares\testdatadb\routes\api.js" -Force
Write-Host "[OK] Original file restored" -ForegroundColor Green
Write-Host "[ACTION] Restart Node.js: taskkill /F /IM node.exe && cd C:\Shares\testdatadb && node server.js" -ForegroundColor Yellow
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,60 @@
# Run sync directly and capture detailed output
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Running Sync Directly ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$scriptPath = "C:\Shares\test\scripts\Sync-FromNAS.ps1"
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "[1] Getting log position" -ForegroundColor Yellow
$logSize = (Get-Item $logFile).Length
Write-Host "[2] Running sync..." -ForegroundColor Yellow
Write-Host ""
# Run sync and capture output
& powershell.exe -ExecutionPolicy Bypass -File $scriptPath 2>&1 | Out-Null
Write-Host "[3] Checking new log entries for SCP errors" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Start-Sleep -Seconds 2
$newLogSize = (Get-Item $logFile).Length
$newBytes = $newLogSize - $logSize
if ($newBytes -gt 0) {
$allContent = Get-Content $logFile -Raw
$newContent = $allContent.Substring([math]::Max(0, $allContent.Length - $newBytes - 500))
# Look specifically for SCP PUSH ERROR
$scpErrors = $newContent -split "`n" | Where-Object { $_ -match "SCP PUSH ERROR" }
if ($scpErrors) {
Write-Host "[SUCCESS] Found detailed SCP errors!" -ForegroundColor Green
Write-Host ""
$scpErrors | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
} else {
# Show all errors
Write-Host "[INFO] No 'SCP PUSH ERROR' found. Showing all errors:" -ForegroundColor Yellow
Write-Host ""
$allErrors = $newContent -split "`n" | Where-Object { $_ -match "ERROR" }
if ($allErrors) {
$allErrors | Select-Object -First 10 | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
} else {
Write-Host "[INFO] No errors in this sync run!" -ForegroundColor Green
}
}
} else {
Write-Host "[WARNING] No new log entries detected" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "=== Sync Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-ChildItem C:\Shares\test -Recurse -Filter '*menux*.bas' -ErrorAction SilentlyContinue | Select-Object FullName, LastWriteTime, Length
}

View File

@@ -0,0 +1,151 @@
# Setup OpenSSH-based sync for AD2 -> NAS transfers
# This replaces PuTTY (pscp/plink) with OpenSSH (scp/ssh)
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Setting Up OpenSSH Sync (AD2 -> NAS) ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$NAS_IP = "192.168.0.9"
$NAS_USER = "root"
$SCRIPTS_DIR = "C:\Shares\test\scripts"
$SSH_DIR = "$SCRIPTS_DIR\.ssh"
$KNOWN_HOSTS = "$SSH_DIR\known_hosts"
Write-Host "[1] Creating SSH directory for sync keys" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
if (-not (Test-Path $SSH_DIR)) {
New-Item -ItemType Directory -Path $SSH_DIR -Force | Out-Null
Write-Host "[OK] Created: $SSH_DIR" -ForegroundColor Green
} else {
Write-Host "[OK] Directory exists: $SSH_DIR" -ForegroundColor Green
}
# Set permissions (only SYSTEM and Administrators)
$acl = Get-Acl $SSH_DIR
$acl.SetAccessRuleProtection($true, $false)
$acl.Access | ForEach-Object { $acl.RemoveAccessRule($_) | Out-Null }
# Add SYSTEM
$systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
"SYSTEM", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
)
$acl.AddAccessRule($systemRule)
# Add Administrators
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
"Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
)
$acl.AddAccessRule($adminRule)
Set-Acl -Path $SSH_DIR -AclObject $acl
Write-Host "[OK] Set secure permissions on SSH directory" -ForegroundColor Green
Write-Host ""
Write-Host "[2] Generating SSH key for NAS sync (ED25519)" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$keyPath = "$SSH_DIR\id_ed25519_nas"
if (Test-Path $keyPath) {
Write-Host "[SKIP] Key already exists: $keyPath" -ForegroundColor Yellow
Write-Host " Using existing key" -ForegroundColor Gray
} else {
# Generate SSH key without passphrase
& "C:\Program Files\OpenSSH\ssh-keygen.exe" -t ed25519 -f $keyPath -N '""' -C "AD2-NAS-Sync"
if (Test-Path $keyPath) {
Write-Host "[OK] Generated SSH key: $keyPath" -ForegroundColor Green
} else {
Write-Host "[ERROR] Failed to generate SSH key" -ForegroundColor Red
return
}
}
# Read public key
$pubKey = Get-Content "$keyPath.pub"
Write-Host ""
Write-Host "Public key to add to NAS:" -ForegroundColor Cyan
Write-Host $pubKey -ForegroundColor White
Write-Host ""
Write-Host "[3] Adding NAS host key to known_hosts" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
# Get NAS host key using ssh-keyscan
$nasHostKey = & "C:\Program Files\OpenSSH\ssh-keyscan.exe" -H $NAS_IP 2>$null
if ($nasHostKey) {
$nasHostKey | Out-File -FilePath $KNOWN_HOSTS -Encoding ASCII -Append
Write-Host "[OK] Added NAS host key to known_hosts" -ForegroundColor Green
} else {
Write-Host "[WARNING] Could not retrieve NAS host key" -ForegroundColor Yellow
Write-Host " Will use StrictHostKeyChecking=accept-new" -ForegroundColor Gray
}
Write-Host ""
Write-Host "[4] Testing SSH connection to NAS (with password first)" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host "Attempting to copy public key to NAS..." -ForegroundColor White
Write-Host ""
# Note: We need to manually add the public key to NAS /root/.ssh/authorized_keys
Write-Host "[ACTION REQUIRED] Add public key to NAS" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host ""
Write-Host "Run this on the NAS (192.168.0.9) as root:" -ForegroundColor Cyan
Write-Host ""
Write-Host "mkdir -p ~/.ssh" -ForegroundColor White
Write-Host "chmod 700 ~/.ssh" -ForegroundColor White
Write-Host "echo '$pubKey' >> ~/.ssh/authorized_keys" -ForegroundColor White
Write-Host "chmod 600 ~/.ssh/authorized_keys" -ForegroundColor White
Write-Host ""
Write-Host "Or from AD2 (requires NAS password):" -ForegroundColor Cyan
Write-Host "ssh root@$NAS_IP 'mkdir -p ~/.ssh && chmod 700 ~/.ssh'" -ForegroundColor White
Write-Host "ssh root@$NAS_IP 'echo `"$pubKey`" >> ~/.ssh/authorized_keys'" -ForegroundColor White
Write-Host "ssh root@$NAS_IP 'chmod 600 ~/.ssh/authorized_keys'" -ForegroundColor White
Write-Host ""
Write-Host "[5] Backing up current sync script" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$scriptPath = "$SCRIPTS_DIR\Sync-FromNAS.ps1"
$backupPath = "$SCRIPTS_DIR\Sync-FromNAS.ps1.backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
if (Test-Path $scriptPath) {
Copy-Item -Path $scriptPath -Destination $backupPath -Force
Write-Host "[OK] Backup created: $backupPath" -ForegroundColor Green
} else {
Write-Host "[WARNING] Original script not found: $scriptPath" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[6] Configuration Summary" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host "SSH Directory: $SSH_DIR" -ForegroundColor White
Write-Host "Private Key: $keyPath" -ForegroundColor White
Write-Host "Public Key: $keyPath.pub" -ForegroundColor White
Write-Host "Known Hosts: $KNOWN_HOSTS" -ForegroundColor White
Write-Host "NAS IP: $NAS_IP" -ForegroundColor White
Write-Host "NAS User: $NAS_USER" -ForegroundColor White
Write-Host ""
# Return the public key for NAS setup
return @{
PublicKey = $pubKey
KeyPath = $keyPath
KnownHosts = $KNOWN_HOSTS
}
}
Write-Host ""
Write-Host "=== Setup Phase 1 Complete ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Add the public key to NAS (shown above)" -ForegroundColor White
Write-Host "2. Test SSH key authentication" -ForegroundColor White
Write-Host "3. Update Sync-FromNAS.ps1 to use OpenSSH" -ForegroundColor White
Write-Host ""

View File

@@ -0,0 +1,41 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..."
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
Write-Host "[OK] Checking testdatadb..."
if (Test-Path "AD2:\Shares\testdatadb") {
Write-Host " [FOUND] testdatadb exists"
Write-Host "`n[OK] Top-level contents:"
Get-ChildItem "AD2:\Shares\testdatadb" | Select-Object Mode, Name, Length
Write-Host "`n[OK] Database folder contents:"
if (Test-Path "AD2:\Shares\testdatadb\database") {
Get-ChildItem "AD2:\Shares\testdatadb\database" | Select-Object Mode, Name, Length
}
Write-Host "`n[OK] Retrieving import.js..."
if (Test-Path "AD2:\Shares\testdatadb\database\import.js") {
$importJs = Get-Content "AD2:\Shares\testdatadb\database\import.js" -Raw
$importJs | Out-File "D:\ClaudeTools\import-js-retrieved.js" -Encoding UTF8
Write-Host " [OK] Saved to D:\ClaudeTools\import-js-retrieved.js"
Write-Host " [INFO] File size: $($importJs.Length) bytes"
}
Write-Host "`n[OK] Checking for database file..."
$dbFiles = Get-ChildItem "AD2:\Shares\testdatadb" -Recurse -Include "*.db","*.sqlite","*.sqlite3" -ErrorAction SilentlyContinue
if ($dbFiles) {
Write-Host " [FOUND] Database files:"
$dbFiles | Select-Object FullName, Length
} else {
Write-Host " [INFO] No .db or .sqlite files found"
}
} else {
Write-Host " [NOT FOUND] testdatadb does not exist"
}
Remove-PSDrive -Name AD2
Write-Host "`n[OK] Done"

View File

@@ -0,0 +1,80 @@
# Stop any running GuruRMM agent processes and install service
Write-Host "[INFO] Stopping any running GuruRMM agent processes..."
# Check for running processes
$processes = Get-Process -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($processes) {
Write-Host "[WARNING] Found $($processes.Count) running agent process(es)"
foreach ($proc in $processes) {
Write-Host " Killing PID $($proc.Id)..."
Stop-Process -Id $proc.Id -Force
}
Start-Sleep -Seconds 2
Write-Host "[OK] Processes stopped"
} else {
Write-Host "[INFO] No running agent processes found"
}
# Check for any service (even if not registered properly)
try {
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
Write-Host "[WARNING] Found service - stopping..."
Stop-Service -Name "gururmm-agent" -Force
Start-Sleep -Seconds 2
}
} catch {
# Service might not exist, that's OK
}
# Now install
Write-Host ""
Write-Host "[INFO] Installing GuruRMM agent as service on AD2..."
$serverUrl = "wss://rmm-api.azcomputerguru.com/ws"
$apiKey = "SWIFT-CLOUD-6910"
$agentPath = "C:\Program Files\GuruRMM\gururmm-agent.exe"
if (!(Test-Path $agentPath)) {
Write-Host "[ERROR] Agent binary not found at $agentPath"
exit 1
}
Write-Host "[OK] Agent binary found"
Write-Host "[INFO] Installing agent as service..."
Write-Host " Server URL: $serverUrl"
Write-Host " API Key: $apiKey"
& $agentPath install --server-url $serverUrl --api-key $apiKey
if ($LASTEXITCODE -ne 0) {
Write-Host "[ERROR] Installation failed with exit code: $LASTEXITCODE"
exit 1
}
Start-Sleep -Seconds 2
# Verify service was created
$service = Get-Service -Name "gururmm-agent" -ErrorAction SilentlyContinue
if ($service) {
Write-Host "[OK] Service created successfully"
Write-Host " Name: $($service.Name)"
Write-Host " Status: $($service.Status)"
Write-Host " Start Type: $($service.StartType)"
if ($service.Status -ne "Running") {
Write-Host "[INFO] Starting service..."
Start-Service -Name "gururmm-agent"
Start-Sleep -Seconds 2
$service = Get-Service -Name "gururmm-agent"
Write-Host "[OK] Service status: $($service.Status)"
}
} else {
Write-Host "[ERROR] Service was not created"
exit 1
}
Write-Host ""
Write-Host "[SUCCESS] GuruRMM agent installed and running on AD2!"

View File

@@ -0,0 +1,13 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$files = @('CHECKUPD.BAT', 'CTONW.BAT', 'DEPLOY.BAT', 'UPDATE.BAT')
foreach ($file in $files) {
$path = "C:\Shares\test\COMMON\ProdSW\$file"
if (Test-Path $path) {
$item = Get-Item $path
Write-Host "$file - $($item.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss'))"
}
}
}

View File

@@ -0,0 +1,20 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "=== Checking AD2 BAT files ===" -ForegroundColor Cyan
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$files = @('CHECKUPD.BAT', 'CTONW.BAT', 'DEPLOY.BAT', 'UPDATE.BAT')
foreach ($file in $files) {
$path = "C:\Shares\test\COMMON\ProdSW\$file"
if (Test-Path $path) {
$item = Get-Item $path
Write-Host "$file - Last Modified: $($item.LastWriteTime)" -ForegroundColor Green
} else {
Write-Host "$file - NOT FOUND" -ForegroundColor Red
}
}
}
Write-Host ""
Write-Host "=== Checking NAS BAT files ===" -ForegroundColor Cyan
# Connect to NAS via SSH and check files

View File

@@ -0,0 +1,15 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "=== Scheduled Task Info ===" -ForegroundColor Cyan
Get-ScheduledTask -TaskName "*Sync*" -ErrorAction SilentlyContinue | ForEach-Object {
$task = $_
$info = Get-ScheduledTaskInfo -TaskName $task.TaskName -ErrorAction SilentlyContinue
Write-Host "`nTask: $($task.TaskName)" -ForegroundColor Yellow
Write-Host "State: $($task.State)"
Write-Host "Last Run: $($info.LastRunTime)"
Write-Host "Last Result: $($info.LastTaskResult)"
Write-Host "Next Run: $($info.NextRunTime)"
}
}

View File

@@ -0,0 +1,7 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "Looking for sync script..."
Get-ChildItem 'C:\Shares\test' -Recurse -Filter "sync*.ps1" -ErrorAction SilentlyContinue | Select-Object FullName, LastWriteTime
}

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\sync-from-nas.log' | Select-Object -Last 100
}

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' | Select-Object -First 100 | Select-String -Pattern "NAS_|scp|192.168" -Context 1,1
}

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\sync-from-nas.ps1' | Select-String -Pattern "NAS_HOST|NAS_USER|NAS_BASE|scp" -Context 0,2
}

View File

@@ -0,0 +1,6 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-Content 'C:\Shares\test\scripts\Sync-FromNAS.ps1' | Select-Object -First 50
}

View File

@@ -0,0 +1,13 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Searching for database folders on AD2..."
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Get-ChildItem C:\ -Directory | Where-Object Name -like '*database*' | Select-Object FullName
}
Write-Host "`n[OK] Checking Sync-FromNAS.ps1 for database references..."
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
$content = Get-Content C:\Shares\test\scripts\Sync-FromNAS.ps1 -Raw
$content | Select-String -Pattern "(database|sql|connection|sqlite|mysql|postgres)" -AllMatches -Context 5,5 | Select-Object -First 10
}

View File

@@ -0,0 +1,58 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing Network Connectivity from AD2 to NAS..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Testing ping to NAS (192.168.0.9)..." -ForegroundColor Yellow
$ping = Test-Connection -ComputerName 192.168.0.9 -Count 2 -ErrorAction SilentlyContinue
if ($ping) {
Write-Host " [OK] Ping successful - average: $($ping | Measure-Object -Property ResponseTime -Average | Select-Object -ExpandProperty Average)ms" -ForegroundColor Green
} else {
Write-Host " [ERROR] Ping failed" -ForegroundColor Red
}
Write-Host ""
Write-Host "[2] Testing TCP connection to port 22..." -ForegroundColor Yellow
$tcpTest = Test-NetConnection -ComputerName 192.168.0.9 -Port 22 -InformationLevel Detailed -WarningAction SilentlyContinue
Write-Host " TCP Connection: $($tcpTest.TcpTestSucceeded)" -ForegroundColor $(if ($tcpTest.TcpTestSucceeded) { "Green" } else { "Red" })
Write-Host " Ping: $($tcpTest.PingSucceeded)" -ForegroundColor White
Write-Host " Route: $($tcpTest.InterfaceAlias)" -ForegroundColor White
Write-Host ""
Write-Host "[3] Checking Windows Firewall outbound rules..." -ForegroundColor Yellow
$firewallRule = Get-NetFirewallRule | Where-Object { $_.Direction -eq "Outbound" -and $_.Action -eq "Block" } | Select-Object -First 5
if ($firewallRule) {
Write-Host " Found $($firewallRule.Count) outbound block rules (showing first 5)" -ForegroundColor Yellow
} else {
Write-Host " No outbound block rules found" -ForegroundColor Green
}
Write-Host ""
Write-Host "[4] Checking current user SSH directory..." -ForegroundColor Yellow
$sshDir = "$env:USERPROFILE\.ssh"
if (Test-Path $sshDir) {
Write-Host " SSH directory exists: $sshDir" -ForegroundColor Green
$files = Get-ChildItem $sshDir -ErrorAction SilentlyContinue
if ($files) {
Write-Host " Contents:" -ForegroundColor White
$files | ForEach-Object { Write-Host " $($_.Name)" -ForegroundColor Gray }
}
} else {
Write-Host " [WARNING] No .ssh directory found" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[5] Trying telnet-style connection test..." -ForegroundColor Yellow
try {
$socket = New-Object System.Net.Sockets.TcpClient
$socket.Connect("192.168.0.9", 22)
if ($socket.Connected) {
Write-Host " [OK] Raw TCP socket connection successful" -ForegroundColor Green
$socket.Close()
}
} catch {
Write-Host " [ERROR] Raw TCP socket connection failed: $($_.Exception.Message)" -ForegroundColor Red
}
}

View File

@@ -0,0 +1,72 @@
# Test database directly to see if it's corrupted or locked
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "[OK] Mounting AD2 C$ share..." -ForegroundColor Green
New-PSDrive -Name AD2 -PSProvider FileSystem -Root "\\192.168.0.6\C$" -Credential $cred -ErrorAction Stop | Out-Null
$dbPath = "AD2:\Shares\testdatadb\database\testdata.db"
Write-Host "[OK] Testing database file access..." -ForegroundColor Green
# Test 1: File exists and readable
if (Test-Path $dbPath) {
Write-Host " [OK] Database file exists" -ForegroundColor Green
$dbFile = Get-Item $dbPath
Write-Host " [OK] Size: $([math]::Round($dbFile.Length/1MB,2)) MB" -ForegroundColor Cyan
Write-Host " [OK] Modified: $($dbFile.LastWriteTime)" -ForegroundColor Cyan
} else {
Write-Host " [ERROR] Database file not found!" -ForegroundColor Red
Remove-PSDrive -Name AD2
exit 1
}
# Test 2: Check file lock
Write-Host "`n[OK] Checking if file is locked..." -ForegroundColor Green
try {
$stream = [System.IO.File]::Open($dbFile.FullName, 'Open', 'Read', 'ReadWrite')
$stream.Close()
Write-Host " [OK] File is not locked" -ForegroundColor Green
} catch {
Write-Host " [WARNING] File may be locked by another process" -ForegroundColor Yellow
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor Yellow
}
# Test 3: Check file header (SQLite magic bytes)
Write-Host "`n[OK] Checking SQLite file header..." -ForegroundColor Green
try {
$bytes = [System.IO.File]::ReadAllBytes($dbFile.FullName) | Select-Object -First 16
$header = [System.Text.Encoding]::ASCII.GetString($bytes)
if ($header.StartsWith("SQLite format 3")) {
Write-Host " [OK] Valid SQLite database header detected" -ForegroundColor Green
} else {
Write-Host " [ERROR] Invalid SQLite header! Database may be corrupted" -ForegroundColor Red
Write-Host " Header bytes: $($bytes -join ' ')" -ForegroundColor Yellow
}
} catch {
Write-Host " [ERROR] Cannot read database file: $($_.Exception.Message)" -ForegroundColor Red
}
# Test 4: Check permissions
Write-Host "`n[OK] Checking file permissions..." -ForegroundColor Green
$acl = Get-Acl $dbPath
Write-Host " Owner: $($acl.Owner)" -ForegroundColor Cyan
Write-Host " Access Rules:" -ForegroundColor Cyan
$acl.Access | ForEach-Object {
Write-Host " $($_.IdentityReference): $($_.FileSystemRights) ($($_.AccessControlType))" -ForegroundColor Gray
}
# Test 5: Check if there are journal files
Write-Host "`n[OK] Checking for journal files..." -ForegroundColor Green
$journalFile = Get-Item "$($dbFile.DirectoryName)\testdata.db-journal" -ErrorAction SilentlyContinue
if ($journalFile) {
Write-Host " [FOUND] Journal file exists: $([math]::Round($journalFile.Length/1KB,2)) KB" -ForegroundColor Yellow
Write-Host " [WARNING] This may indicate incomplete transaction or crash" -ForegroundColor Yellow
} else {
Write-Host " [OK] No journal file (clean state)" -ForegroundColor Green
}
Remove-PSDrive -Name AD2 -ErrorAction SilentlyContinue
Write-Host "`n[OK] Done" -ForegroundColor Green

View File

@@ -0,0 +1,63 @@
# Test error logging by attempting a known-failing file push
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Testing Error Logging ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Loading sync script to test Copy-ToNAS" -ForegroundColor Yellow
# Dot-source the sync script to load functions
. "C:\Shares\test\scripts\Sync-FromNAS.ps1"
Write-Host "[2] Attempting to push a file that will fail" -ForegroundColor Yellow
Write-Host " (lowercase .dat file in HVDATA subdirectory)" -ForegroundColor Gray
Write-Host ""
# Try pushing one of the known-failing files
$testFile = "C:\Shares\test\TS-1L\ProdSW\HVDATA\hvin.dat"
if (Test-Path $testFile) {
Write-Host "[OK] Test file exists: $testFile" -ForegroundColor Green
Write-Host "[TESTING] Calling Copy-ToNAS..." -ForegroundColor Cyan
# Call Copy-ToNAS directly
$result = Copy-ToNAS -LocalPath $testFile -RemotePath "/data/test/TS-1L/ProdSW/HVDATA/hvin.dat"
Write-Host ""
if ($result) {
Write-Host "[UNEXPECTED] File pushed successfully!" -ForegroundColor Yellow
} else {
Write-Host "[EXPECTED] File push failed" -ForegroundColor Green
}
Write-Host ""
Write-Host "[3] Checking log for detailed error" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$recentLog = Get-Content "C:\Shares\test\scripts\sync-from-nas.log" -Tail 5
$scpError = $recentLog | Where-Object { $_ -match "SCP PUSH ERROR" }
if ($scpError) {
Write-Host "[SUCCESS] Detailed error logged!" -ForegroundColor Green
Write-Host ""
$scpError | ForEach-Object {
Write-Host $_ -ForegroundColor Red
}
} else {
Write-Host "[FAIL] No detailed SCP error found in recent log" -ForegroundColor Red
Write-Host ""
Write-Host "Recent log entries:" -ForegroundColor Yellow
$recentLog | ForEach-Object {
Write-Host " $_" -ForegroundColor Gray
}
}
} else {
Write-Host "[ERROR] Test file not found: $testFile" -ForegroundColor Red
}
}
Write-Host ""
Write-Host "=== Test Complete ===" -ForegroundColor Cyan

View File

@@ -0,0 +1,32 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing SSH After Adding Key..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Testing SSH as sysadmin user..." -ForegroundColor Yellow
$result = & ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "hostname" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [SUCCESS] SSH works! Result: $result" -ForegroundColor Green
} else {
Write-Host " [FAILED] SSH failed: $result" -ForegroundColor Red
Write-Host " Exit code: $LASTEXITCODE" -ForegroundColor Red
}
Write-Host ""
Write-Host "[2] Testing find command..." -ForegroundColor Yellow
$findResult = & ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no root@192.168.0.9 "find /data/test/TS-4R/LOGS -name '*.DAT' -type f -mmin -1440 2>/dev/null | wc -l" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [SUCCESS] Find command works! Found: $findResult DAT files" -ForegroundColor Green
} else {
Write-Host " [FAILED] Find failed: $findResult" -ForegroundColor Red
}
Write-Host ""
Write-Host "[3] Manually running sync script..." -ForegroundColor Yellow
& powershell.exe -ExecutionPolicy Bypass -File "C:\Shares\test\scripts\Sync-FromNAS.ps1"
}
Write-Host ""
Write-Host "Test complete!" -ForegroundColor Cyan

View File

@@ -0,0 +1,56 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing Direct SSH Execution from AD2..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Checking known_hosts..." -ForegroundColor Yellow
$knownHosts = Get-Content "$env:USERPROFILE\.ssh\known_hosts" -ErrorAction SilentlyContinue
if ($knownHosts -match "192.168.0.9") {
Write-Host " [OK] NAS entry found in known_hosts" -ForegroundColor Green
} else {
Write-Host " [WARNING] NAS not in known_hosts" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[2] Testing SSH with explicit key..." -ForegroundColor Yellow
$sshCmd = "C:\Program Files\OpenSSH\ssh.exe"
$sshKey = "$env:USERPROFILE\.ssh\id_ed25519"
Write-Host " Command: $sshCmd -i $sshKey -o ConnectTimeout=5 root@192.168.0.9 hostname" -ForegroundColor Gray
$process = Start-Process -FilePath $sshCmd -ArgumentList "-i",$sshKey,"-o","ConnectTimeout=5","-o","StrictHostKeyChecking=no","root@192.168.0.9","hostname" -NoNewWindow -Wait -PassThru -RedirectStandardOutput "$env:TEMP\ssh_test_out.txt" -RedirectStandardError "$env:TEMP\ssh_test_err.txt"
$stdout = Get-Content "$env:TEMP\ssh_test_out.txt" -ErrorAction SilentlyContinue
$stderr = Get-Content "$env:TEMP\ssh_test_err.txt" -ErrorAction SilentlyContinue
Write-Host " Exit code: $($process.ExitCode)" -ForegroundColor White
if ($stdout) { Write-Host " STDOUT: $stdout" -ForegroundColor Green }
if ($stderr) { Write-Host " STDERR: $stderr" -ForegroundColor Red }
Write-Host ""
Write-Host "[3] Testing with plink (PuTTY) if available..." -ForegroundColor Yellow
$plink = Get-Command plink -ErrorAction SilentlyContinue
if ($plink) {
Write-Host " Found plink at: $($plink.Source)" -ForegroundColor Green
$plinkResult = & plink -batch root@192.168.0.9 hostname 2>&1
Write-Host " Result: $plinkResult" -ForegroundColor White
} else {
Write-Host " Plink not found" -ForegroundColor Gray
}
Write-Host ""
Write-Host "[4] Testing SCP file transfer..." -ForegroundColor Yellow
$testFile = "$env:TEMP\test_scp_$(Get-Date -Format 'HHmmss').txt"
"TEST" | Out-File -FilePath $testFile -Encoding ASCII
$scpCmd = "C:\Program Files\OpenSSH\scp.exe"
$process = Start-Process -FilePath $scpCmd -ArgumentList "-o","ConnectTimeout=5","-o","StrictHostKeyChecking=no",$testFile,"root@192.168.0.9:/tmp/" -NoNewWindow -Wait -PassThru -RedirectStandardError "$env:TEMP\scp_test_err.txt"
$scpErr = Get-Content "$env:TEMP\scp_test_err.txt" -ErrorAction SilentlyContinue
Write-Host " SCP Exit code: $($process.ExitCode)" -ForegroundColor White
if ($scpErr) { Write-Host " SCP STDERR: $scpErr" -ForegroundColor Red }
Remove-Item $testFile -ErrorAction SilentlyContinue
}

View File

@@ -0,0 +1,39 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing SSH from AD2 to NAS..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Checking SSH executable..." -ForegroundColor Yellow
$sshPath = Get-Command ssh -ErrorAction SilentlyContinue
if ($sshPath) {
Write-Host " SSH found at: $($sshPath.Source)" -ForegroundColor Green
} else {
Write-Host " [ERROR] SSH not found in PATH" -ForegroundColor Red
}
Write-Host ""
Write-Host "[2] Testing basic SSH connection (timeout 5s)..." -ForegroundColor Yellow
try {
$result = & ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "echo CONNECTED" 2>&1
Write-Host " Result: $result" -ForegroundColor White
Write-Host " Exit code: $LASTEXITCODE" -ForegroundColor White
} catch {
Write-Host " [ERROR] Exception: $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host ""
Write-Host "[3] Checking SSH key auth..." -ForegroundColor Yellow
$sshKeyPath = "$env:USERPROFILE\.ssh\id_rsa"
if (Test-Path $sshKeyPath) {
Write-Host " SSH key exists at: $sshKeyPath" -ForegroundColor Green
} else {
Write-Host " [WARNING] No SSH key found at: $sshKeyPath" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "[4] Testing with verbose SSH..." -ForegroundColor Yellow
$verboseResult = & ssh -v -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "echo OK" 2>&1 | Select-Object -Last 10
$verboseResult | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }
}

View File

@@ -0,0 +1,34 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing SSH After Agent Fix..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Quick hostname test..." -ForegroundColor Yellow
$result = & ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 "hostname" 2>&1
Write-Host " Result: $result" -ForegroundColor $(if ($LASTEXITCODE -eq 0) { "Green" } else { "Red" })
Write-Host " Exit code: $LASTEXITCODE" -ForegroundColor White
Write-Host ""
Write-Host "[2] Testing find command (what was hanging sync)..." -ForegroundColor Yellow
$findResult = & ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no root@192.168.0.9 "find /data/test/TS-4R/LOGS -name '*.DAT' -type f 2>/dev/null | head -3" 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] Find command worked!" -ForegroundColor Green
Write-Host " Sample files: $($findResult -join ', ')" -ForegroundColor Gray
} else {
Write-Host " [ERROR] Find command failed: $findResult" -ForegroundColor Red
}
Write-Host ""
Write-Host "[3] Testing SCP..." -ForegroundColor Yellow
$testFile = "$env:TEMP\scp_test.txt"
"TEST" | Out-File $testFile -Encoding ASCII
$scpResult = & scp -o ConnectTimeout=5 -o StrictHostKeyChecking=no $testFile root@192.168.0.9:/tmp/ 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] SCP worked!" -ForegroundColor Green
} else {
Write-Host " [ERROR] SCP failed: $scpResult" -ForegroundColor Red
}
Remove-Item $testFile -ErrorAction SilentlyContinue
}

View File

@@ -0,0 +1,28 @@
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)
Write-Host "Testing SSH via CMD instead of PowerShell..." -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Testing SSH via cmd.exe..." -ForegroundColor Yellow
$cmdResult = cmd /c "echo | C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@192.168.0.9 hostname 2>&1"
Write-Host " Result: $cmdResult" -ForegroundColor White
Write-Host ""
Write-Host "[2] Checking if SSH is hanging on key auth..." -ForegroundColor Yellow
$cmdResult2 = cmd /c "echo | C:\Progra~1\OpenSSH\ssh.exe -o ConnectTimeout=5 -o StrictHostKeyChecking=no -o BatchMode=yes root@192.168.0.9 hostname 2>&1"
Write-Host " Result with BatchMode: $cmdResult2" -ForegroundColor White
Write-Host ""
Write-Host "[3] Killing any stuck SSH processes..." -ForegroundColor Yellow
$sshProcs = Get-Process -Name ssh -ErrorAction SilentlyContinue
if ($sshProcs) {
$sshProcs | ForEach-Object {
Write-Host " Killing SSH PID: $($_.Id)" -ForegroundColor Red
Stop-Process -Id $_.Id -Force
}
} else {
Write-Host " No SSH processes found" -ForegroundColor Green
}
}

View File

@@ -0,0 +1,78 @@
# Test the updated sync script
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)
Write-Host "=== Testing Updated Sync Script ===" -ForegroundColor Cyan
Write-Host ""
Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
Write-Host "[1] Running sync script manually..." -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
Write-Host ""
# Clear recent errors from log
$logFile = "C:\Shares\test\scripts\sync-from-nas.log"
Write-Host "Note: Watching $logFile for new errors..." -ForegroundColor Gray
Write-Host ""
# Get current log size
$logSize = (Get-Item $logFile).Length
# Run sync (in background to avoid blocking)
$job = Start-Job -ScriptBlock {
& powershell.exe -ExecutionPolicy Bypass -File "C:\Shares\test\scripts\Sync-FromNAS.ps1"
}
# Wait a bit for it to start
Start-Sleep -Seconds 10
# Check for new log entries
$newContent = Get-Content $logFile -Raw
$newLines = $newContent.Substring([Math]::Min($logSize, $newContent.Length))
Write-Host "[2] Recent log output:" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$newLines -split "`n" | Select-Object -Last 50 | ForEach-Object {
if ($_ -match "ERROR|error") {
Write-Host $_ -ForegroundColor Red
} elseif ($_ -match "WARNING|warning") {
Write-Host $_ -ForegroundColor Yellow
} elseif ($_ -match "SCP|scp") {
Write-Host $_ -ForegroundColor Cyan
} else {
Write-Host $_ -ForegroundColor Gray
}
}
# Stop the job
Stop-Job -Job $job -ErrorAction SilentlyContinue
Remove-Job -Job $job -ErrorAction SilentlyContinue
Write-Host ""
Write-Host "[3] Checking if detailed SCP errors are logged" -ForegroundColor Yellow
Write-Host "=" * 80 -ForegroundColor Gray
$scpErrors = Get-Content $logFile -Tail 100 | Select-String -Pattern "SCP ERROR"
if ($scpErrors) {
Write-Host "[SUCCESS] Found detailed SCP error logging!" -ForegroundColor Green
Write-Host ""
Write-Host "Sample SCP errors:" -ForegroundColor Cyan
$scpErrors | Select-Object -First 5 | ForEach-Object {
Write-Host " $_" -ForegroundColor Red
}
} else {
Write-Host "[INFO] No 'SCP ERROR' entries found yet" -ForegroundColor Yellow
Write-Host "This could mean:" -ForegroundColor Gray
Write-Host " - No errors occurred (good!)" -ForegroundColor Gray
Write-Host " - Errors happened but weren't logged yet" -ForegroundColor Gray
Write-Host " - Need to wait for next scheduled run" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "=== Test Complete ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Note: The script runs every 15 minutes via scheduled task." -ForegroundColor Yellow
Write-Host "Check the log again in a few minutes for full sync results." -ForegroundColor Yellow

View File

@@ -0,0 +1,52 @@
# Test WinRM Connection to AD2
Write-Host "[INFO] Testing WinRM connection to AD2..."
# Admin account test
Write-Host "`n[TEST 1] Admin Account (INTRANET\sysadmin)"
$adminPassword = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$adminCred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $adminPassword)
try {
$result = Invoke-Command -ComputerName 192.168.0.6 -Credential $adminCred -ScriptBlock {
@{
Computer = $env:COMPUTERNAME
Domain = $env:USERDOMAIN
User = $env:USERNAME
WinRM = (Get-Service WinRM).Status
}
} -ErrorAction Stop
Write-Host "[SUCCESS] Connected to AD2" -ForegroundColor Green
Write-Host " Computer: $($result.Computer)"
Write-Host " Domain: $($result.Domain)"
Write-Host " User: $($result.User)"
Write-Host " WinRM Status: $($result.WinRM)"
} catch {
Write-Host "[ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
# Service account test
Write-Host "`n[TEST 2] Service Account (INTRANET\ClaudeTools-ReadOnly)"
$svcPassword = ConvertTo-SecureString "vG!UCAD>=#gIk}1A3=:{+DV3" -AsPlainText -Force
$svcCred = New-Object System.Management.Automation.PSCredential("INTRANET\ClaudeTools-ReadOnly", $svcPassword)
try {
$result = Invoke-Command -ComputerName 192.168.0.6 -Credential $svcCred -ScriptBlock {
@{
Computer = $env:COMPUTERNAME
Domain = $env:USERDOMAIN
User = $env:USERNAME
UserCount = (Get-ADUser -Filter * | Measure-Object).Count
}
} -ErrorAction Stop
Write-Host "[SUCCESS] Connected to AD2" -ForegroundColor Green
Write-Host " Computer: $($result.Computer)"
Write-Host " Domain: $($result.Domain)"
Write-Host " User: $($result.User)"
Write-Host " AD Users Found: $($result.UserCount)"
} catch {
Write-Host "[ERROR] $($_.Exception.Message)" -ForegroundColor Red
}
Write-Host "`n[INFO] Testing complete."

Some files were not shown because too many files have changed in this diff Show More