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!!!"
}

PowerShell script to monitor SharePoint Services and W3wp process

Below is the script to send status of Services and process from single server

$smtpServer = "mailserver.domain.com" #change your smtp addresss here..
$smtpFrom = "StatusReports@domain.com" #Change your from address
$smtpTo = "users@domain.com" #add users valid email address
$messageSubject = "Services and Process Status report"

$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"

$message.Body = Get-service |where-object{$_.Displayname -like "*SharePoint*"} | Select-Object Displayname,Name,Status | ConvertTo-Html -Head $style

$message.Body+ = Get-Process |where-object{$_.ProcessName  -like"w3wp*"} | Select-Object ProcessName,Id | ConvertTo-Html -Head $style

$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)

Powershell to configure App Management Service Application

Power shell script to configure App Management Service Application and Subscription Settings Service

The below script performs the following:


  1. Creates new application pool for App Management Service Application and Subscription Settings Service
  2. Starts the App Management and Subscription Settings Services
  3. Creates the new Database for App Management Service Application and Subscription Settings Service
  4. Configures the App Management Service Application and Subscription Settings Application
  5. Configures the App URL


Assuming that you have already been configured “Domain Name in DNS to host the apps” if not please follow the below link to configure it.



Note: Copy the below script in notepad and save as ConfigureAppManagmentService.ps1
======================================================================

#create a new application pool for App Management Service application 
$apppool = New-SPServiceApplicationPool -Name "App Management_AppPool" -Account "Domian\sp_farm"  #change your account here..

$appname = "App Management Service"
$dbname = "AppManagement_DB"

#Start App Management service
Get-SPServiceInstance | Where-Object { $_.typename -eq "App Management Service" } | Start-SPServiceInstance

Write-Host "App Management Service started successfully" -ForegroundColor "Yellow" -BackgroundColor "Black"

#Create App Management Service Application
$appmanagmentsa = New-SPAppManagementServiceApplication -ApplicationPool $apppool -Name $appname -DatabaseName $dbname

Write-Host "App Managment Service Application created successfully" -ForegroundColor "Green" -BackgroundColor "Black"

New-SPAppManagementServiceApplicationProxy -ServiceApplication $appmanagmentsa 

Write-Host "App Managment Service Application Proxy created successfully" -ForegroundColor "Green" -BackgroundColor "Black"

$Subscriptionappname = "Subscription Settings Service"
$Subscriptiondbname = "Subscription_Settings_Service_DB"

#Start SharePoint Foundation Subscription Settings service
Get-SPServiceInstance | where{$_.TypeName -eq "Microsoft SharePoint Foundation Subscription Settings Service"} | Start-SPServiceInstance

Write-Host "Subscription Settings Service Started successfully" -ForegroundColor "Yellow" -BackgroundColor "Black"

# Create the Subscription Settings service Application
$Subscriptionsa = New-SPSubscriptionSettingsServiceApplication -ApplicationPool $appPool -Name $Subscriptionappname -DatabaseName $Subscriptiondbname

Write-Host "Subscription Settings Service Application created" -ForegroundColor "Green" -BackgroundColor "Black"

New-SPSubscriptionSettingsServiceApplicationProxy -ServiceApplication $Subscriptionsa

Write-Host "Subscription Settings Service Application proxy created" -ForegroundColor "Yellow" -BackgroundColor "Black"

# Configure your app domain and location
Set-spappdomain -appdomain "appsdomain.com" #change your App domain name here..
Set-spappSiteSubscriptionName -Name "apps"

Write-Host "App domain registred successfully" -ForegroundColor "Green" -BackgroundColor "Black"

#End of script

Thursday, 12 March 2015

Disable Local Administrator account for multiple servers

Disable Local Administrator account for multiple servers

$list =  Import-CSV "C:\Scripts\Serverslist.csv"  #change location of your file
foreach($servers in $list) {

try{

$computer = $servers.ServerName
$User = [ADSI]"WinNT://$computer/Administrator,user"
$User.AccountDisabled = $True
$User.SetInfo()

Write-Host "Administrator Account has been disabled on $computer Succesfully" -ForegroundColor "Green" -BackgroundColor "Black"
}
catch
{

Write-Host "Unable to reach server $computer" -ForegroundColor "Yellow" -BackgroundColor "Red"

}
}


     
     

Set Password Never Expire and User can not change Password for Local User Accounts for Remote Severs

The below script will perform the following tasks:
  1. Set Password Never expire
  2. Set User can not change Password
#-----------------------------------------------------------------------------------------------#
#Script title: Set Local Administrator account password Never expired and can not changed#
#Usage: Change csv file path
#-----------------------------------------------------------------------------------------------#
$list =  Import-CSV "C:\Scripts\Serverslist.csv"    #give your file path here
$ADS_UF_PASSWD_CANT_CHANGE                       = 64        # 0x40
$ADS_UF_DONT_EXPIRE_PASSWD                       = 65536     # 0x10000

foreach($Server in $list) {

$computerName = $Server.ServerName

$computer = [ADSI]"WinNT://$computerName,computer"
$Users = $computer.psbase.Children | Where-Object {$_.psbase.schemaclassname -eq 'user'}
foreach ($user in $Users.psbase.syncroot)
{
try{
If ( $user.name -ne "Guest"){

  $user.userflags = $user.userflags[0] -bor $ADS_UF_DONT_EXPIRE_PASSWD
  $user.userflags = $user.userflags[0] -bor $ADS_UF_PASSWD_CANT_CHANGE
  $user.SetInfo()

  Write-Host "User  account has been set with Password Never Expried" -ForegroundColor "Green" -BackgroundColor "Black"

  Write-Host "User  account has been set with User Can not change Password" -ForegroundColor "yellow" -BackgroundColor "Black"
  }

  }
  catch{
  Write-Host "Unable to reach server $computerName" -ForegroundColor "Red" -BackgroundColor "Black"

  }
}
}

Power Shell Script to create Local User Account & Set Password and add into Local Administrator Group


The below script will perform the following :


  1.  Create Local user on each Server
  2.  Set Password for newly created account
  3.  Add newly created Admin account to Local Administrator group 

Csv file format is as below:



#-----------------------------------------------------------------------------------------------------#
#Script Title : Create local user on each server and add local user account onto Administrator group
#changes in Script : change csv file path in first line of script
#------------------------------------------------------------------------------------------------------#

$list =  Import-CSV "C:\LocalAdmins\testUsers.csv" #change path here..
foreach($Servers in $list) {

try{

$computer = $Servers.ServerName
$user = $Servers.LocalAdminAccount
$pass = $Servers.Password

$objOu = [ADSI]"WinNT://$computer"
$objUser = $objOU.Create("User", $user)
$objUser.setpassword($pass)
$objUser.SetInfo()
$objUser.description = "Local Admin Account"
$objUser.SetInfo()

Write-Host " Admin Account created Successfully  for $computer with password as $pass" -ForegroundColor "Green" -BackgroundColor "Black"

$AdminGroup = [ADSI]"WinNT://$computer/Administrators,group"
$AdminGroup.Add("WinNT://$computer/$computer/$user,user")

Write-Host "Account $user added successfully into local adminstrator group on Server $computer"  -ForegroundColor "Yellow" -BackgroundColor "Black"
}

Catch
{
Write-Host " Unable to reach $computer Server" -ForegroundColor "yellow" -BackgroundColor "red"
}

}