Archive for category Scripting

New-ADUser BULK from CSV file

 Create a CSV file with the following columns:
Name,GivenName,Surname,UserPrincipalName,SamAccountName,Path,Enabled,Password,ChangePasswordAtLogon
User Test,User,Test,Utest@domain.local,utest,”OU=Users,DC=domain,DC=local”,$True,Password1,$True ,DC=local”,$True,Password1,$True
 
 
Then run the following PowerShell command:
import-csv C:\Bulk.csv | % {New-ADUser -Name $_.name -GivenName $_.GivenName -Surname $_.Surname -UserPrincipalName $_.UserPrincipalName -SamAccountName $_.SamAccountName -Path $_.Path -Enabled $True -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -force) -ChangePasswordAtLogon $True}

Tags:

Change / Remap printers on client computers

On Error Resume Next
Set WSHNetwork = CreateObject(“WScript.Network”)

‘ create a dictionary to store our printer paths
Set objDictPrnts = CreateObject(“Scripting.Dictionary”)
objDictPrnts.CompareMode = vbTextCompare
objDictPrnts.Add “\\printrete\P1“, “\\printrete\P1
‘objDictPrnts.Add “\\printrete\P2“, “\\printrete\P2
objDictPrnts.Add “\\stampanti\P3“, “\\stampanti\P3

‘ loop through printer connections
Set WSHPrinters = WSHNetwork.EnumPrinterConnections
For LOOP_COUNTER = 0 To WSHPrinters.Count – 1 Step 2   
PrinterPath = WSHPrinters.Item(LOOP_COUNTER +1)   

‘ if the current path exist in our dictionary remove it   
If objDictPrnts.Exists(PrinterPath) Then
objDictPrnts.Remove PrinterPath
WSHNetwork.RemovePrinterConnection PrinterPath
End if
Next

‘ loop through the path’s that were not found and add them
For Each PrinterPath In objDictPrnts.Keys
WSHNetwork.AddWindowsPrinterConnection PrinterPath
Next

Tags:

Protected: Local User Accounts – Enumerate and Disable

This content is password protected. To view it please enter your password below:

VBS – Point Client Computers to a New Print Server

Logon script that changes the printer connections on workstations.

  

‘This script works well in a login script. When ran from a workstation
‘it will loop through all the printers installed for the current logged on
‘user and if they are connected to the old server they will be removed
‘and then remapped to the new server. It will also attempt to discover
‘which printer is the default printer in order to reset this if it is one
‘of the printers that will be moved.

‘Note: All of the printers must exist on the new server before this script
‘ should be run. If not then the printer will simply be removed from
‘ users profile and the script will not be able to reconnect them.
‘ “Print Migrator” is a utility that is part of the Windows 2000 and
‘ Windows 2003 resource kit. This will create all of the printers
‘ on the new server while maintaining all of their settings including
‘ print queue security. Keep in mind that for a time you will see
‘ duplicate printer if you do a search on printers, one advertisec
‘ from each server.

‘We used this method to move just over 100 printers from one server to another
‘and then ran this script as a logon script in a group policy. We let it run for
‘a few days in order to allow for some users who don’t logout every day have a
‘chance to run it. All of our users profiles were updated and they didn’t even
‘know it was happening. We then deleted all of the printers from the old server.

‘Note: The script does not run if you are in Terminal Service or SMS remote control.

Option Explicit
Dim from_sv, to_sv, PrinterPath, PrinterName, DefaultPrinterName, DefaultPrinter
Dim DefaultPrinterServer, SetDefault, key
Dim spoint, Loop_Counter, scomma
Dim WshNet, WshShell
Dim WS_Printers
DefaultPrinterName = “”
spoint = 0
scomma = 0
SetDefault = 0
set WshShell = CreateObject(“WScript.shell”)

from_sv = “\\old” ‘This should be the name of the old server.
to_sv = “\\new” ‘This should be the name of your new server.

‘Just incase their are no printers and therefor no defauld printer set
‘ this will prevent the script form erroring out.
On Error Resume Next
key = “HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\Device”
DefaultPrinter = LCase(WshShell.RegRead (key))

If Err.Number <> 0 Then
DefaultPrinterName = “”
else
‘If the registry read was successful then parse out the printer name so we can
‘ compare it with each printer later and reset the correct default printer
‘ if one of them matches this one read from the registry.
spoint = instr(3,DefaultPrinter,”\”)+1

DefaultPrinterServer = left(DefaultPrinter,spoint-2)

if lcase(DefaultPrinterServer) = from_sv then
DefaultPrinterName = mid(DefaultPrinter,spoint,len(DefaultPrinter)-spoint+1)
scomma = instr(DefaultPrinterName,”,”)
DefaultPrinterName = left(DefaultPrinterName,scomma -1)
end if
end if

Set WshNet = CreateObject(“WScript.Network”)
Set WS_Printers = WshNet.EnumPrinterConnections

‘You have to step by 2 because only the even numbers will be the print queue’s
‘ server and share name. The odd numbers are the printer names.
For Loop_Counter = 0 To WS_Printers.Count – 1 Step 2
‘Remember the + 1 is to get the full path ie.. \\your_server\your_printer.
PrinterPath = lcase(WS_Printers(Loop_Counter + 1))

‘We only want to work with the network printers that are mapped to the original
‘ server, so we check for “\\Your_server”.
if lcase(LEFT(PrinterPath,len(from_sv))) = from_sv then
‘Now we need to parse the PrinterPath to get rhe Printer Name.
spoint = instr(3,PrinterPath,”\”)+1
PrinterName = mid(PrinterPath,spoint,len(PrinterPath)-spoint+1)
‘Now remove the old printer connection.
WshNet.RemovePrinterConnection from_sv+”\”+PrinterName
‘and then create the new connection.
‘Do not create c6100
if lcase(PrinterName) <> “c6100” then
WshNet.AddWindowsPrinterConnection to_sv+”\”+PrinterName
‘If this printer matches the default printer that we got from the registry then
‘ set it to be the default printer.
if DefaultPrinterName = PrinterName then
WshNet.SetDefaultPrinter to_sv+”\”+PrinterName
end if
end if
end if
Next
Set WS_Printers = Nothing
Set WshNet = Nothing
Set WshShell = Nothing

‘ wscript.echo “Printers Migrated”

Platforms

Windows Server 2008 R2 No
Windows Server 2008 No
Windows Server 2003 No
Windows 7 No
Windows Vista No
Windows XP No
Windows 2000 No

Tags: ,

VBS – Check Group Members and Map Drive and set TS Profile and User Profile

———————————————————————-

The script below does the following interesting things:

  • checks the members of a group
  • for each Maps a drive
  • for each member sets TS Profile TAB
  • for each member sets User Profile TAB
  • displays on screen or file the information

 

[download id=”6″]

Exchange 2007 – Move-Mailbox from file (bulk)

  1. Create a text file under C: named userlist.txt.
  2. From ADUC get the list of users you want to migrate.
  3. Select an OU, from View menu/add-column select EXCHANGE ALIAS and E-MAIL ADDRESS; sort the list by E-mail address so to be sure they have a mailbox.
  4. Click on button EXPORT LIST so you will have a TXT file.
  5. Copy the column ALIAS into userlist.txt file perviously created. They must be in a list each one on its own line separated by RETURN

Now create a file named Move-mailbox.ps1 and copy the following code into it:

$TargetDatabase = “Basic1DB”
$SourceFile = “c:\userlist.txt”
$a = remove-item c:\Movelog.txt -ea SilentlyContinue
$error.Clear()
$UserList = Get-Content $SourceFile
foreach($user in $UserList)
{
$message = “Moving User -> ” + $user
write-output $message | out-file -filePath “c:\MoveLog.txt” -append -noClobber
move-mailbox -Identity $user -TargetDatabase $TargetDatabase -BadItemLimit 5 -PreserveMailboxSizeLimit:$true -Confirm: $false
if($error.Count -ne 0)
{
$message = “User ” + $user + ” failed to move ???????????”
write-output $message | out-file -filePath “c:\MoveLog.txt” -append -noClobber
$message = “Error:::: ” + $error[0].ToString()
write-output $message | out-file -filePath “c:\MoveLog.txt” -append -noClobber
$error.Clear()
}
}

————————————————————————————-

$TARGETDATABASE –> this is the database where you want to move the mailbox (destination database)

$SOURCEFILE –> The file with the list of ALIASES

C:\Movelog.txt –> Log file

————————————————————————————-

Copy this file under c:\program Files\Microsoft\Exchange Server\Scripts.

Open Exchange Shell and launch the file. This will move the users mailbox listed in userlist.txt file, and you’ll get a log file under C:\Movelog.txt

Tags:

Using XCACLS

Downloaded Xcacls.vbs
Copied under shared folder “C:\xcacls” on Domain Controller
Then creted a script with following lines:
copy \\domain controller\XCACLS\xcacls.vbs c:\
cscript c:\XCACLS.vbs “C:\Documents and Settings\%COMPUTERNAME%\Desktop” /G intraosa\user:RWED;RW /T /E
Added the script to a GPO under “Startup Script”
This gives the user Read, Write, Excecute and Delete access to the Computer profile’s Desktop (had user with same name as computer) files, and only Read and Write to the Desktop folder

ShadowGroup.vbs

‘Error handling
 On Error Resume Next
‘——-‘
‘ USAGE ‘
‘——-‘
‘ShadowGroup.vbs “strTargetOU” “strShadowGrp”
‘Eg.: ShadowGroup.vbs “OU=Test,DC=Contoso,DC=Local” “cn=Shadow,OU=Test,DC=Contoso,DC=Local”
‘Constants
  Const ADS_PROPERTY_APPEND = 3
  Const ADS_PROPERTY_DELETE = 4
‘Declare variables
  Dim strTargetOU
  Dim strShadowGrp
‘Get input from Arguments
  If Wscript.Arguments.Count = 2 Then
    Dim objArgs : Set objArgs = WScript.Arguments
    strTargetOU  = objArgs(0)
    strShadowGrp = objArgs(1)
  Else
    MsgBox “Wrong number of arguments!”
    WScript.Quit
  End If
‘Create dictionary for users in OU
  Set dictOUUsers = CreateObject(“Scripting.Dictionary”)
  dictOUUsers.CompareMode = TextMode
‘Create dictionary for users in Group
  Set dictGrpUsers = CreateObject(“Scripting.Dictionary”)
  dictGrpUsers.CompareMode = TextMode
‘Get OU
  Dim oTargetOU
  Set oTargetOU = GetObject(“LDAP://” & strTargetOU)
  oTargetOU.Filter = Array(“user”)
‘Get Users from OU (not Sub OU’s)
  Dim usr
  For Each usr in oTargetOU
    ‘Add hte user to a dictionary object
    dictOUUsers.Add usr.distinguishedName, usr.distinguishedName
  Next
  Set oTargetOU = Nothing
‘Get Users from Group
  Dim mbr
  Set objGroup = GetObject(“LDAP://” & strShadowGrp)
    objGroup.GetInfo
    arrMemberOf = objGroup.GetEx(“member”)
    For Each mbr in arrMemberOf
      ‘Add the user to a dictionary object
      dictGrpUsers.Add mbr, mbr
     Next
   Set objGroup = Nothing
‘Add user to Group
  Dim OUUser
  For Each OUUser in dictOUUsers.Items
    If Not dictGrpUsers.Exists(OUUser) Then
      ‘Place user into Group
      Set objGroup = GetObject(“LDAP://” & strShadowGrp)
        objGroup.PutEx ADS_PROPERTY_APPEND,”member”,Array(OUUser)
        objGroup.SetInfo
      Set objGroup = Nothing
    End If
  Next
 
‘Remove user from Group
  Dim GrpUser
  For Each GrpUser in dictGrpUsers.Items
    If Not dictOUUsers.Exists(GrpUser) Then
      ‘Remove
      Set objGroup = GetObject(“LDAP://” & strShadowGrp)
        objGroup.PutEx ADS_PROPERTY_DELETE,”member”,Array(GrpUser)
        objGroup.SetInfo
      Set objGroup = Nothing
    End If
  Next
‘Close dictionary objects
  Set dictOUUsers = Nothing
  Set dictGrpUsers = Nothing

Tags:

REMOVE Ms-Exch-Send-Headers-Routing.ps1

Get-SendConnector “External –> *” | Remove-ADPermission -User “NT AUTHORITY\ANONYMOUS LOGON” -ExtendedRi
ghts “Ms-Exch-Send-Headers-Routing”

Tags:

GetComputer info

on error resume next
strComputer = “.”
Set objWMI = GetObject(“winmgmts:\\” & strComputer & “\root\directory\LDAP”)
Set objComps = objWMI.ExecQuery(“SELECT * FROM ds_computer ” & _
                            “where ds_OperatingSystem = ‘Windows Server 2003’ “)
If objComps.Count = 0 Then
   WScript.Echo “No matching objects found”
Else
   For Each objComp In objComps
      WScript.Echo objComp.ds_name
      Set objRemoteWMI = GetObject(“winmgmts:\\” & objComp.ds_name & “\root\cimv2″)
      If Err <> 0 Then
         WScript.Echo ”  Could not connect”
         Err.Clear
      Else
         ‘ Perform whatever functions necessary on objRemoteWMI
         Set objOSes = objRemoteWMI.InstancesOf(“Win32_OperatingSystem”)
         For Each objOS In objOSes
            strTime = objOS.LastBootUpTime
            strYear = Left(strTime, 4)
            strMon = Mid(strTime, 5, 2)
            strDay = Mid(strTime, 7, 2)
            WScript.Echo ”  Last Reboot: ” & strYear & “/” & strMon & “/” & strDay
         Next
      End If
      WScript.Echo “”
      Set objRemoteWMI = Nothing
   Next
End If
WScript.Echo “The script has completed successfully.”

Tags:

Get MAILBOX Statistics MB.ps1

Get-Mailboxstatistics -Identity faxassicurazioni | Format-Table DisplayName, @{expression={$_.TotalItemSi
ze.Value.ToMB()};width=8;label=”Mailbox size(MB)”}, itemcount

Add users from a specific file to AD Group

Create a file named userlist.txt with all “sAMAccountNames” listed (one per line)

Create a .cmd file and paste the following code:

:: GrpFromFile.CMD – Guy Teverovsky – January 2007
::
:: Add users from a file to specific group
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEEXTENSIONS
if “%1″==”” goto :SYNTAX
if “%1″==”/?” goto :SYNTAX
echo/
:: Define initial environment
set groupname=%1
set filename=%2
set scriptname=GrpFromFile
:: Determine if supplied arguments were sufficient
if “%groupname%”==”” (
 echo/
 echo ERROR – Insufficient arguments
 goto :SYNTAX
)
if “%filename%”==”” (
 echo/
 echo ERROR – Insufficient arguments
 goto :SYNTAX
)
if not exist “%filename%” (
 echo/
 echo ERROR – File not found
 goto :SYNTAX
)
:: Locate critical executables
for %%e in (dsquery.exe dsget.exe) do (
 set where=”%%~$PATH:e”
 if “!where!”==”””” (
  echo ERROR – Required executable, “%%e”, not located within the path
  goto :END
 )
)
FOR /F “TOKENS=*” %%G IN (‘dsquery group -name %groupname%’) DO SET groupdn=%%~G
if “x%groupdn%” == “x” (
 echo/
 echo ERROR – Group not found
 goto :END
)
 
for /f “delims=” %%i in (%filename%) do (
 :: Search for the user and add to group
 FOR /F “TOKENS=*” %%U IN (‘dsquery user -samid %%i’) DO dsmod group “%groupdn%” -addmbr “%%~U” -c
)
goto :END
:SYNTAX
echo/
echo SYNTAX – %scriptname% [Group] [File]
echo/
echo   * [Group] is the group to add accounts to
echo   * [File]  is the file containing the list of user accounts
echo/
echo     e.g. – %scriptname% grpAllUsers userlist.txt
echo/
da cmd lanciare: %scriptname% grpAllUsers userlist.txt

Get DC OS Version

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET REG_SETUP=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion
for /f “usebackq” %%s in (`dsquery server forestroot`) do (
 for /f “usebackq delims=” %%r in (`dsquery * %%s -attr serverreference ^| findstr /i DC=`) do (
  for /f “usebackq skip=1 delims=” %%d in (`dsquery * forestroot -filter “distinguishedname=%%r” -attr dNSHostName`) do (
   for /f “usebackq skip=1” %%a in (`dsquery * forestroot -filter “distinguishedname=%%r” -attr name`) do (
    set netbiosname=%%a
    set tempname=%%d
    set dnsname=!tempname:~2,-2!
    set sp=[]
    
    for /f “usebackq tokens=3,4,5” %%i in (`reg query “\\!dnsname!\%REG_SETUP%” /v CSDVersion 2^>NUL ^| findstr /i REG_SZ`) do set sp=[%%i %%j %%k]
    for /f “usebackq tokens=3,4,5,6,7” %%i in (`reg query “\\!dnsname!\%REG_SETUP%” /v ProductName 2^>NUL ^| findstr REG_SZ`) do set product=%%i %%j %%k %%l %%m
    
    echo !netbiosname!:   !product!   !sp!
   )
  )
 )
)

Check server Services startup Account

Create a file named “Server.txt” and paste all the server names that have to be checked separated by comma.

Create a file named “getsvc.vbs” and paste the following code:

Const ForAppending = 8
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objLogFile = objFSO.OpenTextFile(“c:\script\service_list.csv”, _
 ForAppending, True)
objLogFile.Write _
 (“System Name, ” _
 & “Caption,” _
 & “Display Name, ” _
 & “Start Mode,Account Name “)
objLogFile.Writeline
Const ForReading = 1
Set objDictionary = CreateObject(“Scripting.Dictionary”)
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objTextFile = objFSO.OpenTextFile(“c:\script\server.txt”, ForReading)
i = 0
Do Until objTextFile.AtEndOfStream
    strNextLine = objTextFile.Readline
Set objWMIService = GetObject(“winmgmts:” _
 & “{impersonationLevel=impersonate}!\\” & strNextLine & “\root\cimv2”)
Set colListOfServices = objWMIService.ExecQuery _
 (“SELECT * FROM Win32_Service”)
For Each objService in colListOfServices
 objLogFile.Write(objService.SystemName) & “,”
 objLogFile.Write(objService.Caption) & “,”
 objLogFile.Write(objService.DisplayName) & “,”
 objLogFile.Write(objService.StartMode) & “,”
 objLogFile.Write(objService.StartName) & “,”
 objLogFile.Writeline
Next
Loop
objLogFile.Close

Launch the script and you’ll get a .csv file with all information

CREATE USERS

for /L %a in (1 1 501) do net user User1%a ComplexPassword$ /domain /add

Protected: REMOVE MS-Exch-Send-Headers-Routing

This content is password protected. To view it please enter your password below:

Move Mailbox

$mailbox = $null
$database = $null
$existingMailboxes = @()
$nonexistingAliases = @()

if ($args.Length -lt 3)
{
write-host “Usage: MoveMailboxes.ps1 aliases.csv [-TargetDatabase [<>]]”
return
}

## Check if the given target database exists
$targetdatabase = $args[2] -replace ‘”‘,””
$database = get-mailboxdatabase $targetdatabase
if ($database -eq $null)
{
write-host “The target database doesn’t exist:” $targetdatabase
return
}

$data= import-csv -path $args[0]

## Check if there is a mailbox associated with the given alias
foreach( $i in $data )
{
$mailbox = get-mailbox | where {$_.alias -eq $i.alias}
if ($mailbox -eq $null) {
$nonexistingAliases += $i.alias
} else {
$existingMailboxes += $mailbox
}
}

write-host “No mailbox associated with below aliases: ”
$nonexistingAliases

write-host “Move below mailboxes to the target database:” $targetdatabase
$existingMailboxes
$existingMailboxes | Move-Mailbox -TargetDatabase $targetdatabase