Powercli script wrapper

From UVOO Tech Wiki
Revision as of 17:10, 16 June 2022 by Busk (talk | contribs)
Jump to navigation Jump to search

.env.ps1

$env:VSPHERE_USERNAME = 'foo'
$env:VSPHERE_USERPASS = "bar"
$env:VCENTERS = "vc1, vc2"
$env:THROTTLE_LIMIT=3
$env:minDiskSize = 80

set env vars

. .env.ps1
#!/usr/bin/pwsh
Param(
   [string] [Parameter(Mandatory=$false)] $VmName,
   [switch] [Parameter(Mandatory=$false)] $InvokeCmd,
   [string] [Parameter(Mandatory=$false)] $Cmd,
   [switch] [Parameter(Mandatory=$false)] $GetCred,
   [switch] [Parameter(Mandatory=$false)] $authenticate,
   [switch] [Parameter(Mandatory=$false)] $GetVmDisk,
   [switch] [Parameter(Mandatory=$false)] $GetVmInfo,
   [switch] [Parameter(Mandatory=$false)] $InvokeCmdAllVms,
   [switch] [Parameter(Mandatory=$false)] $SetVmDisk
)
$ErrorActionPreference = "Continue"  # Stop
if ($GetCred){
  $Cred = Get-Credential
}
$minDiskSize = 80  # In GBs
$ErrorActionPreference = 'Stop'


$vcenters = $env:VCENTERS.split()
Write-Output "Running on vcenters:"
foreach ($vcenter in $vcenters) {
  echo $vcenter
}
sleep 2


function authenticate($vcenters){
  foreach ($vcenter in $vcenters) {
    Write-Output "Authenticating to $vcenter"
    if ($env:VSPHERE_USERNAME -and $env:VSPHERE_USERPASS){
          Connect-VIServer -Server $vcenter -User $env:VSPHERE_USERNAME -Password $env:VSPHERE_USERPASS
    }else{
          Connect-VIServer -Server $vcenter
    }
  }
}


function getGuestOs( $vmGuest ){
  if ( $vmGuest.GuestFamily -Like "*Windows*" ) {
    # Write-Host "vm: $vm os: $vmGuest is Windows"
    return "Windows"
  } elseif ( $vmGuest.GuestFamily -Like "*Linux*" ) {
    # Write-Host "vm: $vm os: $vmGuest is Linux"
    return "Linux"
  } else {
    # Write-Host "$vm is Undetected/Unsupported.\n"
    return "Undetected"
  }
}


function guestIsWindows($vmGuest){
  if ( $vmGuest -Like "*Windows*" ) {
    Write-Output "$vmGuest is Windows"
    return $true
  } else {
    return $false
  }
}


function guestIsLinux($vmGuest){
  Write-Output $vmGuest
  if ( $vmGuest -Like "*Linux*" ) {
    return $true
  } else {
    return $false
  }
}


function resizeDiskToMaxSize ($name){
  Invoke-Command -ComputerName $name `
    -ScriptBlock { Update-Disk -Number 0; Resize-Partition -DriveLetter C -Size $(Get-PartitionSupportedSize -DriveLetter C).SizeMax} `
    -cred $cred
}



# function loop_vcenters($cmd){
function InvokeCmdAllVms($cmd){
  Write-Output "Running on vcenters:"
  foreach ($vcenter in $vcenters) {
        echo $vcenter
        sleep 2
        if ($env:VSPHERE_USERNAME -and $env:VSPHERE_USERPASS){

      # echo try
          Connect-VIServer -Server $vcenters -User $env:VSPHERE_USERNAME -Password $env:VSPHERE_USERPASS
        }else{
      # echo else
          # Connect-VIServer -Server @($env:VCENTERS)
        }
  Invoke-Command-On-All-VMs $cmd
  }
}


function Invoke-Command-On-All-VMs($cmd) {
  Connect-VIServer -Server $global:DefaultVIServer -Session $global:DefaultVIServer.SessionId
  $vmlist = Get-VM
  $vmlist | ForEach-Object -ThrottleLimit $env:THROTTLE_LIMIT -Parallel {
        $null = Connect-VIServer -Server $using:global:DefaultVIServer -Session $using:global:DefaultVIServer.SessionId
        $vm = $_
        echo $vm.Name
        sleep 3
        $PrevErrorActionPreference = $ErrorActionPreference
        $ErrorActionPreference = 'silentlycontinue'

   $vmPowerState = $vm.PowerState
  # PoweredOn
    if($vm.PowerState -eq "PoweredOn"){
          try {
                $r = Invoke-VMScript -vm $vm -ScriptText $using:cmd  -GuestUser $using:env:VSPHERE_USERNAME -GuestPassword $using:env:VSPHERE_USERPASS
                Write-Output $r
          } catch { $e = $_.Exception.Message; Write-Output $e }
    }
  }

}


function Get-vmInfo ($vmName) {
  $vm = Get-VM -Name $vmName | Select-Object -Property *
  Write-Output $vm
  $vmDisk = Get-VM $vmName | Get-Harddisk | Select-Object -Property *
  Write-Output $vmDisk
}


function Get-vmDisk ($vmName) {
  $vm = Get-VM -Name $vmName | Select-Object -Property *
  # $vmDisk = Get-HardDisk -VM $vm
  $vmDisk = Get-VM $vmName | Get-Harddisk | Select-Object -Property *
  if ( $vmDisk.CapacityGB -lt $minDiskSize ) {
    Write-Output "W: $vmName current size $($vmDisk.CapacityGB) GB is < than min $minDiskSize GB"
    if (guestIsWindows($vm.Guest)){
      Write-Output "OS is Windows."
    }
  } else {
    Write-Output "I: $vmName current size $($vmDisk.CapacityGB) GB is > than min $minDiskSize GB"
  }
}


function SetIncreaseVmDiskToMinSize($vmName){
  $vmDisk = Get-VM -Name $vmName | Get-Harddisk | Select-Object -Property *
  Write-Output $vmDisk.CapacityGB
  if ( $vmDisk.CapacityGB -lt $minDiskSize ) {
    Write-Output "W: $vmName current size $($vmDisk.CapacityGB) GB is < than min $minDiskSize GB"
    Get-HardDisk -VM $vm | Set-HardDisk -CapacityGB $minDiskSize
    if (guestIsWindows($vm.Guest)){
      Write-Output "Expand $vmName drive C to max partition size."
      $script0 = "Update-Disk -Number 0; Resize-Partition -DriveLetter C -Size $(Get-PartitionSupportedSize -DriveLetter C).SizeMax"
      Invoke-VMScript $script0 -vm $vmName -GuestCredential $Cred
    }
  } else {
    Write-Output "I: $vmName current size $($vmDisk.CapacityGB) GB is > than min $minDiskSize GB"
  }
}


function InvokeCommand($vmName, $cmd) {

  $vm = Get-VM -name $vmName
  $vmGuest = $vm.Guest
  $vmPowerState = $vm.PowerState
  $vmPowerState = $vm.PowerState
  # PoweredOn
  if($vm.PowerState -eq "PoweredOn"){
    try {
      $r = Invoke-VMScript -vm $vm -ScriptText $cmd  -GuestUser $env:VSPHERE_USERNAME -GuestPassword $env:VSPHERE_USERPASS
      Write-Output $r
    } catch { $e = $_.Exception.Message; Write-Output $e }
  }

}


function DetectInvokeCommand($vmName, $cmd) {
    $vm = Get-VM -name $vmName
    $vmGuest = $vm.Guest
    $vmPowerState = $vm.PowerState
    Write-Host "$vm $vmGuest $vmPowerState"
    $os = getGuestOs($vmGuest)
    $os = "Linux"
    if ($os -eq "Windows"){
      Write-Output "OS is Windows."
      try {
        $r = Invoke-VMScript -vm $vm -ScriptText $cmd -ScriptType Powershell -GuestCredential $Cred
        Write-Output $r
      } catch { $e = $_.Exception.Message; Write-Output $e }
    } elseif ($os -eq "Linux"){
      Write-Output "OS is Linux."
      try {
        $r = Invoke-VMScript -vm $vm -ScriptText $cmd -ScriptType Bash -GuestUser $env:VSPHERE_USERNAME -GuestPassword $env:VSPHERE_USERPASS
        Write-Output $r
      } catch { $e = $_.Exception.Message; Write-Output $e }
    } else {
      Write-Output "W: OS is unsupported."
    }
}


function main(){
  if ($authenticate){
    authenticate $vcenters
  }
  if ($GetVmDisk) {
    Get-VmDisk($VmName)
  }
  if ($GetVmInfo) {
    $info=$(Get-VmInfo($vmName))
    echo "foo"
    echo $info.GuestId
  }
  if ($SetVmDisk) {
    SetIncreaseVmDiskToMinSize($vmName)
  }
  if ($InvokeCmdAllVms) {
    # loop_vcenters $cmd
    InvokeCmdAllVms $cmd
  }
  if ($InvokeCmd) {
    InvokeCommand $vmName $Cmd
  }


}


main




# NOTES ===============================================

# Register-DNSClient

# Notes

# $vm = Get-VM $vm | Select-Object -Property *
  # if ( $vmGuest.Guestid -Like "*ubuntu*" ) {
    # $info=$(Get-VmInfo($vmName))
    # if($info.GuestId -like "ubuntu"){
    #    $cmd="ls"
    # elseif($info.GuestId -like "ubuntu"){
    # else
   # }
    # $Cmd = "ls"
    # Invoke-Command($vmName, $cmd)

Readme

# Getting Started

## Update .env.ps1

Update .env.ps1 with your settings

## Setup

. ./.env.ps1

./vcli.ps1 -authenticate

<br />## Some command examples

./vcli.ps1 -InvokeCmd -VmName "myvmguestname" -Cmd "pwd"

./vcli.ps1 -InvokeCmdAllVms -Cmd "pwd"