Wednesday, July 13, 2022

Virtual machine re-registration, disconnected virtual machine/ read-only VM virtual machine- VMWARE - PowerShell

 Import-Module VMware.VimAutomation.Core

#Run this by opening VMware PowerCLI tool and connect using connect-VIserver

$pscrd = Get-Credential

Connect-VIServer -Server 10.106.202.151 -Credential $pscrd

Write-Host "Current script directory is $ScriptDir"


$CurrDate = Get-Date -Format "yyyyMMdd_HHmmss"

$SubCurrDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"


$agree= "N"

Write-Host "Before you run the code. Makesure, to have required back-up of VMs for any recovery" -BackgroundColor DarkRed

$agree = Read-Host "You want to proceed: Y/N"

If( $agree -eq "Y" -or $agree -eq "y" )

{

#Flag to validate the ZERO Byte VMs

$flag=0

# This will get us the complete list of VMs in the inventory

#$vms = Get-VM

$vms = Get-VM #-Name TESTVM_KDC_03

$status_coll = @()

$vm_coll = @()

# Loop-in throught the Vm with various validation and checks

foreach($vm in $vms)

{


$regvm = "" | Select-Object VMName,PowerState,UsedSpaceGB,vmPathName,Remarks

$vm_state = "" | Select-Object VMName,PowerState,UsedSpaceGB,vmPathName,Remarks

  If($vm.UsedSpaceGB -eq 0 -And $vm.PowerState -eq "PoweredOn")

    {

         # If a VM is found to be a Zero byte space

         # execute the registration process

         $flag=1

         $vmname = $vm.Name

         #Write-Host "This is a Zero Byte VM and is in PowerON state: $vm.Name"

         #code to re-register the VM from the Inventory

         $resourcePool = Get-ResourcePool -VM $vm

         $vmPathName = $vm.ExtensionData.Config.Files.VmPathName

        #VM resource details

        $vm_state.VMName = $vmname

         $vm_pstate = $vm.PowerState

         $vm_state.PowerState = $vm_pstate

         $vm_usedspaceGB = $vm.UsedSpaceGB

         $vm_state.UsedSpaceGB = $vm_usedspaceGB

        $vm_state.vmPathName = $vmPathName

         $vm_state.Remarks = "DataCollection"

         get-vm $vmname | Stop-VM -confirm:$false

         $vm_stp_status = get-vm $vmname

         #Validate VM status condition block to remove from Inventory and re-registration

         If($vm_stp_status.PowerState -eq "PoweredOff") 

         {

          

             # Knock off the VMs from the Inventory without deleting the vmx file from the pool

           # Which is made as false and never make it true or remove the below Switch else Data loss will happen

            #Cautious note touch the below line only when you are aware what you are doing.

             Remove-VM -VM $vm -DeletePermanently:$false -Confirm:$false

             New-VM -VMFilePath $vmPathName -ResourcePool $resourcePool -Confirm:$false

            $vm_new_status = get-vm $vmname

             start-vm $vm_new_status -confirm:$false

                  $vm_strt_status = get-vm $vmname

                  #If the start of VM is successfull on the return

                    If($vm_strt_status.PowerState -eq "PoweredOn" -and $vm_strt_status.UsedSpaceGB -ne 0)

                      {

                       # Collect the server saying sucessfull registration

                       $regvm.VMName = $vmname

                       $vm_strt_pstate = $vm_strt_status.PowerState

                       $regvm.PowerState = $vm_strt_pstate

                       $vm_strt_usedspaceGB = $vm_strt_status.UsedSpaceGB

                       $regvm.UsedSpaceGB = $vm_strt_usedspaceGB

                       $regvm.vmPathName = $vmPathName

                       $regvm.Remarks = "Registered successfully"

                      }

                    Else

                      {

                       $regvm.VMName = $vmname

                       $vm_strt_pstate = $vm_strt_status.PowerState

                       $regvm.PowerState = $vm_strt_pstate

                       $vm_strt_usedspaceGB = $vm_strt_status.UsedSpaceGB

                       $regvm.UsedSpaceGB = $vm_strt_usedspaceGB

                       $regvm.vmPathName = $vmPathName

                       $regvm.Remarks = "Couldn't register, Please check Manually"

                      }            

           }

           Else

           {

            #Couldn't stop VM for re-registration process

            $regvm.VMName = $vmname

            $vm_stp_pstate = $vm_stp_status.PowerState

            $regvm.PowerState = $vm_stp_pstate

            $vm_strt_usedspaceGB =  $vm_stp_status.UsedSpaceGB

            $regvm.UsedSpaceGB = $vm_strt_usedspaceGB

            $regvm.vmPathName = $vmPathName

            $regvm.Remarks = "Couldn't stop VM for re-registration process"

           }

         }

         

        $status_coll = $status_coll +  $regvm

        $vm_coll = $vm_coll + $vm_state

        

}

}

Write-Host "Vmware Registration Status" -BackgroundColor DarkCyan

$status_coll

Write-Host "Vmware Info details" -BackgroundColor DarkMagenta

$vm_coll

$reg_path = $ScriptDir + "\InventoryRegistration.csv"

$status_coll | Export-Csv -Path $reg_path -NoTypeInformation

$vmstatuspath = $ScriptDir + "\Vms_status.csv"

$vm_coll | Export-Csv -Path $vmstatuspath -NoTypeInformation

If( $flag -eq 0)

{

Write-Host "No VMs with Zero Byte found with PoweredON state"

}


Progressive Log file parsing for Windows servers- Powershell

 Clear-Host

######################################################

########File Configurations or Initialization#########

######################################################


#Update the path of the Log file. Not including the file name

#$logFilePath = "C:\Users\bobr\Desktop\LogFileParsing"

$logFilePath = "E:\APP_SERVERS\glassfish-4.1\glassfish4\glassfish\domains\walgreenmonet\logs"

#\\server1\glassfish-4.1\glassfish4\glassfish\domains\walgreenmonet\logs


#Update the Log File name with extension like server.log

$logFileName = "server.log"

$ParserFile = $logFilePath + "\" + $logFileName



$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path


#Create a pattern.txt file in the location where you have placed the script and

#add all the required unique pattern to line-by-line. It does simple match.

$patternFile = $ScriptDir + "\" + "pattern.txt"


# This file will be created automatically in the initial run and

# never modify this file content which is a numerical value to track file 

# line last read

$counterFile = $ScriptDir + "\" + "counterFile.log"


#File which you want to parse once it get archieved from the original source

#make sure you have a right pattern in place as it identified lastWriteTime to pick

$archivedFileNamePattern = "server.log_*"


# SMTP Relay server name

$smtp = "smtp.domain.com"


# E-mail to be sent to when the pattern matches with subject and body details

$from = "xyz@domain.com"

$to = "xyz@domain.com","abc@domain.com"

$subject = "Test Ignore: Walgreen: database connectivity issue server.log"

$body = "<B>This file contains the match found in accordance with pattern.txt file</B><BR>"


######################################################

###############End of Initialization###################

######################################################



$bodyContent = @()

$bodyContent = $bodyContent + $body 

$pattern = Get-Content $patternFile


#$pattern = @("SQLException","SQL")


If ( Test-Path $counterFile )

{

$lastLine = Get-Content -Path $counterFile

}

else

{

New-Item -Path $logFilePath -Name "counterFile.log" -ItemType File

New-Item -Path $logFilePath -Name "pattern.txt" -ItemType File

$count = Get-content $ParserFile | Measure-Object

$lastLine = $count.count

$lastLine|Out-File $counterFile

}

$newCount = Get-content $ParserFile | Measure-Object

$newLine = $newCount.Count

If ( $newLine -gt $lastLine )

{

$diff_Line = $newLine - $lastLine

#Write-Host "FromLineNum:$lastLine to ToLineNum:$newLine"

$matchedContent = Get-Content $ParserFile -Tail $diff_Line | Select-String -Pattern $pattern #-SimpleMatch

#Write-Host $matchedContent

$bodyContent = $bodyContent + $matchedContent

    $bodyAsString = $bodyContent | & {$ofs='<BR>';"$input"}

If ( $matchedContent )

{

#send e-mail

Send-MailMessage -From $from -To $to -Subject $subject -Body $bodyAsString -BodyAsHtml -SmtpServer $smtp

}

$lastLine = $newLine

$lastLine|Out-File $counterFile

}

ElseIF ( $newLine -lt $lastLine ) #check if a new file has been created and archiving older one with timestamp

{

#Read from the newly created file

$diff_Line = -1

#Write-Host "FromLineNum:0 to ToLineNum:$newLine"

$matchedContent = Get-Content $ParserFile -Tail $diff_Line | Select-String -Pattern $pattern #-SimpleMatch

#Write-Host $matchedContent

$bodyContent = $bodyContent + $matchedContent

# Get archived file lastline before overriding with newfile lastline

$archivedFileLastLine = $lastLine

$lastLine = $newLine

$lastLine|Out-File $counterFile

#Read the archived file to make sure we have read everything till the end of the file

#Get the archieved file name from recently modified date with a filename_*.log

$recentArchiveFileName = (Get-ChildItem -Path $logFilePath -Filter $archivedFileNamePattern |Sort-Object LastWriteTime | Select-Object -Last 1).FullName

$archievednewCount = Get-content $recentArchiveFileName | Measure-Object

$archievedNewLine = $archievednewCount.Count

if ( $archievedNewLine -gt $archivedFileLastLine )

{

$diff_Line = $archievedNewLine - $archivedFileLastLine

Write-Host "FromLineNum:$archivedFileLastLine to ToLineNum:$archievedNewLine"

$archievedMatchedContent = Get-Content $recentArchiveFileName -Tail $diff_Line | Select-String -Pattern $pattern #-SimpleMatch

#Write-Host $archievedMatchedContent

$bodyContent = $bodyContent + $archievedMatchedContent

$bodyAsString = $bodyContent | & {$ofs='<BR>';"$input"}

if ( $archievedMatchedContent )

{

#send e-mail

Send-MailMessage -From $from -To $to -Subject $subject -Body $bodyAsString -BodyAsHtml -SmtpServer $smtp

}

}

}