Few of the articles are posted as Images, Please use Laptop / Computers to go through the articles for best experience. For phone users, switch to Web Version

Please Share with your colleagues if you found these blogs informative. Happy Learning :-)

Powershell Script - Adding Bulk Users in an AD Group

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Adding multiple Users in an AD Group.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "Inputusers.txt" which will be containing samaccount of all the users who will be added. Once saved, run script as Administrator.

Execution & Outputs :: During execution, it will prompt for AD group name. Need to provide the same. Once done, script will firt backup current membership of AD Group into Backup_membership.csv and final Output into Output.csv" onto same location. #>



$inputusers = Get-Content .\Inputusers.txt

$line = 0

$lines = $inputusers.count

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

Write-Host -ForegroundColor Yellow "`nAD Group Name Provided : $grp`n"

if((Get-ADGroup -Identity $grp).Samaccountname -eq $grp)

{

$choice = $(Write-Host -ForegroundColor Yellow "`nDo you want to proceed adding users mentioned in Inputusers.txt file to $grp. Press Y for Yes and N for No = " -NoNewline ; Read-Host)

Switch($choice)

{

Y {

 Write-Host -ForegroundColor Green "Backing up $grp Group membership before doing changes in Backup_membership.csv file.."

 Get-ADGroupMember -Identity $grp | Select Name,SamAccountName | Export-Csv .\Backup_membership.csv -NoTypeInformation

foreach($row in $inputusers)

{

    $line++

    $pct = $line/$lines * 100

    $row = $row.trim()

     Write-Progress -Activity "Adding Users ..." -PercentComplete $pct -Status "$line of $lines"

   try

    {

    Add-ADGroupMember -Identity $grp  -Members $row -Confirm:$false 

    $row | Select-Object -Property @{n="User ID";e={("$row")}},@{n="Status";e={("Added now.")}} | Export-Csv .\Output.csv -NoTypeInformation -Append

    }

    catch

    {

    $row  | Select-Object -Property @{n="User ID";e={($row)}},@{n="Status";e={($error.exception.Message)}} | Export-Csv .\Output.csv -NoTypeInformation -Append

    }


}

} #Closing Y condition

N {

Write-Host -ForegroundColor Green "You pressed N & hence nothing added in $grp AD Group."

} #Closing N condition

Default

{

Write-Host -ForegroundColor Red "Invalid Choice. Try again"

}

} #Closing switch

}

Powershell Script - Fetching User details from an Input file containing Email Id's of users - AD

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Fetching user details such as Name,Samaccountname,Accountstatus from Input file containing User Email address.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "Input.txt" which will be containing user's email address. Once saved, run script as Administrator.

Execution & Outputs :: Once executed Output will be saved in a file named "Userdetailsfromemail.csv" and any Errors into "Errorslogs.csv" onto same location.#>


$emaildata = Get-Content ./Input.txt

$line = 0

$linecount = $emaildata.Count

$pct

foreach($emailid in $emaildata)

    {

    $error.Clear()

    $line++

    $pct = $line/$linecount * 100

    $emailid = $emailid.trim()  

    Write-Progress -Activity "Fetching User account information.." -PercentComplete $pct -Status "$line of $linecount"

    if($(Get-ADUser -Filter{EmailAddress -eq $emailid}))

    {

    Get-ADUser -Properties * -Filter{EmailAddress -eq $emailid} | Select Name,Samaccountname,EmailAddress,@{n="AccountStatus";e={$_.Enabled}} | Export-Csv ./Userdetailsfromemail.csv -NoTypeInformation -Append

    }

    else

    {

    $emailid | Select-Object -Property @{n="EmailID";e={$emailid}},@{n="Error";e={"No User exist with this Emailid."}} | Export-Csv ./Errorlogs.csv -NoTypeInformation -Append

    }

}


Sample Output






Powershell Script - Fetching User Membership from Active Directory

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Fetching Membership of users from Active Directory.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "InputUserid.txt" which contains User's ID. Once saved, run script as Administrator.

Execution & Outputs :: Once executed Output will be saved in separate files named "UserID_Date.csv" and any Errors into "Errorslogs.csv" onto same location.#>


$inputusers = Get-Content .\InputUserid.txt

$date = $(Get-Date -Format "dd_MM_yyyy")

foreach($user in $inputusers)

{

    $user = $user.trim()

    try

    {

    $error.Clear()

    $file = "$user"+"_$date"

   Get-ADPrincipalGroupMembership -Identity $user | Select-Object -Property Name,GroupScope,GroupCategory,DistinguishedName | Export-Csv ./$file.csv -NoTypeInformation

    }

    catch

    {

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

    }

}

Powershell Script - Fetching AD Computer Details

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Fetching Computer details from Active Directory.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "InputServers.txt" cointaning Computer name. Once saved, run script as Administrator.

Execution & Outputs :: Once executed Output will be saved in "ADCompdetails.csv" and any Errors into "Errorslogs.csv" onto same location.#>


$inputsrv = Get-Content .\InputServers.txt

foreach($server in $inputsrv)

{

$error.Clear()

    try{

Get-ADComputer -Identity $server -Properties * | Select Name,OperatingSystem,DistinguishedName,Enabled,Created,@{n="Lastlogon";e={[datetime]::FromFileTime($_."Lastlogon")}} | Export-Csv ./ADCompdetails.csv -NoTypeInformation -Append

        }

    catch

    { 

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

    }

}


Sample Output

ADCompdetails.csv 






Errorlogs.csv





Powershell Script - Managing Windows Services ( Starting , Stopping & Fetching )

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Menu driven script for Starting, Stoping and fetching specific service from servers mentioned in a text file.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "Input.txt" which contains Server names. Once saved, run script as Administrator.

Execution & Outputs :: During execution it will first prompt to provide Service name and afterwards a prompt to choose if we want to Start, Stop or fetch service status from Servers. Once executed Output will be saved in separate ".csv files".#>


function startservice{

[CmdletBinding()]

param(

    [parameter()]

    [String] $server,$service

)

$error.Clear()

try{

Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Start-Service -Name $using:service -PassThru}

Invoke-Command -ComputerName $server -ScriptBlock{Get-Service -Name $using:service} | Select-Object -Property @{n="Hostname";e={$server}},Name,Displayname,Status | Export-Csv ./Startservices.csv -Append -NoTypeInformation

}

catch{

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Name";e={"NA"}},@{n="Displayname";e={"NA"}},@{n="Status";e={$error.exception.Message}} | Export-Csv ./Startservices.csv -Append -NoTypeInformation

}

}


function stopservice{

[CmdletBinding()]

param(

    [parameter()]

    [String] $server,$service

)

$error.Clear()

try{

Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Stop-Service -Name $using:service -Force -PassThru}

Invoke-Command -ComputerName $server -ScriptBlock{Get-Service -Name $using:service} | Select-Object -Property @{n="Hostname";e={$server}},Name,Displayname,Status | Export-Csv ./Stopservices.csv -Append -NoTypeInformation

}

catch{

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Name";e={"NA"}},@{n="Displayname";e={"NA"}},@{n="Status";e={$error.exception.Message}} | Export-Csv ./Stopservices.csv -Append -NoTypeInformation

}

function fetchservice{

[CmdletBinding()]

param(

    [parameter()]

    [String] $server,$service

)

$file = "Servicestatus_"+".csv"

$error.Clear()

try{

Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Get-Service -Name $using:service} | Select-Object -Property @{n="Hostname";e={$server}},Name,Displayname,Status | Export-Csv ./$file -Append -NoTypeInformation

}

catch{

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

}

}


$inputsrv = Get-content ./Input.txt

$service = Read-Host "Enter Service name = "

Write-Host "`nPress 1 to Start $service on servers mentioned in Input.txt.

Press 2 to Stop $service on servers mentioned in Input.txt.

Press 3 to fetch services status on servers mentioned in Input.txt "


$choice = Read-Host "Provide choice = "

foreach($server in $inputsrv)

 {

 $server = $server.trim()

 if($choice -eq 1)

 {

 startservice -server $server -service $service

 }

 elseif($choice -eq 2)

 {

 stopservice -server $server -service $service

 }

 elseif($choice -eq 3)

 {

 fetchservice -server $server -service $service

 }

 else

 {

 Write-Host "Invalid Choice.."

 }

}


Powershell Script - Identifying Disabled ID's in AD & Moving them in Disabled OU - Cleanup Project

Last month, i was given a cleanup project to locate all the Disable User account in Active Directory & move them into a specific OU. Below Script was created & it can be referred to accomplish this task.  

<#Read Me !!

Script Usage

1. Useful in doing AD Cleanups. Firstly Identying all the disabled ID's.

2. Once identified, moving them from different location in a particular OU.

Note - Based on your environment, specify Destination OU path explicity at the first line of Script.

Also, since we have some Default & System account in AD, so i have excluded them in foreach loop.

(Examples - Krbtgt, Guest, Default account etc)

You will be getting two CSVs post execution. BeforeScriptOutput displays all the Disabled ID's & the DN before any operation.

AfterScriptOutput.csv displays all the ID's that were moved to Disabled OU's


*********************************************************************************#>

$disabledOU_DN = "OU=DisabledUsers,DC=Mari,DC=com" #***Provide DisabledOU DN***#

$userdetails = Get-ADUser -Filter{(Enabled -eq $false)} -Properties Displayname,Enabled,DistinguishedName,CN `

| Select-Object -Property Displayname,Samaccountname,DistinguishedName,@{n="AccountStatus";e={if($($_.Enabled) -eq $true){"Active"}else{"Disabled"}}},CN

$userdetails | Export-Csv ./BeforeScriptOutput.csv -NoTypeInformation


foreach($user in $userdetails)

{

    $DN = "CN="+$($user.CN)+","+$($disabledOU_DN)

    if(($user.DistinguishedName -eq $DN) -or ($user.Samaccountname -like "krbtgt*") -or ($user.Samaccountname -like "Guest*") -or ($user.Samaccountname -like "DefaultAccount*"))

    {

    continue

    }

    else

    {

    try{

    Move-ADObject -Identity $user.DistinguishedName -TargetPath $disabledOU_DN

    Write-Host "Moved $($user.Samaccountname)"

    Get-ADUser -Identity $user.Samaccountname -Properties Displayname,DistinguishedName,Enabled,LastLogonDate,msDS-UserPasswordExpiryTimeComputed,PasswordExpired,`

    Passwordlastset | Select-Object -Property Displayname,Samaccountname,DistinguishedName,@{n="AccountStatus";e={if($($_.Enabled) -eq $true){"Active"}else{"Disabled"}}},`

Passwordlastset,PasswordExpired,@{n="ExpiryDate";e={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},`

@{n="DaysLeft";e={(New-TimeSpan -Start $(Get-Date) -End $([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed"))).Days}},`

LastLogonDate | Export-Csv ./AfterScriptOutput.csv -NoTypeInformation -Append

    }

catch

    {

    $user | Select @{n="Displayname";e={$user.Displayname}},@{n="Samaccountname";e={$user.Samaccountname}},@{n="DistinguishedName";e={"Error, unable to move"}}`

    ,@{n="AccountStatus";e={"NA"}},@{n="Passwordlastset";e={"NA"}},@{n="PasswordExpired";e={"NA"}},@{n="ExpiryDate";e={"NA"}},@{n="DaysLeft";e={"NA"}},@{n="LastLogonDate";e={"NA"}} `

    | Export-Csv ./AfterScriptOutput.csv -NoTypeInformation -Append

    }

}

}


Powershell Script - Fetch membership of multiple AD Groups at once.

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Fetching Membership of Multiple AD Group at once.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a text file named "Input.txt" which contains AD Group names. Once saved, run script as Administrator.

Execution & Outputs :: Output will be saved into separate files named "Groupname.csv" and any error logs into Errorlogs.csv #>


$grp = Get-Content .\Input.txt

    foreach($groupname in $grp)

    {

    $groupname = $groupname.Trim()

    $error.Clear()

    try{

    $membership = Get-ADGroupMember -Identity $groupname | Select Name,Samaccountname,DistinguishedName,@{n="ObjectType";e={$_.objectClass}}

    $membership | Export-Csv ./$groupname.csv -NoTypeInformation -Append 

    }

   catch

    {

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

    }

}