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

}

Friday, 11 April 2014

Email functionality with Power Shell

There are multiple methods to send an emails using power shell script, below are the few methods i used to follow.......

Use below script to send test email from Power Shell...


$To = "SPAdmin@org.com" #change your email id to send an email
$fromemail = "SPReports@org.com" #Add your from email address
$server = "smtp.org.com"  #change your SMTP address
$TodayDate = Get-Date

send-mailmessage -from $fromemail -to $users -subject "Test Reports" -body "Test Report for $TodayDate" -priority Normal -smtpServer $server


Permissions for Power Shell



Getting Started SharePoint 2013 Management Shell

Click Start, click Microsoft SharePoint 2013 Products, and then click SharePoint 2013 Management Shell

Permissions

Before you can use the Add-SPShellAdmin cmdlet to grant permissions for users to run SharePoint 2013 cmdlets, verify that you meet all of the following minimum requirements:


  •  You must have membership in the securityadmin fixed server role on the SQL Server instance
  • You must have membership in the db_owner fixed database role on all databases that are to be updated.
  • You must be a member of the Administrators group on the server on which you are running the Windows PowerShell cmdlet.
  •   If you do not have membership in the SharePoint_Shell_Access role or WSS_Admin_WPG local group, use the Add-SPShellAdmin cmdlet to add the WSS_Admin_WPG group in all front-end web servers in the SharePoint farm and the SharePoint_Shell_Access role. If the SQL Server database does not have a SharePoint_Shell_Access role, the role is automatically created when you run the Add-SPShellAdmin cmdlet. After you run the Add-SPShellAdmin cmdlet, users can run SharePoint Windows PowerShell cmdlets in a multiple-server farm environment.
  •  When you install SharePoint 2013, the user account from which you run the installation is granted the appropriate permissions to run Windows PowerShell cmdlets. If any users have not been added to run a Windows PowerShell cmdlet, you can use the Add-SPShellAdmin cmdlet to add them.
  •  You must run the Add-SPShellAdmin cmdlet for all databases to which you want to grant access. If no database is specified, the farm configuration database is used. If you do specify a database, the farm content database will be included in addition to the farm configuration database that you specify.
  • To see a list of all of the SPShellAdmin cmdlets, from a Windows PowerShell command prompt, type Get-Command -Noun SPShellAdmin or Get-SPShellAdmin
Reference: http://technet.microsoft.com/en-us/library/ee806878%28v=office.15%29.aspx 

Configure ISE in SharePoint Server



The Windows PowerShell Integrated Scripting Environment (ISE) is a host application for Windows PowerShell. In Windows PowerShell ISE,

  • You can run commands and write, test, and debug scripts in a single Windows-based graphic user interface with multiline editing, tab completion, syntax coloring, selective execution, context-sensitive help, and support for right-to-left languages.
  •  You can use menu items and keyboard shortcuts to perform many of the same tasks that you would perform in the Windows PowerShell console.  For example, when you debug a script in the Windows PowerShell ISE, to set a line breakpoint in a script, right-click the line of code, and then click Toggle Breakpoint. 
  •  PowerShell is a great companion for SharePoint 2010 and 2013. As a developer or Administrator you can go through the Integrated Scripting Environment (ISE) to write scripting in best way. The only problem is, the SharePoint snap-in doesn't load automatically when you start PowerShell ISE.

Below are the steps to get ISE installed and make sure the SharePoint snap-in always loads.

1. Open Server Manager
2. Click the Features node
3. Click the Add Features link
4. Check the box for "Windows PowerShell Integrated Scripting Environment".
5. Click Next, then Install
6. Wait until installation is complete
7. Open Powershell ISE from Programs>Accessories>PowerShell folder
8. Run the following code from the immediate window in ISE to create a new profile for all users
 if (!(test-path $profile.AllUsersAllHosts))

       {new-item -type file -path $profile.AllUsersAllHosts-force}

9. Run the following code to edit the new profile
psEdit $profile.AllUsersAllHosts
10. When profile1.ps1 opens, add the following code to attach the SharePoint snap-in every time PowerShell is run.
 If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )

{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }
 11. Save profile.ps1 and close PowerShell ISE.
12. Start PowerShell ISE again and type the following command to verify that the SharePoint snap-in loaded. You should see SharePoint-specific command listed.

Get-Command Get-SP*


Reference: http://technet.microsoft.com/en-us/library