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

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

AD Script - Fetching all Windows Server Computers 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

    }

}

 


Windows Script - Fetching Uptime of 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

    }

}


Windows Script - 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

    }

}

 

AD 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

    }

}

Windows Script - Comparing Windows Services Status before and after 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..."

    }


Windows Script - 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 






























Windows Script - Disabling IPv6 on all Network adapters 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.







AD 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 -







AD Script - Adding multiple 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

}

AD Script - Fetching User details from their Email ID's as Input

<#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






AD Script - Fetching User's Group membership from AD

<#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

    }

}

AD Script - Fetching Computer details mentioned in input file from AD

<#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





Windows Script - Menu Driven Script to handle specific service on multiple Computers

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Menu driven script for Starting, Stopping 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.."

 }

}


AD Script - Identifying Disabled ID's in AD and Moving them in Disabled OU

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.  

<#Created By Abhishek Bansal

Read Me !!

Script Usage - 

1. Useful in doing AD Cleanups. Firstly Identfying 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 explicitly 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

    }

}

}


AD Script - Fetch membership of multiple AD Groups

<#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

    }

}

AD Script - Fetch User Account Password related details

 <#Created By - Abhishek Bansal

Read Note 

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 ?

Pre requisite :: Copy all the code into a text file, save it with an extension ".PS1". On the same location create a file named "Input.txt" containing Samaccountname of all the users against which you are looking to get info.

Execution & Outputs :: Once executed Output will be saved in a file named 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





AD Script - Creating new AD Groups

<#Created By - Abhishek Bansal

Script Usage - Creating new AD Groups.

Pre requisites :: Setup a Input.csv file containing details such as Group name, Category, Description, Group type and Path. Once done, 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, AD Groups will be created along with an output file named "Logs_date" containing all the results.#>

#Below is the snip of CSV file, (don't change the headers of each columns).













$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






Windows Script - Profile folder Status check with Active Directory | Cleanup Project

<#Created By Abhishek Bansal

Read Note 

Script Usage :: Checks all the profile folders created under C:\Users for their current status in AD, ie whether they are active or not. Useful in finding out unnecessary profile folder.

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



Powershell Script - Exporting GPO Settings in HTML

<#Read Me

Script Usage - Backing/Exporting GPO settings into HTML format.

Script Workflow

1. We can either use a ".txt" file as an Input file containing GPO's which we want to export.

2. Incase, we want to export all the GPO's in the domain, then use "Get-GPO" cmdlet with -All switch.

3. Outputs will be created in GPOname.html 

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


#Script 1 - Exporting all the GPO's in the domain.

$gpo = Get-GPO -All

foreach($item in $gpo)

{

$gponame = $item.DisplayName

Get-GPOReport -Name $gponame -ReportType HTML | Out-File ./$gponame.html

}


#Script 2 - Exporting all the GPO's mentioned in 'InputGPOdetails.txt' file.

#Note - Have this file under same folder where Script is kept.


$InputGPOdetails = Get-Content ./InputGPOdetails.txt

foreach($gponame in $InputGPOdetails)

{

Get-GPOReport -Name $gponame -ReportType HTML | Out-File ./$gponame.html

}