# If there's an error in a call such as $cfg.settings.Lock(), it is important that the script stops. # Continuing while another application is also potentially modifying settings may corrupt them. $ErrorActionPreference = "Stop" $virtAcctInactivityDays = 60 # The PowerShell instance executing this script needs to run elevated, as administrator, to access SSH Server settings. $cfg = new-object -com "Bitvise.BssCfg" foreach ($instance in $cfg.instances.entries) { if (-not $instance.canManage) { Write-Host "SSH Server instance '$($instance.name)' cannot be managed using the available COM object" } else { Write-Host "Checking for inactive virtual accounts in SSH Server instance '$($instance.name)'" $cfg.SetInstance($instance.name) # Find inactive virtual accounts in the SSH Server's statistics files $statsDir = Join-Path $instance.installDir "Stats" $statsFiles = Get-ChildItem $statsDir -Filter "BssStats-*.xml" $inactiveAccts = @() foreach ($statsFile in $statsFiles) { $stats = Select-Xml -Path $statsFile.FullName -XPath "/stats" if (($stats.Node.type -eq "VirtAccount") -and $stats.Node.info.lastLogin) { $lastLogin = [DateTimeOffset]::Parse($stats.Node.info.lastLogin) $now = [DateTimeOffset]::Now $elapsed = $now.Subtract($lastLogin) if ($elapsed.TotalDays -ge $virtAcctInactivityDays) { $inactiveAccts += $stats.Node.account } } } # Settings must be locked while undergoing change to preserve their integrity. # If you lock settings and do not unlock them, no other process will be able to edit settings until the object is released. $cfg.settings.Lock() try { $cfg.settings.Load() # Find SSH Server settings entries for inactive accounts and disable them $anyDisabled = $false foreach ($acctName in $inactiveAccts) { $acct = $cfg.settings.access.virtAccounts.FirstWhere1("virtAccount eq ?", $acctName) if ($acct -and ($acct.loginAllowed -ne 2)) { Write-Host "Disabling virtual account $acctName" $acct.loginAllowed = 2 # $cfg.enums.DefaultGroupYesNo.no $nowStr = [DateTime]::Now.ToString() if ($acct.comment) { $acct.comment += "; " } $acct.comment += "Disabled for inactivity at $nowStr" $anyDisabled = $true } } # Save and unlock settings if ($anyDisabled) { $cfg.settings.Save() } } finally { $cfg.settings.Unlock() } } }