Some articles are posted as Images, Please use Computers to go through them for best experience. For phone users, switch to Web Version

AD Script - Disable ID's and then Move to different OU

 <#Created By - Abhishek Bansal

Use - Disable Users mentioned in InputUsers.csv and then move them onto a different OU containing all the disabled Users".

Prerquistes - Copy entire code, save it in a file with .ps1 extension. On same location, create another file named "InputUsers.csv". 

This csv will be containing user details in columns like Samaccountname, DistinguishedName.

#>

Start-Transcript -Path ./Transcript.txt -Append

$disabledOU_DN = Read-Host "Provide DN of Disabled OU = "  #***Provide destination OU of disabled Users***#

$userdetails = Import-Csv .\InputUsers.csv

$line = 0 #

$linecount = $userdetails.Count #

$pct = 0 #


foreach($user in $userdetails)

{

$Error.Clear()

$line = $line + 1 #

$pct = $line/$linecount*100 #

Write-Progress -Activity "Checking on $server" -Status "$line out of $linecount" -PercentComplete $pct #


    try{

   Write-Host -ForegroundColor Cyan "`nDisabling User account $($User.SamAccountName)"

   Disable-ADAccount -Identity $user.SamAccountName-PassThru -ErrorAction Stop | Export-Csv ./DisableUsersResult.csv -NoTypeInformation -Append

   Write-Host -ForegroundColor Green "Succesfully disable $($User.SamAccountName) ID."

     Write-Host -ForegroundColor Cyan "`nMoving User account $($User.SamAccountName) to $disabledOU_DN now.."

     Move-ADObject -Identity $user.DistinguishedName -TargetPath $disabledOU_DN -PassThru -ErrorAction Stop | Export-Csv ./MoveUserResult.csv -NoTypeInformation -Append

     Write-Host -ForegroundColor Green "Succesfully moved $($User.SamAccountName) ID."

    }

    catch{

    Write-Host -ForegroundColor Red "Error handling $($User.SamAccountName) ID."

    $user | Select-Object -Property @{n="User ID";e={$user.SamAccountName}},@{n="Error";e={$Error.exception.message}} | Export-Csv ./DisableUsersErrorlogs.csv -NoTypeInformation -Append

    }


}


Stop-Transcript

Windows Script - Test if Path input by User exist or not on Remote Servers

 <#Created By - Abhishek Bansal

Use - Script that runs on Servers mentioned in Input.txt file, checks if path input by User while executing this script exists or not on the server.

Prerquistes - Copy entire code, save it in a file with .ps1 extension. On same location, create another file named "Input.txt" and mention all the servers on which this script will run.

Output - TestaccessPath.csv file containing details. Column name Status shows if Path exist or not.

#>


$servers = Get-Content .\Input.txt

$line = 0 #

$linecount = $servers.Count #

$pct = 0 #

$path = Read-Host "Enter a path = "

$remotepath = $path -replace '^([A-Z]):', '$1$'

foreach($server in $servers)

{

$Error.Clear()

$line = $line + 1 #

$pct = $line/$linecount*100 #

Write-Progress -Activity "Checking on $server" -Status "$line out of $linecount" -PercentComplete $pct #

Write-Host -ForegroundColor Cyan "Traversing to $server."#

$result = Test-Path "\\$server\$remotepath" -ErrorAction Stop

    if($result -eq "True")

    {

    Write-Host -ForegroundColor Green "$($path) exists on $server`n"

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Path";e={$path}},@{n="Status";e={"Yes"}} | Export-Csv ./TestaccessPath.csv -NoTypeInformation -Append

    }

    else

    {

    Write-Host -ForegroundColor Red "$($path) doesn't exist on $server`n"

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Path";e={$path}},@{n="Status";e={"No"}} | Export-Csv ./TestaccessPath.csv -NoTypeInformation -Append

    }

}

Windows Script - Check Unallocated free space right after Recovery Partition

 <#Created By - Abhishek Bansal

Use - Script that runs on Servers mentioned in Input.txt file, fetches details of Servers having Unallocated free space right after Recovery Partition.

Prerquistes - Copy entire code, save it in a file with .ps1 extension. On same location, create another file named "Input.txt" and mention all the servers against which this script will run.

Output - Two Output files, Output.csv containing details and Errorlogs.csv containing errors if any occued during execution of script.

#>

$servers = Get-Content .\Input.txt

$line = 0

$linecount = $servers.Count

$pct = 0

foreach($server in $servers)

{

$line = $line + 1

$pct = $line/$linecount*100

$Error.Clear()

Write-Progress -Activity "Checking $server" -Status "$line out of $linecount" -PercentComplete $pct

Write-Host -ForegroundColor Green "Exporting results for $server."

try{

$OSDisk = Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Get-Disk | ?{$_.bootfromdisk -eq $true}}

$partitions = Invoke-Command -ComputerName $server -ScriptBlock{Get-Partition -DiskNumber $using:OSDisk.Number | Sort-Object Offset} -ErrorAction Stop 

$recoverypartition =  $partitions | Where-Object {$_.Type -eq 'Recovery'} | Sort-Object Offset -Descending | Select-Object -First 1

    if ($recoverypartition) {

        $recoveryEnd = $($recoverypartition.Offset + $recoverypartition.Size)

        $lastoffset = $partitions | Select-Object -Last 1

       if($($recoveryEnd /1GB) -lt $($lastoffset.Offset /1GB))

       {

       $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Status";e={"Recovery Partition is not at the end of volume, hence skipping checks"}},@{n="Size (GB)";e={"NA"}} | Export-Csv ./Output.csv -NoTypeInformation -Append

       }

      else

      {

        if($($OSDisk.Size /1GB) -gt $($recoveryEnd /1GB))

        {

        $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Status";e={"Yes, Unallocated space exists."}},@{n="Size (GB)";e={$($OSDisk.Size /1GB - $($recoveryEnd /1GB))}}  | Export-Csv ./Output.csv -NoTypeInformation -Append

        }

        else

        {

        $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Status";e={"No, Unallocated space exists."}},@{n="Size (GB)";e={"NA"}} | Export-Csv ./Output.csv -NoTypeInformation -Append

        }

    }}

    else

    {

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Status";e={"No Recovery Partition exists."}},@{n="Size (GB)";e={"NA"}} | Export-Csv ./Output.csv -NoTypeInformation -Append

       }

}

catch{

$server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Error";e={$Error.exception.Message}} | Export-Csv ./Errorlogs.csv -NoTypeInformation -Append

    }

}


Active Directory - Delegating SPN Read/Write Access to a Domain account

 

Windows - Setup an automated task that clear up Older log files automatically.

Powershell command to cleanup logs

Get-ChildItem "C:\UpdateLogs" -File -Recurse | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-5) } | Remove-Item -Force


































Windows Script - Fetching Ownership details, Inheritance status and NTFS Permissions of Root and all it's Subfolders

 <# Created By Abhishek Bansal

Read Note 

Script Usage - Useful in fetching Owners details, Inheritance status, NTFS Permissons of Parent / Root folder & all the sub folders.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1".Once saved, run this script as Administrato / from ID that has access to the folders.

Execution & Outputs :: Once executed, there will be multiple Outifle files created which would be -

FolderInheritance.csv - Containing Root folder and subfolders Ownnership details along with inheritance status.

FolderACL.csv - Containing Root folder and subfolders NTFS permissions.

Along with above, Errorlogs.csv can also be produced if there are any errors encountered while executing this script.#>

 


$RootPath = Read-Host "Enter Full Absolute Path of the Root folder = " 

$subfolders = Get-ChildItem -Path "$RootPath" -Filter * -Recurse -Directory | Select * #Listing all the Subfolders inside Root Path.


Get-Acl -Path $RootPath  |  Select-Object -Property @{n="Path";e={$RootPath}},Owner,@{n="Inheritance Blocked";e={$_.AreAccessRulesProtected}} | Export-Csv ./FolderInheritance.csv -NoTypeInformation -Append

(Get-Acl -Path $RootPath).Access | Select @{n="Path";e={$RootPath}},IdentityReference,FileSystemRights,AccessControlType | Export-Csv ./FolderACL.csv -NoTypeInformation -Append


foreach($Subfolder in $subfolders)

    {

    $Subfolderpath = $Subfolder.FullName

    try{

    Get-Acl -Path $Subfolderpath  |  Select-Object -Property @{n="Path";e={$Subfolderpath}},Owner,@{n="Inheritance Blocked";e={$_.AreAccessRulesProtected}} | Export-Csv ./FolderInheritance.csv -NoTypeInformation -Append

    (Get-Acl -Path $Subfolderpath).Access | Select @{n="Path";e={$Subfolderpath}},IdentityReference,FileSystemRights,AccessControlType | Export-Csv ./FolderACL.csv -NoTypeInformation -Append


       }


    catch{

    $Subfolderpath | Select @{n="Path";e={$Subfolderpath}},@{n="Errorinfo";e={"Path Not accessible."}} | Export-Csv ./Errorlogs.csv -NoTypeInformation -Append

    }


 }

AD Script - Fetching User's manager details from Active Directory

 <#Created By - Abhishek Bansal

Read Note

Script Usage :: Fetching User details along with their Manager's name & email ID from AD.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1".  A file named Input.txt needs to be created, this file will be containing User Samaccount name. Once saved run it with Admin rights.

Execution & Outputs :: Output_.csv fill will be containing all the results. #>

function getdetails($mgrdn)

{

$mgrdata = Get-ADUser -Properties * -Filter{DistinguishedName -like $mgrdn} | Select Samaccountname,Name,EmailAddress

return $mgrdata

}

$inputuser = Get-Content ./Input.txt

$line = 0 

$linecount = $inputuser.count

$percentagecomplete= 0

$filename = "Output_"+(Get-Date -Format "yyyy_MM_dd")+".csv"

foreach($userid in $inputuser)

{

$line++

$percentagecomplete = ($line / $linecount) * 100

$userid = $userid.trim()

Write-Progress -Activity "Checking Status.." -PercentComplete $percentagecomplete -Status "$line out of $linecount"

[String]$dn = (Get-ADUser -Properties * -Identity $userid).Manager

$managerdetails = getdetails -mgrdn "$dn"

$Error.Clear()

    try

    {

    Get-ADUser -Properties * -Identity $userid | Select Samaccountname,Name,EmailAddress,co,@{n="Manager_Samaccountname";e={$managerdetails.Samaccountname}},@{n="Manger Name";e={$managerdetails.Name}},@{n="Manager Mail";e={$managerdetails.EmailAddress}} `

    | Export-Csv ./$filename -NoTypeInformation -Append

    }

    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]

    {

    $userid | Select @{n="Samaccountname";e={$userid}},@{n="Name";e={$Error.Exception.Message}},EmailAddress,co,@{n="Manager_Samaccountname";e={}},@{n="Manger Name";e={}},@{n="Manager Mail";e={}} `

    | Export-Csv ./$filename -NoTypeInformation -Append

    }

}

AD Script - Exporting AD Group Membership containing Large count of members

<#Created By - Abhishek Bansal

Read Note 

Script Usage :: Fetching AD Group membership containing large number of members. There are cases where Get-ADGroupMember fails. ( More then 5K /6K ). Script is capable of exporting not only users objects but others too. ( Ex Groups ).

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". Once saved run it with Admin rights.

Execution & Outputs :: User need to input AD Group name when prompt & results can be checked in Groupname_Membership.csv file. #>

$group = Read-Host "Enter AD Group Name = "

$dn = Get-ADGroup -Identity $group -Properties * | Select objectClass -ExpandProperty Member

$line = 0 

$linecount = $dn.Count

$percentagecomplete= 0

foreach($row in $dn)

{

$line++

$percentagecomplete = ($line/$linecount)*100

$row = $row.trim()

Write-Progress -Activity "Checking Status.." -PercentComplete $percentagecomplete -Status "$line out of $linecount"

Get-ADObject -Properties * -Filter{DistinguishedName -like $row} | Select Name,Samaccountname,@{n="Member Category";e={$_.ObjectClass}} | Export-Csv ./$group.Membership.csv -NoTypeInformation -Append

}

 

AD Script - Remove Computer Objects from Active Directory

<#Created By - Abhishek Bansal

Script Usage - Deleting Computer Objects mentioned in Input.txt from AD.

Incase of Access Denied, run ISE as Administrator & make sure account used should have sufficient rights to delete a Computer Object.

For using it on any other server, just copy the entire folder, edit .ps1 into PS ISE & run it. 

#>

$servers = Get-Content -Path .\Input.txt

$line = 0

$linecount = $servers.Count

$percentagecomplete= 0

$filename = "Output_"+(Get-Date -Format "yyyy_MM_dd")+".csv"

foreach($server in $servers)

{

$error.Clear()

$server = $server.trim()

$line++

$percentagecomplete = $line / $linecount * 100

Write-Progress -Activity "Removing Computer Objects.." -PercentComplete $percentagecomplete -Status "$line out of $linecount"

    try{

    Remove-ADComputer -Identity $server -Confirm:$false

    $server | Select-Object -Property @{n="Computer Name";e={$server}},@{n="Status";e={("Deleted Succesfully")}} | Export-csv ./$filename -NoTypeInformation -Append

    }

    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]

      {

    $server | Select-Object -Property @{n="Computer Name";e={$server}},@{n="Status";e={$error.exception.Message}} |  Export-csv ./$filename -NoTypeInformation -Append

      }

}