Privacy Info

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

Tuesday, October 18, 2022

PowerShell Script - Recycle Application Pool



We sometimes require to recycle the application pool of the websites, to clear cache content or to restart website. Below script comes in handy to do this task. We need to specify user credentials, server name and application pool name. PowerShell script will do the recycling task.

Script

$Username="Username"
$Password="Password"

function RecycleAppPool($Server,$AppPool)
{           
        Write-Host "ServerName:$Server ApplicationPool:$AppPool"

        # Credentials    				
	$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
				
	# Checking App Pool by name                
        $AppItem = (Invoke-Command $Server -ScriptBlock{param($AppPool) Get-WebAppPoolState | Where-Object {$_.ItemXPath -match "$using:AppPool"} } -ArgumentList $AppPool -Credential $Cred)[0] 
                                 
        If($AppItem -ne $Null)
        {
            try
            {
                # Recycle App Pool
                $Recycle = Invoke-Command $Server -ScriptBlock{param($AppPool)Restart-WebAppPool -name "$using:AppPool"} -ArgumentList $AppPool -Credential $Cred
                Write-Host "Recycle Successful"
            }
            catch
            {
                Write-Host "Error: " -NoNewline -ForegroundColor red
                Write-Host $_.Exception.Message
                Contiune
            }
	}
		    							           
}


RecycleAppPool  "ServerName" "AppPoolName"


You can modify script based on your requirement

Sunday, October 16, 2022

PowerShell Script - CPU and Storage Details


Manually checking Storage consumption and CPU usage multiple time is very repetitive and boring task. Also if you want to check same details on remote servers then it will again consume lot of time. PowerShell help us to automate this process. We need to specify credentials, name of the server in the script and it will provide storage consumption and CPU utilization details.

Script 

PowerShell Script

$MyDir = Split-Path -Parent $MyInvocation.MyCommand.Path
[xml]$ConfigFile = Get-Content "$MyDir\Settings.xml"


function GetCPUStorageDetails($serverName)
{
    $Username = $ConfigFile.Settings.CredentialsSettings.Username;
    $Password = ConvertTo-SecureString -String $ConfigFile.Settings.CredentialsSettings.Password -AsPlainText -Force   		
    $Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password

     $cpuUsage = Get-WmiObject Win32_Processor -ComputerName $serverName -Credential $Cred
     Write-Host ({0}% -f $cpuUsage.LoadPercentage )

     $storageDetails = Get-WmiObject -Class win32_logicaldisk -ComputerName $serverName -Credential $Cred

      foreach ($storageDetail in $storageDetails) {
        #Device ID | FreeSpace
        Write-Host -NoNewline ({0} {1}GB   -f  $storageDetail.DeviceId,([math]::Round($storageDetail.FreeSpace/1GB,2)) )   
     }

     Write-Host ""
}

GetCPUStorageDetails("ServerName")


Settings.xml

<?xml version="1.0"?>
<Settings>
	<CredentialsSettings>
		<Username>Username</Username>
		<Password>Password</Password>
	</CredentialsSettings>
</Settings>


Hope you find this information useful.




Tuesday, October 11, 2022

PowerShell Script - Website Certificate Information


It is difficult to manage the certificates for websites. When websites hosted on server are large in number task become more tedious and complicated. We have also received similar task for collecting  details of certificates for each website on remote server. In our case websites hosted on server were large in number and manually collecting the details for the certificates was time consuming task. So we came up with below PowerShell script which will help us to provide the details.

Script  

Import-Module -Name WebAdministration


Get-ChildItem -Path IIS:SSLBindings | ForEach-Object -Process `
{
    if ($_.Sites)
    {
        $certificate = Get-ChildItem -Path CERT:LocalMachine/My | Where-Object -Property Thumbprint -EQ -Value $_.Thumbprint       

        [PsCustomObject]@{
            Sites                        = $_.Sites.Value
            CertificateFriendlyName      = $certificate.FriendlyName                     
            CertificateIssuer            = $certificate.Issuer
            ExpiryDate                   = [string]$certificate.NotAfter            
        }
    }
} | ConvertTo-Json  | Out-File -Width 4096 C:\ServerCertDetails.json -Append 

Above script will provide details of fields for each website hosted on server.

  • Website Name
  • Certificate Name
  • Certificate Issuer
  • Certificate Expiry Date
You can customize display details as per your requirement. It will convert the details into json file and save it in specified location.


ServerCertDetails.json


Hope you find this information useful.
  

Saturday, May 7, 2022

PowerShell Service Monitor



We have previously faced issue monitoring our windows service and websites. Whenever the service is down, functionality which is dependent on the service stops working. Continuously monitoring the services is difficult and not feasible. To solve this problem we came up with PowerShell script which will monitor the service, alerts when service is down and automatically restart the service. This blog post will explain you how you can create similar Service Monitor application which will make your work easier.

Create folder with below folder structure:

Logs Folder

It will have logs files after execution of PowerShell script

Settings.xml File

It will contain the configuration details of the PowerShell script 

ServiceMonitor.ps1 File

It will contain actual code for monitoring service


Code Snippets

Settings.xml

<?xml version="1.0"?>
<Settings>
	<SolrSettings>
		<SolrURL>https://localhost:8984/solr/#/</SolrURL>
		<SolrServiceName>Solr-Service</SolrServiceName>		
	</SolrSettings>				
	<EmailSettings>
		<ToEmail>"noreply@gmail.com"</ToEmail>
		<FromEmail>ServiceMonitor@gmail.com</FromEmail>
		<EmailSubject>Service is not working</EmailSubject>
		<SMTPServer>smpt.gmail.com</SMTPServer>
		<EmailPort>25</EmailPort>
	</EmailSettings>
	<LogSettings>
		<LogFileFolder>C:\User\Projects\Restart Service\Logs\</LogFileFolder>
	</LogSettings>	
</Settings>


ServiceMonitor.ps1

#Import settings from config file
$MyDir = Split-Path -Parent $MyInvocation.MyCommand.Path
[xml]$ConfigFile = Get-Content "$MyDir\Settings.xml"

#Email Configuration 
[string[]]$ToEmail = $ConfigFile.Settings.EmailSettings.ToEmail
$FromEmail = $ConfigFile.Settings.EmailSettings.FromEmail
$EmailSubject = $ConfigFile.Settings.EmailSettings.EmailSubject
$EmailSmtpServer = $ConfigFile.Settings.EmailSettings.SMTPServer
$EmailPort = $ConfigFile.Settings.EmailSettings.EmailPort
$ErrorEmailMessage = ""
$ExceptionErrorEmailMessage=""

#LogFile Details
$TodayDate = Get-Date -format "dd-MM-yyyy"
$LogFileFolder = $ConfigFile.Settings.LogSettings.LogFileFolder
$LogFileName = $LogFileFolder+"ServiceMonitor-"+$TodayDate+".txt"
$LogMessage = ""  

#Solr Details
$SolrURL = $ConfigFile.Settings.SolrSettings.SolrURL
$SolrServiceName = $ConfigFile.Settings.SolrSettings.SolrServiceName

try{    
    $LogMessage +="`nStart - $((Get-Date).ToString())"

    $HTTP_Request = [System.Net.WebRequest]::Create($SolrURL)

    $HTTP_Response = $HTTP_Request.GetResponse()

    $HTTP_Status = [int]$HTTP_Response.StatusCode
    
    if($HTTP_Status -eq 200) {
        Write-Host "Solr Site is working"
        $LogMessage +="Solr Site is working`n"
    }
    else
    {
	throw "Solr website Error Occured" 								 			
    }  

}
catch{
	Write-host "Solr Site is down Error Occured:  $_"
	$LogMessage +="Solr Site is down Error Occured: $_`n"    	       
                
        #Restart Service       
        Invoke-Command -ScriptBlock { Restart-Service -Name  $args }  -ArgumentList $SolrServiceName
        Write-Host "Service Restarted"
        $LogMessage +="Service Restarted`n"
               
        
        #Send Email
        $ErrorEmailMessage = "URL: "+$solrURL+"`nError Details:"+$_+"`nSolr site was down`nService Restared"
        Send-MailMessage -To $ToEmail -From $FromEmail  -Subject $EmailSubject  -Body $ErrorEmailMessage  -SmtpServer $EmailSmtpServer  -Port $EmailPort			       
        Write-Host "Email Sent"
        $LogMessage +="Email Sent`n"						 		
		       	
}
finally{
    # Closing Objects
    If ($HTTP_Response -eq $null) { } 
    Else { $HTTP_Response.Close() }
}  
     
$LogMessage +="End - $((Get-Date).ToString())"
Add-Content $LogFileName $LogMessage


Sample Log File





You can also deploy code on Task Scheduler and monitor your service continuously.

I hope you will find the blog useful 😃


Sitecore PowerShell Script - Remove item from Workflow

We came across scenario where we need to remove multiple items from workflow. If items would be less then there would not be any issue but i...