Search This Blog

Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

Monday, December 04, 2023

List Members of AD groups

To get the members of a group, we need to login into a server with an admin account.

The admin account is member of another domain in the same forest, but the groups are in a different domain. In order to perform the inquiry, an AD controller server for the target domain must be specified.

Simple select: Get-ADGroup -Filter { Name -like "*the_searched_group*" } -Server DC.TARGET.TLD | Get-ADGroupMember -Server DC.TARGET.TLD | Select-Object name, objectClass | Out-GridView

#to be run as normal user, so excel lauches without interference, it will ask for admin cred when needed

$wrkfldr='C:\temp'
$server='DC.TARGET.TLD'
$grps="app*-VNC*"
$cred = Get-Credential;
$ErrorActionPreference= 'silentlycontinue'

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$wb = $excel.Workbooks.Add()

$groups = Get-ADGroup -Credential $cred -filter { name -like $grps } -server $server | Select Name -ExpandProperty Name

foreach ($group in $groups){ Get-ADGroupMember -Credential $cred -identity $group -server $server | Where-Object {$_.objectClass -eq "user"} | Select-Object Name | Export-Csv "$wrkfldr\$group.csv" -NoTypeInformation }

Get-ChildItem $wrkfldr\*.csv | ForEach-Object {
if ((Import-Csv $_.FullName).Length -gt 0) {
    $csvBook = $excel.Workbooks.Open($_.FullName)
    $csvBook.ActiveSheet.Copy($wb.Worksheets($wb.Worksheets.Count))
    $csvBook.Close()
    }
}

Tuesday, January 03, 2017

TS - FR keyboard by default

Keyboard
Data collected on: 4/21/2015 1:44:16 PM
General
Details
Domain
domain.local
Owner
DOMAIN\Admins du domaine
Created
4/21/2015 1:32:00 PM
Modified
4/21/2015 1:42:44 PM
User Revisions
18 (AD), 18 (sysvol)
Computer Revisions
1 (AD), 1 (sysvol)
Unique ID
{0E240A4C-8A26-4761-8907-DB164F024AFC}
GPO Status
Enabled
Links
Location
Enforced
Link Status
Path
TS
No
Enabled
domain.local/Member Servers/TS

This list only includes links in the domain of the GPO.
Security Filtering
The settings in this GPO can only apply to the following groups, users, and computers:
Name
NT AUTHORITY\Authenticated Users
Delegation
These groups and users have the specified permission for this GPO
Name
Allowed Permissions
Inherited
NT AUTHORITY\Authenticated Users
Read (from Security Filtering)
No
NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS
Read
No
NT AUTHORITY\SYSTEM
Edit settings, delete, modify security
No





No
Computer Configuration (Enabled)
Policies
Administrative Templates
Policy definitions (ADMX files) retrieved from the local machine.
System/Group Policy
Policy
Setting
Comment
User Group Policy loopback processing mode
Enabled
Mode:
Merge
User Configuration (Enabled)
Preferences
Windows Settings
Registry
2 (Order: 1)
General
Action
Update
Properties
Hive
HKEY_CURRENT_USER
Key path
Keyboard Layout\Preload
Value name
2
Value type
REG_SZ
Value data
00000409
Common
Options
Stop processing items on this extension if an error occurs on this item
No
Run in logged-on user's security context (user policy option)
No
Remove this item when it is no longer applied
No
Apply once and do not reapply
No
1 (Order: 2)
General
Action
Update
Properties
Hive
HKEY_CURRENT_USER
Key path
Keyboard Layout\Preload
Value name
1
Value type
REG_SZ
Value data
00000c0c
Common
Options
Stop processing items on this extension if an error occurs on this item
No
Run in logged-on user's security context (user policy option)
No
Remove this item when it is no longer applied
No
Apply once and do not reapply
No
ShowStatus (Order: 3)
General
Action
Update
Properties
Hive
HKEY_CURRENT_USER
Key path
Software\Microsoft\CTF\LangBar
Value name
ShowStatus
Value type
REG_DWORD
Value data
0x4 (4)
Common
Options
Stop processing items on this extension if an error occurs on this item
No
Run in logged-on user's security context (user policy option)
No
Remove this item when it is no longer applied
No
Apply once and do not reapply
No
Label (Order: 4)
General
Action
Update
Properties
Hive
HKEY_CURRENT_USER
Key path
Software\Microsoft\CTF\LangBar
Value name
Label
Value type
REG_DWORD
Value data
0x0 (0)
Common
Options
Stop processing items on this extension if an error occurs on this item
No
Run in logged-on user's security context (user policy option)
No
Remove this item when it is no longer applied
No
Apply once and do not reapply
No
AutoAdjustDeskBand (Order: 5)
General
Action
Update
Properties
Hive
HKEY_CURRENT_USER
Key path
Software\Microsoft\CTF\MSUTB
Value name
AutoAdjustDeskBand
Value type
REG_DWORD
Value data
0x0 (0)
Common
Options
Stop processing items on this extension if an error occurs on this item
No
Run in logged-on user's security context (user policy option)
No
Remove this item when it is no longer applied
No
Apply once and do not reapply
No

Monday, July 04, 2016

Your system administrator does not allow the use of saved credentials to log on to the remote computer RDP terminal server because its identity is not fully verified.

In order to use saved RDP or Terminal Server credentials you need to do the following:

1. On the local machine, Open Group Policy Editor via Run -> gpedit.msc
2. Navigate to Local Computer Policy>Computer Configuration>Administrative Templates>System>Credentials Delegation

3.Open Setting Allow Delegating Saved Credentials with NTLM-only Server Authentication, set it to Enabled click on button Show... and in Show Contents window add Value TERMSRV/*. Close the windows by pressing OK.

*Repeat step 3 on the following settings:
Allow Delegating Default Credentials
Allow Delegating Saved Credentials
Allow Delegating Default Credentials with NTLM-only Server Authentication

4. Open comman prompt and enter gpupdate /force command to update your policy.


Monday, May 02, 2016

Autodiscover and/or EWS unavailable on Exchange 2007/2010

Symptom: Outlook crashes or you cannot access OutOfOffice settings after you install a package that contains the .NET Framework 3.5 with SP1 and the .NET Framework 2.0 with SP2 on an Exchange 2007 or on an Exchange 2010 server (CAS role)

Problem described in:
kb958934
kb952883
kb976814


My solution:

Turn of any mmc, powershel console, emc etc.

Uninstall .net 3.5 sp1
Uninstall .net 3.0 sp2
Uninstall .net 2.0 sp2

In this order, without restarting!
if it complains that "you can't uninstall, some other package depends on it", do this:

net stop MSExchangeTransportLogSearch /yes
net stop MSExchangeTransport /yes
net stop MSExchangeServiceHost /yes
net stop MSExchangeSearch /yes
net stop MSExchangeRepl /yes
net stop MSExchangePop3 /yes
net stop MSExchangeMailSubmission /yes
net stop MSExchangeMailboxAssistants /yes
net stop MSExchangeIMAP4 /yes
net stop MSExchangeFDS /yes
net stop MSExchangeSA /yes
net stop MSExchangeEdgeSync /yes
net stop MSExchangeAntispamUpdate /yes
net stop MSExchangeADTopology /yes
net stop MSExchangeIS /yes
ping -n 5 -w 1000 1.0.0.0 >nul
net stop w3svc /yes

If you still can't uninstall, use procexp's "find" feature and close any .NET handle still open.

At the end there should be no reference to .NET in the installed programs.
DO NOT RESTART!

Install .net 3.0 (I used version 3.0.4506.30 downloaded in 2008 an forgotten on server...)
DO NOT RESTART!

[PS] Remove-AutodiscoverVirtualDirectory -Identity "EXCHANGE2007\Autodiscover (Default Web Site)"
[PS] New-AutodiscoverVirtualDirectory
[PS] Set-ClientAccessServer -Identity "EXCHANGE2007" -AutoDiscoverServiceInternalUri https://exchange2007.domain.tld/autodiscover/autodiscover.xml
[PS] Test-OutlookWebServices | fl

If you receive Error 401 when attempting to run Test-OutlookWebServices | FL, disable the loopback check in  HKLM\SYSTEM\CurrentControlSet\Control\Lsa  "DisableLoopbackCheck" DWORD, 1

- In IIS Manager make sure ASP.NET 2.0.50727 is ENABLED
- In IIS Manager make sure Autodiscovery and EWS uses only "Integrated windows authentication" and that the security cert is "require ssl", "128 bit" and "ignore client certificates"

- Verify that the folder %ExchangeInstallaDir%\ClientAccess\Autodiscover is readable by "authenticated users"
 - perform iisreset /noforce

[PS] Test-OutlookWebServices | FL should give you a good answer now, if not, make sure the autodiscover DNS entry exists:

- in DNS Manager rightclick the local forward lookup zone, "Other new records", "SRV", service "_autodiscover", pri "10", weight "5", port "443", host "autodiscover.domain.tld"
- in DNS Manager, new A-Record "autodiscover.domain.tld"


[PS] Test-OutlookWebServices | FL should give you a good answer now, if not, get the backup tape, it's that time...

Saturday, January 02, 2016

"FullyQualifiedErrorId : -2144108477,PSSessionOpenFailed"

The PowerShell window displayed this error.
VERBOSE: Connecting to E15MB2.exchange2013demo.com.
New-PSSession : [e15mb2.exchange2013demo.com] Processing data from remote server e15mb2.exchange2013demo.com failed
with the following error message: The WinRM Shell client cannot process the request. The shell handle passed to the WSMan Shell function is not valid. The shell handle is valid only when WSManCreateShell function completes successfully. Change the request including a valid shell handle and try again. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ New-PSSession -ConnectionURI “$connectionUri” -ConfigurationName Microsoft.Excha …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme….RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : -2144108212,PSSessionOpenFailed
The cause of this error in my specific case was that the SSL certificate was no longer bound to the Exchange Back End website on that Exchange 2013 server.
To fix this, in IIS Manager right-click the Exchange Back End website and click Bindings.

Highlight https and click Edit.
If you see “Not selected” like I did, click on Select.
Choose the certificate you want to bind to the site.
Apply the changes and retry the Exchange management shell. If it connects successfully to the server then you have most likely resolved this issue.



Thursday, October 01, 2015

Authentify linux users to a windows 2012 R2 domain controller

As root type:
rpm –Uvh  samba-winbind samba-winbind-clients pam_krb5 krb5-libs

Then:
authconfig --enablekrb5 --krb5kdc=2k12srv.domain.local --krb5adminserver=2k12srv.domain.local --krb5realm=DOMAIN.LOCAL --enablewinbind --enablewinbindauth --smbsecurity=ads --smbrealm=DOMAIN.LOCAL --smbservers=2k12srv.domain.local --smbworkgroup=DOMAIN --winbindtemplatehomedir=/home/%U --winbindtemplateshell=/bin/bash --enablemkhomedir --enablewinbindusedefaultdomain –update && net ads join -U administrator -D DOMAIN

vi smb.conf
[global]
   workgroup = DOMAIN
   password server = 2k12srv.domain.local
   realm = DOMAIN.LOCAL
   security = ads
   idmap config * : range = 16777216-33554431
   template homedir = /home/%U
   template shell = /bin/bash
   winbind use default domain = true
   winbind offline logon = true

Restart and enable winbind:
chkconfig winbind on
service winbind restart

-----------------------------------------------------------------------------------------------------------------------------






The old way, for a 2008 Server was:
rpm -Uvh samba-winbind-clients samba-winbind samba-client

service winbind start
chkconfig winbind on

authconfig --enablewinbind --enablewinbindauth --enablelocauthorize --enablemkhomedir --updateall

vi smb.conf:
# Any modification may be deleted or altered by authconfig in future
   workgroup = DOMAIN
   password server = 2008dc 2008R2dc
   realm = DOMAIN.LOCAL
   security = ads
   idmap config * : range = 16777216-33554431
   template homedir = /home/%D/%U
   template shell = /bin/bash
   winbind use default domain = true
   winbind offline logon = true
#--authconfig--end-line--


vi /etc/openldap/ldap.conf:
TLS_CACERTDIR   /etc/openldap/cacerts
SASL_NOCANON    on

cp shared_DOMAIN_cert.cer /etc/openldap/cacerts/
cacertdir_rehash /etc/openldap/cacerts/

net join -w DOMAIN -S 2008dc.domain.tld -U Administrator
systemctl restart winbind.service

In order to allow certain AD Groups to login:
vi /etc/login.group.allowed
A_CERTAIN_AD_GROUP

vi /etc/pam.d/sshd
auth       required     pam_listfile.so item=group sense=allow onerr=fail file=/etc/login.group.allowed

vi /etc/pam.d/login
auth       required     pam_listfile.so item=group sense=allow onerr=fail file=/etc/login.group.allowed

cd /home
mkdir DOMAIN

Sunday, August 10, 2014

Tune UP (in fact down) Windows 2008 R2

sssc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

netsh int tcp set global rss=disabled
netsh int tcp set global chimney=disabled
netsh int tcp set global autotuninglevel=disabled
netsh int ip set global taskoffload=disablednetsh int tcp set global autotuninglevel=disablednetsh int tcp set global ecncapability=disablednetsh int tcp set global timestamps=disablednetsh advf set allp state off


:: reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v DisableTaskOffload /t REG_DWORD /d "1" /f

reg add "HKLM\SYSTEM\CurrentControlSet\services\LanmanWorkstation\Parameters" /v DisableBandwidthThrottling /t REG_DWORD /d "1" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v EnableTCPA /t REG_DWORD /d "0" /f

Thursday, June 05, 2014

Allow login only if the member of a certain OU comes from a certain IP subnet

@echo off
:: (c)2014 sorinakis@g*il.com
setlocal enableextensions enabledelayedexpansion
set config=c:\pair.txt

:: find the primary OU that user belongs to
for /F "tokens=3 delims=/,CN=" %%n in ('"gpresult /R | findstr CN | findstr /I %username%"') do (
 set myou=%%n
)
:: echo myou is: !myou!

:: find the client subnet (need gettscip.exe from www.ctrl-alt-del.com.au in the path somewhere)
for /F "tokens=2 delims=/: " %%f in ('gettscip.exe') do (
 for /F "tokens=1-3 delims=/." %%g in ('echo %%f') do set mynet=%%g.%%h.%%i
)
:: echo mynet is: !mynet!

:: read the config file containing the pair IP_subnet/Organisational_Unit (or group)
:: the pair have to be separated by a space, ex: '192.168.1 Users' comments start with ;
for /F "eol=; tokens=1,2 delims=/ " %%l in ('type !config!') do (
 set net=%%l
:: set group=%%m
 set ou=%%m

:: find if the user belongs to a group
rem for /f %%f in ('"net user /domain %username% | findstr /i %group%"') do set /a ingroup=yes

:: if the two pairs are identical, the user can login from that subnet
 if "!net!"=="!mynet!" (
::  if "!ingroup!"=="yes" (
 if /I "!ou!"=="!myou!" (
   set canrun=yes
  )
 )
)
::echo canrun: !canrun!

:: if the user can't login let him know, then end the session
if NOT "!canrun!"=="yes" (
 echo Sorry %username%, "!myou!" are NOT ALLOWED to login from !mynet!.0/24
 msg %username% Sorry, %username% is NOT ALLOWED to login from this location.
 shutdown /l
)

:: Cleanup variables at end
endlocal

Tuesday, May 06, 2014

Delete old printers ond add new ones - second version

This version keeps track of the default printer :)

' s@to**.guru - Jan 08 2015 Replace the default Printer

'********************************************************************************************************************
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
'Set wmiLocator = CreateObject("WbemScripting.SWbemLocator")
'Set wmiNameSpace = wmiLocator.ConnectServer(objNetwork.ComputerName, "root\default")
'Set objRegistry = wmiNameSpace.Get("StdRegProv")
'strComputer = "."
'Const HKEY_CLASSES_ROOT  = &H80000000
'Const HKEY_CURRENT_USER  = &H80000001
'Const HKEY_LOCAL_MACHINE = &H80000002
'Const HKEY_USERS         = &H80000003
userprrf = objShell.Environment("PROCESS")("UserProfile")
lockfile = "\prinstalled"
oldlockfile = "\printersinstalled"
strnewSrv = "\\2K12SRV\"
strOldSrv = "\\critesdc\"
arrPrinters = Array("HP Color LaserJet 4700 PCL 5c","HP Color LaserJet 4700 PCL 5c Sales","HP LaserJet 4100 Series PCL6 Sales","HP LaserJet 4250 PCL6","HP Laserjet 5100tn","Xerox WorkCentre 5655 PS","Xerox7545 PS")

'********************************************************************************************************************
' If this script was already run at least once for this user, EXIT and don't look back
If (objFSO.FileExists(userprrf & lockfile)) Then
  Wscript.Quit
End If
' Delete old lockfile
objFSO.DeleteFile(userprrf & oldlockfile)
'' If we're on the TS server create lockfile and Exit!
'If objNetwork.ComputerName = "2K12TS1" Then
'  Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
'  Set objFile = objFSO.GetFile(userprrf & lockfile)
'  objFile.Attributes = 2
'  Wscript.Quit
'End if

'********************************************************************************************************************
' Make spooler autostart without waiting
' use Microsoft's way of getting StdRegProv, set_binary is special!
'Set oRegistry = _
'   GetObject("Winmgmts:root\default:StdRegProv")
'strPath = "SYSTEM\CurrentControlSet\Services\Spooler"
'uBinary = Array(80,51,01,00,00,00,00,00,00,00,00,00,03,00,00,00,20,00,64,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00)
'Return = oRegistry.SetBinaryValue(HKEY_LOCAL_MACHINE, _
'   strPath, _
'   "FailureActions", _
'   uBinary)
'oShell.RegWrite "HKLM\SYSTEM\CurrentControlSet\Services\Spooler\Start", 2, "REG_DWORD"

'********************************************************************************************************************
' get the default printer
strdefValue = "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device"
strdefPrinter = objShell.RegRead(strdefValue)
strdefPrinter = Split(strdefPrinter, ",")(0)
'wscript.Echo "Actual default printer: " & strdefPrinter
' put the default printer into the lockfile if we want to keep it for historical records
'Set objFile = objFSO.CreateTextFile(userprrf & lockfile)
'objFile.Write strdefPrinter & vbCrLf
'objFile.Close

'********************************************************************************************************************
'Delete old printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strOldSrv & strPrn)
'wscript.echo "removing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /dn /n """ & strPrinter & """ /q"
      objShell.Run strCmd,,true
'    objNetwork.RemoveWindowsPrinterConnection strOldSrv & strPrn
Next

'********************************************************************************************************************
' to make sure all printers are removed, Deletes RegistryKey with all subkeys in Network printers
'sPath = "Printers\Connections"
'lRC = DeleteRegEntry(HKEY_CURRENT_USER, sPath)
'Function DeleteRegEntry(sHive, sEnumPath)
' Attempt to delete key.  If it fails, start the subkey enumration process.
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
' The deletion failed, start deleting subkeys.
'If (lRC <> 0) Then
' Subkey Enumerator  
'On Error Resume Next  
'lRC = objRegistry.EnumKey(HKEY_CURRENT_USER, sEnumPath, sNames)  
'For Each sKeyName In sNames    
'If Err.Number <> 0 Then Exit For    
'lRC = DeleteRegEntry(sHive, sEnumPath & "\" & sKeyName)  
'Next  
'On Error Goto 0
' At this point we should have looped through all subkeys, trying to delete the key again.  
'lRC = objRegistry.DeleteKey(sHive, sEnumPath)
'End If
'End Function
' Now let's recreate only the "root" Key we deleted before
'objRegistry.CreateKey HKEY_CURRENT_USER,sPath

'********************************************************************************************************************
' we have zero network printers, let`s remove all unused drivers by using Microsoft`s own prndrvr.vbs
' first restart print spooler in order to release open files
'Set objWMIService = GetObject("winmgmts:" _
'    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'Set colServiceList = objWMIService.ExecQuery _
'        ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StopService()
'Next
'wscript.sleep 1000
'Set colServiceList = objWMIService.ExecQuery _
'    ("Select * from Win32_Service where Name='Spooler'")
'For each objService in colServiceList
'     errReturn = objService.StartService()
'Next
'oShell.Run "cscript %systemroot%\system32\prndrvr.vbs -x"

'********************************************************************************************************************
'Add new printers using either printui.dll or AddWindowsPrinterConnection
wscript.sleep 100
For Each strPrn in arrPrinters
strPrinter = (strNewSrv & strPrn)
'wscript.echo "installing "  & strPrinter
strCmd = "rundll32 printui.dll,PrintUIEntry /in /n """ & strPrinter & """ /u /q /Gw"
      objShell.Run strCmd,,true
'    objNetwork.AddWindowsPrinterConnection strNewSrv & strPrn
Next

'********************************************************************************************************************
' Try to put back the default printer
'Set objFile = objFSO.OpenTextFile(userprrf & lockfile)
'Do Until objFile.AtEndOfStream
'    strNewDefPrinter = objFile.ReadLine
'Loop
'objFile.Close

strNewDefault = (Replace(strdefPrinter,strOldSrv, strNewSrv))
'wscript.Echo "New default printer: " & strNewDefault
strCmd = "rundll32 printui.dll,PrintUIEntry /y /n """ & strrNewDefault & """ /u /q /Gw"
      objShell.Run strCmd,,true
'objNetwork.SetDefaultPrinter strNewDefault


'********************************************************************************************************************
' Tell the user to check his default printer
beep = chr(007)
objShell.Run "cmd /c @echo " & beep & beep, 0
'with createobject("wscript.shell")
'   .popup "Tous vos imprimantes réseau ont été installés. SVP vérifier et changer votre imprimante DÉFAULT si nécessaire.",30, "Printers Manager"
'end with
'objShell.Exec("control printers")

'********************************************************************************************************************
' We're done, let's leave a hidden file in userprofile, so at next login this script will exit
Set objFile = objFSO.CreateTextFile(userprrf & lockfile, true)
Set objFile = objFSO.GetFile(userprrf & lockfile)
objFile.Attributes = 2
Wscript.Quit

Thursday, May 01, 2014

Delete old printers and change the default

'Change default Printer and delete the old ones
'(c)2014 s@xxxxxxxx.com
' defaultlist example: service Client,\\2K12SRV\HP 4050 P005



PrintServer = "2K8SRV" 'Old Print server name goes here - case sensitive
listfile = "\defaultlist.txt"
lockfile = "\defaultprt"
Set objNetwork = CreateObject("WScript.Network")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSysInfo = CreateObject("ADSystemInfo")
Set objShell =  CreateObject("WScript.Shell")
userprrf = objShell.Environment("PROCESS")("UserProfile")
strComputer = "."
'strCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(strComputer)
strCurPath = "\\2k12srv\netlogon\deploy" ' relpath doesn't seems to work on UNC
 wscript.echo strCurPath
If (objFSO.FileExists(userprrf & lockfile)) Then
 'Debug
 'with createobject("wscript.shell")
 '.popup userprrf & "Lockfile EXIST!" , 1 , "Info"
 'end with
 Wscript.Quit
End If

'On Error Resume Next
strName = objSysInfo.UserName
' Split full username by comma (warning: comma is a valid char in OU, verify personally that it doesn't exist in your OU!)
arrUserName = Split(strName, ",")
' remove OU= or DC= for the last 2 OU's
arrOU = Split(arrUserName(1), "=")
arrOU2 = Split(arrUserName(2), "=")
'put those OU toghether
strOU = arrOU2(1) & " " & arrOU(1)
' open the list of OU vs printers pairs
Set objFile = objFSO.OpenTextFile(strCurPath + listfile, 1)
 Do Until objFile.AtEndOfStream
 ' they are separated by comma, first is OU second is printer
 defaultArray = split(objFile.ReadLine,",")
 readOU=defaultArray(0)
 defaultprt=defaultArray(1)
 ' Debug
 'with createobject("wscript.shell")
 '.popup "Check: """ & strOU & """ = """ & readOU & """ Choose """ & defaultprt & """. " , 1 , "Info"
 'end with
 If strOU = readOU Then
  ' Debug
  'with createobject("wscript.shell")
  '.popup "Found: """ & strOU & """ = """ & readOU & """ Printer: """ & defaultprt & """. " , 5 , "Info"
  'end with
  ' first ensure that the printer is installed, then set it default
  objNetwork.AddWindowsPrinterConnection defaultprt
  objNetwork.SetDefaultPrinter defaultprt
  exit do
 End If
Loop
objFile.Close

'Remove old printers
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colInstalledPrinters =  objWMIService.ExecQuery _
    ("Select * from Win32_Printer")

For Each objPrinter in colInstalledPrinters
    'Debug
    'with createobject("wscript.shell")
  '.popup "Name: " & objPrinter.Name , 1 , "Info"
  'end with
  'Wscript.Echo "Name: " & objPrinter.Name
    i = 0
    ReDim Preserve arrPrinterName(i)
    arrPrinterName(i) = objPrinter.Name
        If InStr(arrPrinterName(i), PrintServer) Then
            Set objNetwork = WScript.CreateObject("WScript.Network")
            'Debug
        'with createobject("wscript.shell")
      '.popup "Removing: " & arrPrinterName(i) , 5 , "Info"
      'end with       
            objNetwork.RemovePrinterConnection arrPrinterName(i)
            i=i+1
        Else
            'Debug
        'with createobject("wscript.shell")
      '.popup "Skipped: " & arrPrinterName(i) , 5 , "Info"
      'end with       
        End If

Next

' Leave a lockfile in user's home
Set objFile1 = objFSO.CreateTextFile(userprrf & lockfile)
Wscript.Quit