Some Powershell - For anyone who might need it.



  • All descriptions are in the Scripts I've written. Hope they help

    # This script will apply user permissions and a logon script on a 1:1 basis from an existing (Source) user to a new (Target) user. This script can also be used to reapply permissions on a large scale basis
    # using the 1:1 ratio, allowing control over what permissions may change between users. 
    
    # confirm:$false suppresses the confirmation for changes to an OU or DL. Otherwise this could be rather tedious.
    
    
    [CmdletBinding()] Param ( [Parameter(Mandatory = $True, HelpMessage = "Logon name of source user")] [string]$Source, [Parameter(Mandatory = $True, HelpMessage = "Logon name of target user")] [string]$Target )
    
    # Retrieve group memberships.
    $SourceUser = Get-ADUser $Source -Properties memberOf, scriptpath, manager, Organization, Department, Company
    $TargetUser = Get-ADUser $Target -Properties memberOf
    
    # Determines what Logon, Manager, Email, Department, Company.
    $Script = $SourceUser.scriptpath
    $Manager =$SourceUser.Manager
    $Company =$SourceUser.Company
    $Organization = $SourceUser.Organization
    $Department = $SourceUser.Department
    $Email = $Target + "@YOURDOMAIN.COM"
    
    # Hash table of source user groups.
    $List = @{}
    
    # Enumerate direct group memberships of source user.
    ForEach ($SourceDN In $SourceUser.memberOf)
    {
    	# Add this group to hash table.
    	$List.Add($SourceDN, $True)
    	# Bind to group object.
    	$SourceGroup = [ADSI]"LDAP://$SourceDN"
    
    	# Check if target user is already a member of this group.
    	If ($SourceGroup.IsMember("LDAP://" + $TargetUser.distinguishedName) -eq $False)
    	{
    		# Duplicates permissions from the Source user to the target user, and sets the following AD Fields: Login Script, Manager, Company, Organization, Department and Email address.
    		Add-ADGroupMember $SourceDN -Members $Target
    
    	 }
    }
    
    # The below lines ensure that the user account is not locked out, and is enabled. 
    	Enable-ADAccount -Identity $Target
    	Unlock-ADAccount -Identity $Target
    
    	Write-Output " "
    	Write-Output "Account is Unlocked and Enabled."
    
    # Sets the Basic AD information, manager, company, login script, Orangization, Department, and Email Address
    	Set-ADUser $Target -ScriptPath $Script
    	Set-ADUSer $Target -Manager $Manager
    	Set-ADUser $Target -Company $Company
    	Set-ADUser $Target -Organization $Organization
    	Set-ADUser $Target -Department $Department
    	Set-ADUser $Target -EmailAddress $Email
    
    
    # The below section will remove any group memberships that are not apart of the Source User that the Target user may be a part of. This trues up the permissions from the Source user to the Target User. 
    # Meaning only identical memberships will exist.
    
    # Extremely useful if there is a need to confirm or reapply group memberships across an OU or Domain, while still using a precise 1:1 operation. As blanket operations generally have unintended consequences.
    
    # Comment out everything below if this functionality is not required.
    
    # Enumerate direct group memberships of target user.
    ForEach ($TargetDN In $TargetUser.memberOf)
    {
    	# Check if source user is a member of this group.
    	If ($List.ContainsKey($TargetDN) -eq $False)
    	{
    		# Source user not a member of this group.
    		# Remove target user from this group.
    		Remove-ADGroupMember $TargetDN $Target -confirm:$false
    	}
    
    }


  • #List acconts not logged into within the past X (90) days
    Import-module activedirectory
    
    $domain = “YOUR-DOMAIN”
    
    $DaysInactive = 90
    
    $time = (Get-Date).Adddays(-($DaysInactive))
    
    # Get all AD User with lastLogonTimestamp less than our time and set to enable
    
    Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp |
    
    # Output Name and lastLogonTimestamp into CSV
    
    select-object Name,@{Name=”Stamp”; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString(‘yyyy-MM-dd_hh:mm:ss’)}} | export-csv C:\OLD_User.csv –notypeinformation


  • # This script will export all users of the specified domain, and their group memberships to a CSV file. The usefulness of this tool is expressed when
    # setting up new hire employees or reviewing domain membership permissions.
    
    # It's not advisable to store the user credentials required to run this script as they can be decrypted. This script is not designed to save these credentials but could be modified to do so.
    
    # Use of this script implies that you understand what it does, and will do to with regards to your Active Directory installation members and group memberships.
    # As designed there are no changes made to your installation, the script simply generates a report of members, and their group memberships. 
    # Any changes to this script are the responsibility of the person/organization which made said changes. 
    
    # We cannot be held responsible for your misuse or misunderstanding of this script as it was designed.
    #
    #
    #
    
    #
    # Imports Active Directory information 
    Import-Module Activedirectory
    $credentials = Get-Credential
    # Prompts for user credentials default user is “   ”, enter an administrator account in the form of “domain-name\administrator-account”
    Get-ADUser -Credential $credentials  -Filter * -Properties DisplayName,EmailAddress,memberof,DistinguishedName,Enabled |  %  {
      New-Object PSObject -Property  @{
    	UserName = $_.DisplayName 
    	EmailAddress = $_.EmailAddress
    	DistinguishedName = $_.DistinguishedName
    	Enabled = $_.Enabled
    # Deliminates the document for easy copy and paste using ";" as the delimiter. Incredibly useful for Copy & Paste of group memberships to new hire employees.
    	Groups = ($_.memberof | Get-ADGroup | Select -ExpandProperty Name) -join ";"
    	}
    # The export path is variable change to desired location on domain controller or end user computer. 
    } | Select UserName,EmailAddress,@{l='OU';e={$_.DistinguishedName.split(',')[1].split('=')[1]}},Groups,Enabled | Sort-Object Username | Export-Csv $ENV:UserProfile\Documents\User-Permissions.csv –NTI
    
    
    #Function Get-SaveFile($initialDirectory)
    #{ 
    #[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
    #Out-Null
    #
    #$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
    #$SaveFileDialog.initialDirectory = $initialDirectory
    #$SaveFileDialog.filter = "All files (*.*)| *.*"
    #$SaveFileDialog.ShowDialog() | Out-Null
    #$SaveFileDialog.filename
    #} 
    #
    #
    # open dialog box to select the .nessuss file. 
    #$InputFile = Get-OpenFile
    #$OutputFile = Get-SaveFile
    #
    #
    #$Contents = [io.file]::ReadAllText($inputfile)
    #$Contents = [io.file]::ReadAllText('C:\tools\wd\nessus\data\data.xml')
    #$Global:OutFile = [System.IO.StreamWriter] "c:\tools\wd\nessus\outfile.csv"
    #
    ##$InputFile
    #$OutputFile
    #


  • # Termination Script, which will revoke user permissions and restart their computers.
    
    Import-Module ActiveDirectory 
    $userInput = $null 
    Do 
    { 
    	$prompt = Read-Host -Prompt "Leaving Employee" 
    	$user = Get-ADUser $prompt -Properties memberof
    	$userInput = "$($user.samaccountname)" 
    } While($user -eq $null)
    
    #Disabling and locking the users' account
    $user | Set-ADUser -Enabled $False
    
    #Removing the users' group memberships. (Revoking all permissions)
    $user.Memberof | ForEach{Remove-ADGroupMember -identity $_ -members $user.samaccountname -confirm:$false}
    
    #Creating an arraylist that will collect all of the computer names 
    $arraylist = New-Object System.Collections.Arraylist 
    
    
    #Retrieving all the computers beginning with the $computer value
    $computerlist = Get-ADComputer -filter "name -like `"$userinput*`"" 
    
    #We add all the computer names to the previously created list
    $objects = $computerlist | Select-Object -expandproperty Name 
    if ($objects.count -eq 0) 
    { 
    Write-Warning "No computer with this username has been found! Stopping the script" 
    Start-Sleep -seconds 5 
    throw("I can't find this computer :-(") 
    } 
    else 
    { 
    if ($objects.count -eq 1) 
    { 
    $arraylist.add($objects) 
    } 
    else 
    { 
    $arraylist.addrange($objects) 
    } 
    Write-Host "$($arraylist.count) computer(s) found in Active Directory!"
    
    }
    $index = 0
    foreach ($listitem in $arraylist)
    {
       $index++
    
       #We format the index to be 2 digits longs
       Write-Host "$("{0:D2}" -f $index) : $listitem" 
    }
    
    #N.T.U.I. Never Trust User Input... If you enter incorrect value, it will not work. I let you do the checks ;)
    $choice = Read-Host -prompt "Select the computer you want to reboot."
    
    Write-Host "Attempting to Restart $($arraylist[$choice-1])..." -ForegroundColor Cyan
    
    #We restart the computer who has the value of the index (-1) into the list. -1 because a list starts from 0. So the 10th in the list is in fact the number 9
    #Restart-Computer -ComputerName $($arraylist[$choice-1])
    
    If (Test-Connection -Count 1 -ComputerName $($arraylist[$choice-1]) -Quiet) 
    { 
    Restart-Computer -ComputerName $($arraylist[$choice-1]) 
    } 
    else 
    { 
    Write-Host  "##############################################################################################" 
    Write-Host  "That computer is in Active Drictory but doesn't appear to be online!!"                            -ForegroundColor Red 
    Write-Host  "The users permissions have still been revoked but you still might try another computer listed"    -ForegroundColor Green
    Write-Host  "##############################################################################################" 
    }

Log in to reply
 

Looks like your connection to MangoLassi was lost, please wait while we try to reconnect.