Tuesday, 27 October 2015

Powershell deleting SharePoint and SQL 90 days old logs files




#---------------------------------------------------------------#
#Script Ttile : deleting SharePoint and SQL 90 days old logs files 
#Scrit Author : KRR 
#---------------------------------------------------------------#

$SPLogs = "C:\logs"  # SharePoint log file location

$SqlLogs = "C:\Sql_logs" #SQL Server Log file location

$path = @($SPLogs,$SqlLogs)
$limit = (Get-Date).AddDays(-90)  #log file age
foreach($logs in $path)
{
write-host "SharePoint and SQL  logs are deleting!!!!" -ForegroundColor Yellow -BackgroundColor Black

Get-ChildItem $logs -Recurse |where-object{$_.CreationTime -gt $limit} | Remove-Item

write-host "SharePoint and Sql logs deleted sucessfully" -ForegroundColor green -BackgroundColor Black

}

Powershell Script to delete 90 days old SharePoint ULS logs


#---------------------------------------------------------------#
#Script Ttile : deleting the 90 days old log files from one server
# Scrit Author : KRR 
#---------------------------------------------------------------#

$SPLogs = "C:\logs"  # SharePoint log file location
$limit = (Get-Date).AddDays(-90)  #log file age
try
{
write-host "SharePoint ULS logs are deleting!!!!" -ForegroundColor Yellow -BackgroundColor Black

Get-ChildItem $SPLogs -Recurse |where-object{$_.CreationTime -lt $limit} | Remove-Item

write-host "SharePoint ULS logs deleted sucessfully" -ForegroundColor green -BackgroundColor Black
}
catch
{
write-error "error deleting the log files or no files found" 
}

#

Thursday, 8 October 2015

Powershell to Enable Remote Desktop Remotely


Below are the Powershell cmdlets to enable Remote Desk top feature on Servers and Client OS.

Enable Remote Desktop:

Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0



Disable Remote Desktop:

Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 1



Enable secure RDP authentication:


Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1


Allow incoming RDP on firewall:

Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

Wednesday, 7 October 2015

Install and Configure Active Directory and DNS with PowerShell


I have created this script to install and Configure Active Directory services & DNS

Please save below script as "Install_Configure_AD_DNS.Ps1" file and execute in Powershell with Administrator rights on Server.

References : 
https://technet.microsoft.com/en-us/library/hh974720(v=wps.630).aspx



#----------------------------------------------------------------------------#
#Script Title : Install and Configure Active Directory and DNS
#Script Author : KRR
#----------------------------------------------------------------------------#
Import-Module ServerManager
Write-Host "Installing the windows feature: Active Directory Domain Service" -ForegroundColor "Green"
Install-windowsfeature AD-domain-services  –IncludeManagementTools
Write-Host "Active Directory Domain Service Installed successfully!!!" -ForegroundColor "Green"
Write-Host "Importing Active Directory Module..........." -ForegroundColor "Yellow"
Import-Module ADDSDeployment
Write-Host "Importing Active Directory Module Done" -ForegroundColor "Green"
#----------------------------------------------------------------------------------------#
Write-Host "Please enter the below details to configure AD and DNS" -ForegroundColor "Blue"
#-----------------------------------------------------------------------------------------#
$DomainandForestModes = @("-- Windows Server 2003: 2 or Win2003","-- Windows Server 2008: 3 or Win2008","-- Windows Server 2008 R2: 4 or Win2008R2","-- Windows Server 2012: 5 or Win2012","-- Windows Server 2012 R2: 6 or Win2012R")
#------------------------------------------------------------------------------------------#
Write-Host "Below are the domain and Forest function levels..." -ForegroundColor "Yellow"
$DomainandForestModes
$domainMode = Read-Host "Please enter Domain Functional Mode number or Value"
$ForestMode = Read-Host "Please enter Forest Functional Level"
$InstallDNS = Read-Host "Please enter '$true' if you want install DNS"
$DomainName = Read-Host "Please enter Domain Name , Example : corp.com"
$DomainNetbiosName = Read-Host "Please enter Domain NetBios Name , Example : corp"
#------------------------------------------------------------------------------------------#
Write-Host " Active Directory  and DNS configuration is in-progress" -ForegroundColor "Green"
Install-ADDSForest  -CreateDnsDelegation:$false -DatabasePath "C:\Windows\NTDS" -DomainMode $domainMode -DomainName $DomainName -DomainNetbiosName $DomainNetbiosName -ForestMode $ForestMode -InstallDns:$InstallDNS -LogPath "C:\Windows\NTDS" -NoRebootOnCompletion:$false -SysvolPath "C:\Windows\SYSVOL" -Force:$true
#-----------------------------------------------------------------------------------------------#
Write-Host "Active Directory and DNS configuration Completed!" -ForegroundColor "Green"

#--------------------------------End-----------------------------------------------------------#

Please feel to add comments and suggestions

Thanks
KRR

Monday, 20 April 2015

Change or Re-name single or multiple Computers Name using PowerShell Scripts

Syntax
Parameter Set: Default
Rename-Computer [-NewName] <String> [-ComputerName <String> ] [-DomainCredential <PSCredential> ] [-Force] [-LocalCredential <PSCredential> ] [-PassThru] [-Restart] [-Confirm] [-WhatIf] [ <CommonParameters>]

Reference:https://technet.microsoft.com/en-us/library/hh849792.aspx

Change Single comupter name:

Using Domain Credentials:
Rename-Computer -NewName WIN-SP01 -DomainCredential CORP\Administrator -Restart     #-Please Change computer name and domain credentials

Using Domain and Local credentials:
Rename-Computer -ComputerName WIN-89C5DXRG -NewName WIN-SP01 -LocalCredential "WIN-89C5DXRG\Administrator" -DomainCredential "CORP\Administrator" -Force -PassThru -Restart


Change/Re-Name multiple computers:


$a = Import-Csv C:\Serverslist.csv -Header OldName, NewName   #-Change csv file path

Foreach ( $Server in $a ) 
{
Rename-Computer -ComputerName $Server.OldName -NewName $Server.NewName -DomainCredential Domain01\Admin01 -Force -Restart

write-Host "$Server Name has been changed successfully!!" -ForegroundColor "Green" -BackgroundColor "Black"

}
else
{

write-Host "Unable to connect remote server $Server" -ForegroundColor "Yellow" -BackgroundColor "Red"

}

Tuesday, 17 March 2015

Powershell script to monitor SharePoint Timer jobs

The below script will monitor status of SharePoint user profile services timer jobs and email notification will be send to administrators

# -----------------------------------------------------------------------------
# Script : User Profile Jobs Daily Status Report
#------------------------------------------------------------------------------
#Add SharePoint PowerShell Snap-In
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$today=Get-Date
$WebApp = Get-SPWebapplication -identity "http://intranet.domain.com"    #change your Url here..
function Get-SPTimerJobStatus ()
{
    Get-SPTimerJob  |sort Name |Where {$_.WebApplication.Name -eq "Intranet" -and  $_.DisplayName -like "*User Profile*" } | ForEach-Object {
        $lastRun = $_.HistoryEntries | Select-Object -first 1
        if ($_.WebApplication -eq "$WebApp ") { $level = $_.WebApplication.Url }
        else { $level = "Farm" }
     
        $values = @{
            "Name" = $_.Name
           "Job Title" = $_.DisplayName
            "SiteName" = $_.WebApplication.Name
            "Level" = $level
            "StartTime" = $lastRun.StartTime
            "EndTime" = $lastRun.EndTime
            "Status" = $lastRun.Status
"Schedule" = $_.Schedule
"Duration (HH:MM:SS)" = ($lastRun.EndTime - $lastRun.StartTime)

        }
        New-Object PSObject -Property $values | Select @("Job Title", "SiteName", "Schedule","StartTime","EndTime","Status", "Duration (HH:MM:SS)" )
    }
}
$TimerJobStatus = Get-SPTimerJobStatus |ConvertTo-Html -Fragment


#-----------------------------------------------------------------------------------------
#Style Body
#-----------------------------------------------------------------------------------------
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{font-family:sans-serif;font-size:10pt;border-width:5px;border-style: solid;border-color: black;border-collapse: collapse;cellpadding:10px cellspacing:10px}"
$a = $a + "TH{border-width: 2px;padding: 3px;border-style: solid;border-color: black;background-color:blue}"
$a = $a + "TD{border-width: 2px;padding: 3px;border-style: solid;border-color: black;background-color:FFFAF0}"
$a = $a + "</style>"
ConvertTo-Html -head "$a" -Body "<font color = red><H2>Timer Jobs status Reports for $today</H2></font>$TimerJobStatus | Out-File "C:\Scripts\TimerJobsreport.txt"  #change path here


#-----------------------------------------------------------------------------------------
#Send email to administrators
#-----------------------------------------------------------------------------------------
$Subject = "User profile Jobs status Reports for $today"
$To = "administrator@domain.com"              #change email address here..
$From = "StatusReport@domain.com"         #change from address here...
$SMTP = "smtp.domain.com"                       #change SMTP address here..
$SPReport = Get-Content "C:\Scripts\TimerJobsreport.txt"

Send-MailMessage -To $To -SmtpServer $SMTP -From $From -Subject $Subject -BodyAsHtml "$SPReport"

PowerShell Script to Schedule daily Site collections backup and retention policy for backup files

PowerShell Script to Schedule daily Sites collection backup and retention policy for backup files


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
try
{
$today = (Get-Date -Format dd-MM-yyyy)
 [IO.Directory]::CreateDirectory("D:\SharePointBackups\Production_$today")

Backup-SPSite -Identity http://sitea.domain.com/ -Path D:\SharePointBackups\Production_$today\SiteA.bak
Backup-SPSite -Identity http://siteb.domain.com/ -Path D:\SharePointBackups\Production_$today\SiteB.bak
Backup-SPSite -Identity http://sitec.domain.com/ -Path D:\SharePointBackups\Production_$today\SiteC.bak
Backup-SPSite -Identity http://sited.domain.com/ -Path D:\SharePointBackups\Production_$today\SiteD.bak
}
catch
{
"No sites found!!!!"
}
#Retention policy for old backup files
try
{
# set folder path
$dump_path = "D:\SharePointBackups"

# set min age of files
$max_days = "-5"

# get the current date
$curr_date = Get-Date

# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)

# delete the files
Get-ChildItem $dump_path -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item  -force -Confirm:$false -ErrorAction:SilentlyContinue;

}
catch
{
"No path found!!!"
}