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

}