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 :-)

Showing posts with label Powershell Scripting. Show all posts
Showing posts with label Powershell Scripting. Show all posts

Fetching all Windows Server details from Active Directory

 <# Created By Abhishek Bansal

Read Note 

Script Usage - Fetching all Windows Server details in the domain from Active Directory. Useful in doing inventory management.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". Once saved, run this script as Administrator

Execution & Outputs :: Once executed, there will be two Output files created as -

ADCompdetails.csv - Containing details of all the Windows server found in Active Directory.

Errorlogs.csv - Logs any error while fetching the uptime.#>

 

 $inputsrv = $(Get-ADComputer -Filter * -Properties OperatingSystem | ?{$_.OperatingSystem -match "Server"}).Name

foreach($server in $inputsrv)

{

$error.Clear()

    try{

    Get-ADComputer -Identity $server -Properties * | Select Name,OperatingSystem,DistinguishedName,IPv4Address,Enabled,Created | 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

    }

}

 


Fetching Uptime of Remote Windows Servers

  <# Created By Abhishek Bansal

Read Note 

Script Usage - Useful in fetching uptime of Servers mentioned in a txt file.

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

Execution & Outputs :: Once executed, there will be two Output files created as -

Uptime.csv - Containing uptime of Servers

Errorlogs.csv - Logs any error while fetching the uptime.#>


function fetchuptime($server)

{

    try{

    $Error.Clear()

    $details = Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Get-CimInstance -ClassName Win32_OperatingSystem}

    return $($details.LocalDateTime - $details.LastBootUpTime)

    }

    catch

    {

    Write-Host -ForegroundColor Red "Logging error while fetching uptime of $server."

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

    return "Error"  

    }

}


$Servers = Get-Content .\Servers.txt

Write-Host "Total Servers count = $($servers.count)"

#Pause for confirmation..

foreach($server in $Servers)

{

$server = $server.trim()

 try{

    $Error.Clear()

    Write-Host -ForegroundColor Yellow "`nChecking if $server exist in the domain or not ..."

    $compdetails = Get-ADComputer -Identity $server -Properties OperatingSystem 

    Write-Host -ForegroundColor Green "$server exist in domain having $($compdetails.OperatingSystem) OS."

    $uptime = fetchuptime -server $server

    if($uptime -eq "Error")

    {

   continue

    }

    else

    {

    $server | Select-Object -Property @{n="Hostname";e={$server}},@{n="Uptime";e={$(echo "Uptime is $($uptime.Days)Days $($uptime.Hours)Hrs $($uptime.Minutes)mins")}} | Export-Csv ./Uptime.csv -NoTypeInformation -Append

    }

   }

catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]

    {

    Write-Host -ForegroundColor Red "Logging error while fetching status of $server."

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

    }

}


Fetching NTFS Permissions, Inheritance Status & Ownership details of Root folders along with 1 Level Sub folders

 <# Created By Abhishek Bansal

 Read Note 

Script Usage - Useful in fetching Owners details, Inheritance status, NTFS Permissons of Parent / Root folder & one Level Sub folders.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". On same location create a txt file named "InputPath.txt" containing UNC path of share folders. Once saved, run this script as Administrator.

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

ParentfolderInheritance.csv - Containing parent folder Ownnership details along with inheritance status.

ParentfolderACL.csv - Containing parent folder NTFS permissions.

SubfoldersInheritance.csv - Containing one level subfoldes Ownnership details along with inheritance status.

SubfoldersACL.csv - Containing NTFS permissions for 1 level sub folders inside the parent folders.


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

 

 $rootfolders = Get-Content .\InputPath.txt

foreach($rootpath in $rootfolders)

{

$rootpath = $rootpath.trim()

Get-Acl -Path $rootpath  |  Select Path,Owner,@{n="Inheritance Status";e={$_.AreAccessRulesProtected}} | Export-Csv ./ParentfolderInheritance.csv -NoTypeInformation -Append

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

    $subfolders = Get-ChildItem -Path $rootpath

     foreach ($path in $subfolders)

    {

    try{

    Get-Acl -Path $path.FullName  |  Select Path,Owner,@{n="Inheritance Status";e={$_.AreAccessRulesProtected}} | Export-Csv ./SubfoldersInheritance.csv -NoTypeInformation -Append

     }

     catch{   

        $rootpath | Select @{n="Rootfolder";e={$rootpath}},@{n="Errorinfo";e={"$path not accessible under $rootpath"}} | Export-Csv ./Errorlogs.csv -NoTypeInformation -Append

        }

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

    }

}

 

Powershell Script - Finding out time Source of all the DC's in the domain

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Useful in fetching sync time source for all the domain controllers of the domain.

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

Execution & Outputs :: Once executed, there will be two files created as Timesyncdetails.csv containing output and Errorlogs.csv for any errors. #>


$dcs = (Get-ADDomainController -Filter *).Name

Write-Host -ForegroundColor Green "$((Get-ADDomain).PDCEmulator) is holding PDC role.."

$line = 0

$linecount = $dcs.Count

$pct = 0

foreach($dc in $dcs)

{

    $line++

    $dc = $dc.Trim()

    $pct = $line/$linecount * 100

    try{

    $error.Clear()

    Write-Progress -Activity " " -PercentComplete $pct

    Invoke-Command -ComputerName $dc -ScriptBlock{"`nFetching Sync time for $($using:dc)"} -ErrorAction Stop

    $dc | Select-Object -Property @{n="Hostname";e={$dc}},@{n="Source";e={Invoke-Command -ComputerName $dc -ScriptBlock{w32tm /query /source}}} | Export-Csv ./Timesyncdetails.csv -NoTypeInformation -Append

    }

    catch{

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

    }

}

Comparing Windows Services Status Prior and Post Reboot

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Validation Script, Useful in Comparing Windows Services Status before & after reboot.

Pre requisites :: Copy all the code into a text file, save it with an extension ".PS1". Once saved, run it as Administrator. You need to run this script twice, first prior reboot with Option 1 and second time will be after rebooting with option 2.

Execution & Outputs :: Once executed, there will be two files created as BeforeRestart.csv containing Services status before reboot & one with name AfterRestart.csv containing Services status post reboot. Differences among both the files will be visible directly on the console in Red color. #>


Write-Host -ForegroundColor Yellow   "`nPress 1 to fetch services status before reboot"

Write-Host -ForegroundColor Yellow  "Press 2 to fetch services status after reboot & proceed with validations.."

$choice = Read-Host "`nEnter your choice = "

if($choice -eq 1)

    {

    Get-Service | Select Name,DisplayName,Status | Export-Csv ./BeforeRestart.csv -NoTypeInformation

    }

    elseif($choice -eq 2)

    {

    Get-Service | Select Name,DisplayName,Status | Export-Csv ./AfterRestart.csv -NoTypeInformation


    $Beforerestartdata = Import-Csv .\BeforeRestart.csv

    $Afterrestartdata = Import-Csv .\AfterRestart.csv


#Comparing Services.....


foreach($row in $Beforerestartdata)

{

    foreach($row1 in $Afterrestartdata)

    {

           if($($row.Name) -eq $($row1.Name))

           {

                if($($row.Status) -eq $($row1.Status))

                {

                 Write-Host "$($row.Name) seems fine" -ForegroundColor Green    

                }


                else

                {

                

                Write-Host "$($row.DisplayName) service is having differences. Before Reboot Status was $($row.Status) and after reboot status is $($row1.Status)" -ForegroundColor Red

                

                }

           }


           else

           {

            continue

           }

           

    }


}

        }

    else

    {

    Write-Host "Invalid Choice..."

    }


Powershell Script - Comparing Policies sub folders with GP

  <#Created By - Abhishek Bansal

Read Me !!

Script Usage - This script will compare sub folder of Policies folder inside Sysvol for every DC with the Group Policy configured in GPMC

Once it compares, it will list all the Policy folders which are mapped to GPMC and show as "Valid GPO Folder" and Policy folder for any non existing Group Policy would be shows as "Not valid GPO folder .#>


$gpoid = Get-GPO -All

$dcs = (Get-ADDomainController -Filter *).Name

foreach($dc in $dcs)

{

    if($(Test-Path -Path "\\$dc\sysvol\Mari.com\Policies")-eq $true)

    {

    $Sysvolgpos = $(Get-ChildItem -Path "\\$dc\sysvol\Mari.com\Policies" -Exclude "*PolicyDefin*").Name

            $arr = @()   

                                foreach($Sysvolgpo in $Sysvolgpos)

                        {

                              foreach($gpo in $gpoid)

                                {

                                    $gpoingpmc = "{$($gpo.id)}"

                                    if($($gpoingpmc -eq $Sysvolgpo))

                                        {

                                        $arr += $gpoingpmc

                                        break

                                            }

                                   }

                }

        }

$Sysvolgpos | Where {$arr -Contains $_} | Select-Object -Property @{n="Domain Controller";e={$dc}},@{n="GPO Folder";e={$_}},@{n="Status";e={"Valid GPO folder"}}

$Sysvolgpos | Where {$arr -NotContains $_} | Select-Object -Property @{n="Domain Controller";e={$dc}},@{n="GPO Folder";e={$_}},@{n="Status";e={"Not valid GPO folder"}}

}


Sample Output












Fetching Event Logging Mode on Windows Servers

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Want to check what logging mode is configured for events like System , Setup, Application , Security logs for all your servers ?? What' the current size of all the events contained in these logs ?? What's the maximum log size of these events ?? For all this, use below script.

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" which will be containing names of machines. Once saved, run script as Administrator.

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


$servers = Get-Content .\InputServers.txt

foreach($server in $servers)

{

$server = $server.trim()

$Error.Clear()

    try{

    Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Get-WinEvent -ListLog Application,Setup,System,Security | Select-Object @{n="Hostname";e={$using:server}},LogName,LastAccessTime,LastWriteTime,@{n="MaximumLogSize(MB)";e={[Math]::Round($($_.MaximumSizeInBytes)/1024/1024,1)}},@{n="CurrentEventSize(MB)";e={[Math]::Round($($_.FileSize)/1024/1024,1)}},@{n="Events Count";e={$_.RecordCount}},@{n="LoggingMode";e={$(if($_.Logmode -eq "Circular"){echo "Overwrite events as needed (Oldest events first)"}elseif($_.Logmode  -eq "Retain"){echo "Do not overwrite events (Clear logs manually)"}elseif($_.Logmode  -eq "AutoBackup"){echo "Archive the log when full, do not overwrite events)"})}},LogFilePath} | Export-Csv ./LoggingmodeOutput.csv -NoTypeInformation -Append

        }

    catch

    {

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

    }

}


Sample Output 






























Powershell Script - Disabling IPv6 on Windows Servers

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Disabling IPv6 under TCP/IP for a NIC Card.

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" which will be containing names of machines. Once saved, run script as Administrator.

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


$servers = Get-Content .\InputServers.txt

$filename = "Postresults_"+ $(Get-Date -Format "dd_MM_yyy")+".csv"

foreach($server in $servers)

{

$Error.Clear()

    try{

    Invoke-Command -ComputerName $server -ErrorAction Stop -ScriptBlock{Disable-NetAdapterBinding -Name * -ComponentID ms_tcpip6}

    Invoke-Command -ComputerName $server  -ScriptBlock{Get-NetAdapterBinding | Where-Object ComponentID -EQ 'ms_tcpip6'} | `

    Select-Object -Property @{n="Hostname";e={$server}},@{n="Adapter";e={$_.Name}},Displayname,Enabled | Export-Csv ./$filename -Append -NoTypeInformation

    }

    catch{

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

    }

}

# Below option under TCP/IP will be unchecked post executing this script.







Powershell Script - Fetching AD Infra Details

<#Created By Abhishek Bansal
Read Note 

Script Usage :: Being working as Active Directory Admin & that too for multiple clients, i always have curiosity of getting an overview of their environment. So for this, i created below script which can give a high level overview of their Active Directory Environment.

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

Execution & Outputs :: During  execution, provide Client name when prompted. Output will be saved in a file named "Output.html" onto same location.
You will get to know about things like which all DC's are holding FSMO roles, Domain / Forest functional level, Total sites, Total Windows servers along with version wise count. #>


$client = Read-Host "Enter Client name = "
$detailOutput = "<html><body>
<h1>$client - Environment Info - $(Get-Date) </h1>
<table border=1 width=35% style='float: left'>"
$domaininfo = Get-ADDomain
$forestinfo = Get-ADForest
$detailOutput += "<tr>
<td width=15%><b>Fields</b></td>
<td width=20%><b>Values</b></td></tr>

<tr>
<td>Forest</td>
<td>$($domaininfo.Forest)</td></tr>

<tr>
<td>Root Domain</td>
<td>$($forestinfo.RootDomain)</td></tr>

<tr>
<td>Domain SID</td>
<td>$($domaininfo.DomainSID)</td></tr>

<tr>
<td>Forest Functional Level</td>
<td>$($forestinfo.ForestMode)</td></tr>

<tr>
<td>Domain Functional Level</td>
<td>$($domaininfo.DomainMode)</td></tr>

<tr>
<td>PDCEmulator Holder</td>
<td>$($domaininfo.PDCEmulator)</td></tr>

<tr>
<td>RIDMaster Holder</td>
<td>$($domaininfo.RIDMaster)</td></tr>

<tr>
<td>InfrastructureMaster Holder</td>
<td>$($domaininfo.InfrastructureMaster)</td></tr>

<tr>
<td>Schemamaster Holder</td>
<td>$($forestinfo.SchemaMaster)</td></tr>


<tr>
<td>DomainNamingMaster Holder</td>
<td>$($forestinfo.DomainNamingMaster)</td></tr>

<tr>
<td>Total Site count</td>
<td>$((Get-ADReplicationSite -Filter *).count)</td>
</tr>
"

$inventoryouput = "<table border=1 width=30% style='float: left;margin-left:100px'>"
$inventoryouput += "<tr>
<td><b>Fields</b></td>
<td><b>Values</b></td></tr>

<tr><td>Windows Servers Count</td>
<td>$((Get-ADComputer -Properties OperatingSystem  -Filter {OperatingSystem -like "Windows Server*"}).count)</td></tr>

<tr><td>Domain Controllers Count </td>
<td>$((Get-ADDomainController -Filter *).count)</td></tr>"


$osflavours = Get-ADComputer -Properties OperatingSystem  -Filter {OperatingSystem -like "Windows Server*"} | Select Operatingsystem -Unique

foreach($version in $osflavours)
{
$inventoryouput += "<tr><td>$($version.Operatingsystem)</td>"
$os = $((Get-ADComputer -Properties OperatingSystem -Filter * | ?{$_.Operatingsystem -eq $version.Operatingsystem})).Name
$inventoryouput += "<td>$($os.count)</td></tr>"


}

$detailOutput += "</table>"
$detailOutput | Out-File .\Output.html -Append


$inventoryouput += "</table></body></html>"
$inventoryouput | Out-File .\Output.html -Append






Output snap for reference -







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

    }

}

Powershell Script - AD User Account & Password related details

 <#Read Me

Script Usage - Finding UserID password related details such as -

1. Password Expired or not ?

2. If Expired, then on which day it's going to expired ?

3. How many days left before it expires ?

4. Whether UserId is active or not ?


Note - Input.txt contains Samaccountname of all the users against which you are looking to get info.

Input.txt should be in the same location of script.

Refer Userdetails_$date.csv for detailed output.


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


$inputuserids = Get-Content ./Input.txt

$date = $(Get-Date -Format "dd_MM_yyy")+".csv"

foreach($userid in $inputuserids)

{

    try{


Get-ADUser -Identity $userid -Properties Displayname,msDS-UserPasswordExpiryTimeComputed,PasswordExpired,Enabled,`

Passwordlastset | Select Displayname,Samaccountname,@{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}}`

| Export-Csv ./Userdetails_$date.csv -NoTypeInformation -Append


}

catch

{

$userid | Select-Object -Property @{n="Displayname";e={"NA"}},@{n="Samaccountname";e={$userid}},@{n="AccountStatus";e={"NA"}},@{n="Passwordlastset";e={"NA"}},@{n="PasswordExpired";e={"NA"}},@{n="ExpiryDate";e={"NA"}},@{n="DaysLeft";e={"NA"}}| Export-Csv ./Userdetails_$date.csv -NoTypeInformation -Append


}


}

Sample Output





Powershell Script - New AD Groups Creation from .CSV File

Few weeks back, I got a task to create multiple AD Groups from a CSV file. Below is a dummy look of a CSV that i got.



<#Read me !!

1. Make sure columns heading mentioned in Input file should not be altered.

2. In below case, i am taking details such as Group name, Path, scope description from Input.csv.

3. Logs_date.csv file can also be referred for detailed output.

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

$groupdetails = Import-Csv .\Input.csv

$date = $(Get-Date -Format "dd_MM_yy")+".csv"

foreach($group in $groupdetails)

{

    try

    {

    New-ADGroup -Name $group.Name -GroupScope $group.Scope -GroupCategory $group.Category -Path $group.Path -Description $group.Description -PassThru  | Select Name,@{n=("Status");e={("Created under")}},DistinguishedName | Export-Csv ./Logs_$date -Append -NoTypeInformation

    }


catch

    {

       $group | Select-Object -Property @{n=("Name");e={($group.Name)}},@{n=("Status");e={("already exist under ")}},@{n="DistinguishedName";e={((Get-ADGroup -Identity $group.Name).DistinguishedName)}} | Export-Csv ./Logs_$date -Append -NoTypeInformation

        }

}

Sample Output after Groups creation















Powershell Script - Checking SMB1 Feature Status on Windows Servers

$servers = @("DDC01","DMMS01","DMMS02","DDC02","FakeServer","Tempvm4") #Listing all servers in " " quotes. Take input from a file if server count is large.

$date = (Get-Date -Format "dd_MM_yyyy")+".html"

$outputHTML = "<HTML>

<Body><Table border='2'>

<h2> SMB1 Status Report Started at $(Get-Date)</h2>

<TR><Td>Name</Td><Td>Operating System</Td><Td>DistinguishedName</Td>s

<Td>SMB1Status</Td></Tr>"


foreach($server in $servers)

{

$server = $server.trim()

$error.Clear()

try{

$command1 = Get-ADComputer -Identity $server -Properties OperatingSystem,DistinguishedName | Select-Object -Property Name,OperatingSystem,DistinguishedName -ErrorAction Stop 

}

catch{

$command1 = "Error"

}

try{

$command2 = Invoke-Command -ComputerName $server -ScriptBlock{(Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol).State} -ErrorAction Stop

}


catch{

$command2 = "Error"

}

if(($command1 -eq "Error")) 

    {

    $outputHTML += "<TR style='background-color:orange'>"

     $outputHTML += "

    <TD>$($server)</TD>

    <TD>$("NA")</TD>

    <TD>$("NA")</TD>

    <TD>$("Unable to fetch, please check manually")</TD>

    </TR>"

    }

    elseif(($command2 -eq "Error"))

    {

    $outputHTML += "<TR style='background-color:orange'>"

     $outputHTML += "

    <TD>$($server)</TD>

    <TD>$($command1.OperatingSystem)</TD>

    <TD>$($command1.DistinguishedName)</TD>

    <TD>$("Unable to fetch, please check manually")</TD>

    </TR>"

   }

else

    {

    $command3 = $command1 | Select-Object -Property Name,OperatingSystem,DistinguishedName,@{n="SMB1Status";e={$command2}}

        if(($($command3.SMB1Status.Value) -eq "Disabled"))

        {

        $outputHTML += "<TR style='background-color:red'>"

        }

        else

        {

        $outputHTML += "<TR>"

        }


   $outputHTML += "

    <TD>$($command3.Name)</TD>

    <TD>$($command3.OperatingSystem)</TD>

    <TD>$($command3.DistinguishedName)</TD>

    <TD>$($command3.SMB1Status.Value)</TD>

    </TR>"

    }

}


$outputHTML += "</Table></Body></Html>"

$outputHTML += "<h2> SMB1 Status Report Ended at $(Get-Date) </h2>"

$outputHTML | Out-File ./SMB1Status_$date



Sample Output






Powershell Script - Windows Servers User Profile Status Check :: Cleanup Project

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Useful in finding out all the domain profiles created under C:\Users on Windows Servers is Enabled or Not in AD.

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

Execution & Outputs :: Output will be displayed in ProfileID_Status.csv #>


$srv = Read-Host "Enter Name or IP address of the Server = "

$Profile = Get-ChildItem "\\$srv\c$\Users" -Exclude "Public","Administrator*",".Net*","MSSQL*","Temp*"   #Mention any other local profile that you want to exclude.

foreach($row in $Profile.Name){

    $row = $row.Trim()

    try{

    Get-ADUser -Properties * $row | Select-Object -Property Displayname,Samaccountname,@{n="Status";e={$_.Enabled}},whenChanged,PasswordExpired,LastLogonDate | Export-Csv ./ProfileID_Status.csv -Append -NoTypeInformation

    }

    catch

    {

    $row | Select-Object -Property @{n="Displayname";e={"NA"}}, @{n="Samaccountname";e={$row}},@{n="Status";e={"ID is either local/disabled or doesn't exist in AD"}}, @{n="whenChanged";e={"NA"}}, @{n="PasswordExpired";e={"NA"}}, @{n="LastLogonDate";e={"NA"}} | Export-Csv ./ProfileID_Status.csv -Append -NoTypeInformation

    }

}


Sample Output