vmwarecode.psm1
function Set-VMHostPassword { <# .NOTES =========================================================================== Author: Ankush Sethi Blog: www.vmwarecode.com Description: ESXi root password reset =========================================================================== .SYNOPSIS Recover the ESXI root/other user's Password .DESCRIPTION Function will recover the esxi root password using PowerCli .PARAMETER VMHost Enter the esxi Hotsname for which we need to recover the password. .PARAMETER UserName Enter the username of esxi host. .PARAMETER Password Enter the new password for esxi host. .EXAMPLE example 1>Set-VMHostPassword -VMHost homelab.vmwarecode.com -UserName root -Password VMware123! ` example 2>Get-VMHost Homelab.vmwarecode.com|Set-VMHostPassword -UserName root -Password VMware123! #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [VMware.VimAutomation.ViCore.Impl.V1.VIObjectImpl]$VMHost, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String[]]$UserName, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]$Password ) Process{ try { $validation1=Get-VMHost $VMHost -ErrorAction Stop } catch { Write-Error -Message "Please check the host is part of connected vCenter or not and try again" -ErrorAction Stop } If(($validation1.ConnectionState -eq "Connected") -or ( $validation1.ConnectionState -eq "Maintenance")) { $esxcli=Get-EsxCli -VMHost $VMHost -V2 $IDList=$esxcli.system.account.list.invoke().UserID If(($IDList -contains $UserName) -ne $true){Write-Error -Message "Entered Username does not exist in esxi userid list" -ErrorAction stop} } else { Write-Error -Message "ESXI is not connected or maintenance mode to perform the action" -ErrorAction Stop } $argu=$esxcli.system.account.set.CreateArgs() $argu.id=$UserName $argu.password=$Password $argu.passwordconfirmation=$Password $output=$esxcli.system.account.set.invoke($argu) } end{ If($output -eq $true) { Get-VIEvent -Entity (Get-VMHost $VMHost) -MaxSamples 1|?{$_.fullformattedmessage -match "Password"}|select UserLogin,Createdtime,Username,Fullformattedmessage|ft -AutoSize $hostd=Get-Log -Key hostd -VMHost (Get-VMHost $VMHost) $hostd.Entries|Select-String "Password was changed for account" |select -Last 1 } } } function Get-DatastoreFolderSize { <# .NOTES =========================================================================== Created by: Ankush Sethi Blog: www.vmwarecode.com =========================================================================== .SYNOPSIS Provide the VMFolder Size Utilization .DESCRIPTION Function will provide the vmfolder size in datastore using PowerCli .PARAMETER Datastore Enter the Datastore name for which you want to check the utilization .PARAMETER ExportToCSV If you want to genetate the report .EXAMPLE Get-DatastoreFolderSize -Datastore (Get-Datastore DSname) Get-Datastore SA-shared-01-ms-remote|Get-DatastoreFolderSize Get-Datastore SA-shared-01-ms-remote|Get-DatastoreFolderSize -ExportToCSV:$true #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [VMware.VimAutomation.ViCore.Impl.V1.DatastoreManagement.DatastoreImpl] $Datastore, [switch]$ExportToCSV ) Begin { $DSobject=New-Object VMware.Vim.HostDatastoreBrowserSearchSpec $DSfileobject=New-Object VMware.Vim.FileQueryFlags $DSfileobject.Modification=$true $DSfileobject.FileSize=$true $DSfileobject.FileOwner=$true $DSfileobject.FileType=$true $DSobject.Details=$DSfileobject } Process { Try { foreach($as in $Datastore) { $ds=Get-Datastore $as -ErrorAction Stop } } catch { Write-Error -Message "Entered datastore is not found" -ErrorAction Stop } foreach($store in $Datastore) { $dspath="["+$store.name+"]" $dsview=Get-View -id $store.ExtensionData.browser $output+=@($dsview.SearchDatastoreSubFolders($dspath,$DSobject)|select Folderpath, @{N="FolderSize-MB";E={[math]::Round((($_.file|measure -Property Filesize -sum).sum)/1MB,2)}}, @{N="FolderSpace-GB";E={[math]::Round((($_.file|measure -Property FileSize -Sum).sum)/1GB,2)}}, @{N="TotalFiles";E={($_.file|measure -Property FileSize).count}}, @{N="Last-Modified";E={($_.File|Sort-Object -Property Modification -Descending|select -First 1).modification}} ) } } End { Write-Host "------------------------------------------------------------------------------------------------------------------------------------------------" $output|FT -AutoSize|Out-Default Write-Host "------------------------------------------------------------------------------------------------------------------------------------------------" If($ExportToCSV -eq $true) { $path=Get-Location $name="\VMwareCode_VMfolderReport"+" "+($global:DefaultVIServer).name.Split('.')[0]+".csv" $Reportname= $path.path+$name $output|Export-Csv -NoTypeInformation -Path $Reportname } } } function Renew-VMHostCertificate { <# .NOTES =========================================================================== Created by: Ankush Sethi Blog: www.vmwarecode.com =========================================================================== .SYNOPSIS Renew ESXi VMCA certificate .DESCRIPTION Function will Renew the Certificate using PowerCli .PARAMETER VMHost Enter the esxi Hotsname for which we need to renew the certificate .EXAMPLE Get-VMHost ESXiName|Renew-VMHostCertificate -RunAsync Renew-VMHostCertificate -VMHost (Get-VMHost "ESXi") -RunAsync:$true Get-Cluster "ClusterName"|Get-VMHost|Renew-VMHostCertificate Get-VMHost ESXiName|Renew-VMHostCertificate Renew-VMHostCertificate -VMHost (Get-VMHost "ESXi") #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl]$VMHost, [switch]$RunAsync ) begin { If(($global:DefaultVIServers).Count -gt 1) { Write-Error -Message "Currently you are connected to more than 1 vCenter, Please disconnect and connect to Respective vCenter" -ErrorAction Stop } elseIf(($global:DefaultVIServers).Count -lt 1) { Write-Error -Message "You are not connected to vCenter to perform the task" -ErrorAction Stop } $ServiceInstance=Get-View ServiceInstance $CertMgrID=$ServiceInstance.content.CertificateManager $CertMgr=Get-View -Id $CertMgrID } Process { try { $validation=Get-VMHost $VMHost -ErrorAction Stop } catch { Write-Error -Message "Entered esxi host does not exist in $global:DefaultVIServer" } If(($validation.ConnectionState -eq "Connected") -or ($validation.ConnectionState -eq "Maintenance")) { If($RunAsync -eq $true){ foreach($script:ESXi in $VMHost){$script:task=$CertMgr.CertMgrRefreshCertificates_Task($script:ESXi.extensiondata.moref)} } else { foreach($script:ESXi in $VMHost){$script:task=$CertMgr.CertMgrRefreshCertificates($script:ESXi.extensiondata.moref)} } } else{Write-error -Message "Action cannot be performed on current state of ESXi" -ErrorAction Stop} } End { Get-Task|?{$_.Name -match "Certificate"}|ft -AutoSize } } function Get-VMDiskStoragePolicy { <# .NOTES =========================================================================== Author: Ankush Sethi Blog: www.vmwarecode.com Description: VM Disk Storage Policy =========================================================================== .SYNOPSIS Provide VM Disk's storage Policy information .DESCRIPTION Function will provide the disk policy information for one or More VM using PowerCli .PARAMETER VM Enter the VM for which we need to get details of storage policy. .PARAMETER ExportToCSV Function can generate the CSV report. .EXAMPLE example 1>Get-VM VMName|Get-VMDiskStoragePolicy ` example 2>Get-VM cexp*|Get-VMDiskStoragePolicy -ExportToCSV:$true example 3>Get-VMDiskStoragePolicy -VM (Get-VM vmname) example 4>Get-VMDiskStoragePolicy -VM (Get-VM vmname) -ExportToCSV:$true #> #> #> param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] # [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl]$VM [VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$VM, [switch]$ExportToCSV ) begin{ If (($global:DefaultVIServers).Count -gt 1) { Write-Error -Message "Currently you are connected to more than 1 vCenter, Please disconnect and connect to Respective vCenter" -ErrorAction Stop } elseIf(($global:DefaultVIServers).Count -lt 1) { Write-Error -Message "You are not connected to vCenter to perform the task" -ErrorAction Stop } } Process { try { $VMS = Get-VM $VM -ErrorAction Stop } catch { Write-Error -Message "Entered VM does not exist in $global:DefaultVIServer" } foreach($script:VM in $VMS){ $output += @(Get-VM $script:VM|Get-HardDisk |Get-SpbmEntityConfiguration|Select-Object @{n="VM Name";E={(Get-View -id ($_.id).split('/')[0]).name}}, @{n="DiskName";E={$_.entity}},@{n="DiskType";E={(Get-HardDisk -VM (Get-VM -Id ($_.id).split('/')[0]) -Name $_.entity).StorageFormat}},StoragePolicy, @{n="CapacityGB";E={(Get-HardDisk -VM (Get-VM -Id ($_.id).split('/')[0]) -Name $_.entity).CapacityGB}} ) } } End { Write-Host "----------------------------------------------------------------------------------------------------------------------------------------" $output|Format-Table -AutoSize|Out-Default Write-Host "----------------------------------------------------------------------------------------------------------------------------------------" If($ExportToCSV -eq $true) { $path=Get-Location $name="\VMwareCode_VMStoragePolicy_Report"+" "+($global:DefaultVIServer).name.Split('.')[0]+".csv" $Reportname= $path.path+$name $output|Export-Csv -NoTypeInformation -Path $Reportname } } } Function Set-VMHostNetworkCard { <# .NOTES =========================================================================== Created by: Ankush Sethi Blog: www.vmwarecode.com =========================================================================== .SYNOPSIS To enable/disable the esxi network card .DESCRIPTION Function will provide the funtionality to disable or enable the network card etc. .PARAMETER VMhost Enter the ESXi name for which you want to perform the action. .PARAMETER vmnic Use this parameter provide the network card of esxi ,If you press Tab values will come automatically. .PARAMETER Action Use this parameter to provide the enable disable action .EXAMPLE example 1>Get-vmhost esxiname|Set-vmhostnetworkcard -vmnic vmnic1 -Action Disable example 2>Get-vmhost esxiname|Set-vmhostnetworkcard -vmnic vmnic1 -Action Enable #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$VMhost, [Parameter(Mandatory=$true)] [ValidateSet("vmnic0","vmnic1","vmnic2","vmnic3","vmnic4","vmnic5","vmnic6","vmnic7")] $vmnic, [Parameter(Mandatory=$true)][ValidateSet("Enable","Disable")]$Action ) process { Try{$esx=Get-VMHost -Name $VMhost -ErrorAction Stop} catch { Write-Error "Please enter the correct name of ESXi" } If(($esx.ConnectionState -match "Disconnected") -or ($esx.ConnectionState -match "NotResponding")) { Write-Error "ESXi host is not in connected or maintenance mode state to perform the action." } $esxcli=Get-EsxCli -VMHost $esx -V2 if($Action -match "Enable") { $arg=$esxcli.network.nic.up.CreateArgs() $arg.nicname=$vmnic $output=$Esxcli.network.nic.up.invoke($arg) If($output -eq $true){$esxcli.network.nic.list.invoke()|?{$_.name -match $vmnic}|ft -AutoSize} } elseIf($Action -match "Disable") { $arg1=$esxcli.network.nic.down.CreateArgs() $arg1.nicname=$vmnic $output=$Esxcli.network.nic.down.invoke($arg1) If($output){$esxcli.network.nic.list.invoke()|?{$_.name -match $vmnic}|ft -AutoSize} } } } function Get-VIObjectTask { <# .NOTES =========================================================================== Created by: Ankush Sethi Blog: www.vmwarecode.com =========================================================================== .SYNOPSIS Check the Task of any Object in vSphere .DESCRIPTION Function will provide the task history of any object like vm,esxi,datastore,distributed switch etc. .PARAMETER Entity Enter the Entity name for which you want to check the task details. .PARAMETER Recursion Use this parameter if you want to check the child object also like vm is child object of esxi. .PARAMETER TaskName Use this parameter to filter the task just by specifying the ketword .Parameter Initiator Use this parameter to filter the task just by giving the Username .Parameter ExportToCsv Use this parameter to generate the csv report of task. .EXAMPLE example 1>Get-vmhost esxiname|get-viobjecttask example 2>Get-vmhost esxiname|get-viobjecttask -recursion:$true example 3>Get-vmhost esxiname|get-viobjecttask -recursion:$true -taskname "clone" example 4>Get-vmhost esxiname|get-viobjecttask -recursion:$true -Initiator "admin" example 5>Get-vmhost esxiname|get-viobjecttask -recursion:$true -TaskName "clone" -Initiator "admin" example 6>Get-vmhost esxiname|get-viobjecttask -recursion:$true -TaskName "clone" -Initiator "admin" -ExportToCSV:$true #> param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [VMware.VimAutomation.ViCore.Impl.V1.Inventory.InventoryItemImpl]$Entity, [Switch]$Recursion, [int]$MaxSample=[int]1000, [ValidateNotNullOrEmpty()][string]$TaskName, [ValidateNotNullOrEmpty()][string]$Initiator, [switch]$ExportToCsv ) Process{ try{ $Inv=Get-Inventory -Name $Entity -ErrorAction Stop } catch { Write-Error -Message "Please enter the correct name of Object" -ErrorAction Stop } $TaskObject=New-Object VMware.Vim.TaskFilterSpec $Entityobject=New-Object VMware.Vim.TaskFilterSpecByEntity $TaskObject.Entity=$Entityobject $TaskObject.Entity.Entity=$Entity.ExtensionData.moref If($Recursion -eq $true){$TaskObject.Entity.Recursion=[VMware.Vim.TaskFilterSpecRecursionOption]::all} $TskMgr=Get-View TaskManager $taskcollected= $TskMgr.CreateCollectorForTasks($TaskObject) $TaskView=Get-View $taskcollected $taskout=$TaskView.ReadNextTasks($MaxSample) If(($TaskName -ne $null) -and ($Initiator -eq $null)) { $output=$taskout|?{$_.name -match $TaskName} } elseif($TaskName -eq $null -and $Initiator -ne $null) { $output=$taskout|?{$_.reason.username} } elseif(($TaskName -eq $null) -and ($Initiator -eq $null)) { $output=$taskout } elseif(($TaskName -ne $null) -and ($Initiator -ne $null)) { $output=$taskout|?{$_.name -match $TaskName -and $_.reason.username -match $Initiator} } } End{ $Report=$output|select Name,DescriptionId,EntityName, @{N="QueueTime";E={[string]($_.StartTime-$_.QueueTime).Milliseconds+"ms"}}, StartTime,CompleteTime, @{N="ExecutionTime";E={[string]($_.CompleteTime-$_.StartTime).Milliseconds+"ms"}}, @{N="Initiator";E={$_.reason.username}}, @{N="Status";E={If($_.state -match "error"){[string]$_.Error.LocalizedMessage}else{$_.state}}} $Report|ft -AutoSize If($ExportToCsv) { $path=Get-Location $name="\VMwareCode_TaskReport"+" "+($global:DefaultVIServer).name.Split('.')[0]+".csv" $Reportname= $path.path+$name $Report|Export-Csv -NoTypeInformation -Path $Reportname } $TaskView.DestroyCollector() } } |