Quantcast
Channel: VMware Communities : All Content - VMware PowerCLI

Host overall status

$
0
0

Hi All,

 

I'm trying to generate the report for Host over all status from multiple vcenter server, but it while running the script. No error. Any pointers will be much appreciated.

 

$userbane = "domain\admin"

$encrypted = Get-Content D:\Scripts\scriptsencrypted_paswd_admin.txt | ConvertTo-SecureString

 

 

$Cred = New-Object System.Management.Automation.PsCredential($userbane, $encrypted)

 

 

 

 

$vCenters = (Get-Content "C:\Temp\VC1.txt")

$report = @()

 

 

foreach ($vcenter in $vcenters) {

 

 

    Connect-VIServer $vcenter -Credential $Cred

 

 

 

 

    foreach ($cluster in Get-Cluster -Server $vcenter){

 

 

 

 

Get-Datacenter | Get-Cluster -PipelineVariable cluster | Get-VMHost |

  select @{N = 'Cluster'; e = {$cluster.Name}}, Name,

 

 

@{N = 'OverallStatus'; E = {$_.ExtensionData.OverallStatus}}}

 

 

Disconnect-VIServer -Server $vcenter -Confirm:$false

 

 

}

 

 

$report | Export-Csv -path c:\Temp\HostStatus.csv -NoTypeInformation -UseCulture

 

 

$sMail = @{

 

 

    From                       = 'mail@domain.com'

 

 

    To                         = 'mail@domain.com'

 

 

    Subject                    = 'Remote Site Host Report'

 

 

    Body                       = "Report. Sending now."

 

 

    Attachments                = 'C:\Temp\HostStatus.csv'

 

 

    Priority                   = 'High'

 

 

    DeliveryNotificationOption = 'OnSuccess', 'OnFailure'

 

 

    SmtpServer                 = 'smtp.ta.domain.com'

 

 

}

 

 

Send-MailMessage @sMail

 

 

 

Thanks

V


How to get VM Guest/Config ConfiguredGuestId and RuntimeGuestId by using get-view?

$
0
0

Hello,

 

I would like to retrieve the VM Guest properties ConfiguredGuestId and RuntimeGuestId by using get-view and not get-vm.

How do I do that?

 

I cannot find it in VMware.Vim.GuestInfo, VMware.Vim.VirtualMachineGuestSummary, VMware.Vim.VirtualMachineConfigSummary or VMware.Vim.VirtualMachineConfigInfo.

 

Also i cannot find this in the API Documentation.

 

Thanks a lot in advance!

 

Perhaps mattboren or LucD can solve my problem ;-)?

 

Regards,

René

Move-VM dosent work to move a VM to a DatastoreCluster for Cross VC Migrations

$
0
0

Hi Experts

 

I have a Script to do cross VC migration which works perfectly. We use it everyday and its fabulous

Recently we wanted to move a VM which we could not get into one datastore so we used Datastorecluster which is supported by Move-VM

Now if i use a script to move a VM within a Cluster then the Datastorecluster is working.

If i use the same approach for a Cross VC then I get the following error and i need your help please

 

VM is a alive on the source VC... Migration_Oct_Test

VM will be placed on following ESXi host... vhst6013.mydomain.com

VM Network Adaptor info... Network adapter 1

VM will be moved to following PortGroup...  XXX-VLAN-AAA-BK-VMN

VM will be moved to following datastore...  DSClusterDS_NR

 

 

Move-VM : 20-10-2020 17:49:37 Move-VM When migrating a VM to a different vCenter Ser

ver both Destination and Datastore need to be specified. No other destination types b

ut VMHost/Resource Pool and Datastore are supported for Cross vCenter vMotion

At line:120 char:7

+       Move-VM -vm $VM -Destination $destination -NetworkAdapter $netw ...

+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Move-VM], VimException

    + FullyQualifiedErrorId : Client20_VmHostServiceImpl_CheckMoveVmParameters_BothD

   estinationAndStorageRequiredForXVCVmotion,VMware.VimAutomation.ViCore.Cmdlets.Co 

  mmands.MoveVM

 

 

This part of the script is the one which gives the issue

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

 

#$destinationDatastore = Get-Datastore $VMdetail.TgDatastore  -ErrorAction SilentlyContinue

 

    #If  i add the get-datastorecluster then the move VM fails

          $destinationDatastore = get-datastorecluster $VMdetail.TgDatastore  -Server "DestinationVC.Mydomain.com"

 

 

         if ($destinationDatastore)  {

           

            Write-Host "VM will be moved to following datastore... " -ForegroundColor Yellow  $destinationDatastore

            }

         Else {

        

            Write-Host " Destination datastore not found" -ForegroundColor Magenta

            Continue

            }

 

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

#################### SCRIPT####################################

 

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

#        ***Kick off the vMotion VMs between Virtual Centers***

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

# vMotion Details

 

 

$VMdetails = Get-Content -Path $FileBrowserMigrationDetailsFile |Select-String '^[^#]' | ConvertFrom-Csv -UseCulture

 

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

# Search the VM to be migrated and validate VM if found else skip to next record

# on the CSV

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

 

 

Foreach ($VMdetail in $VMdetails)  {

 

 

         $VM = Get-VM -Name $VMdetail.VMNAME -ErrorAction SilentlyContinue

 

 

 

 

If ($VM) { 

                        Write-Host "VM is a alive on the source VC..." -ForegroundColor Yellow  $VM

Else { 

                        Write-Host 'VM'  $VMdetail.VMNAME' Cannot be found' -ForegroundColor Magenta

                        continue 

 

 

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

# Check if there is a Destination ESXi host on the specified cluster

# If found proceed or skip to next record

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

 

 

       

        

$destination = Get-cluster $vmdetail.TgCluster -ErrorAction SilentlyContinue |Get-VMHost |Select-Object -First 1  #-Name vhst6012.rabobank.corp #

 

 

if ($destination){ 

                        Write-Host "VM will be placed on following ESXi host..." -ForegroundColor Yellow $destination 

Else { 

                        Write-host "Destination ESXi host" $vmdetail.TgCluster "is not Accessible"  -ForegroundColor Magenta

                        continue

              

 

 

 

 

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

# Check if the Network Adapter for the VM is found

# If found proceed or skip to next record

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

 

 

 

 

 

 

         $networkAdapter = Get-NetworkAdapter -vm $VM -ErrorAction SilentlyContinue

               

If ($networkAdapter){ 

                        Write-Host "VM Network Adaptor info..." -ForegroundColor Yellow $networkAdapter 

Else { 

                        Write-Host "Network Adpater cannot be attahced and migration will fail" -ForegroundColor Magenta

                        continue 

 

 

 

 

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

# Check if the destination vDS switch is available, also check if the destination

# PortGroup is found, if unavailable skip to the next record

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

 

 

 

 

        

         $destinationPortGroup = Get-VDSwitch -Name $VMdetail.TgSwitch -ErrorAction SilentlyContinue |Get-VDPortgroup -Name $VMdetail.TgPortGroup -ErrorAction SilentlyContinue

 

 

If ($destinationPortGroup){ 

                        Write-Host "VM will be moved to following PortGroup... " -ForegroundColor Yellow  $destinationPortGroup 

Else { 

                        Write-Host "vDS Switch or PortGroup cannot be found " -ForegroundColor Magenta

                        continue 

                

 

 

       

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

# Check if the destination Datastore is available if found 

# Proceed , if unavailable skip to the next record

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

 

 

 

 

 

 

         #$destinationDatastore = Get-Datastore $VMdetail.TgDatastore  -ErrorAction SilentlyContinue

 

 

          $destinationDatastore = get-datastorecluster $VMdetail.TgDatastore  -Server "DestinationVC.Mydomain.com"

 

 

         if ($destinationDatastore)  {

           

            Write-Host "VM will be moved to following datastore... " -ForegroundColor Yellow  $destinationDatastore

            }

         Else {

        

            Write-Host " Destination datastore not found" -ForegroundColor Magenta

            Continue

            }

              

}            

 

 

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

# Move-VM does the actual move of the VM provided all of the above checks are

# Satisfied and completes the migration.

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

 

 

               

      Move-VM -vm $VM -Destination $destination -NetworkAdapter $networkAdapter -PortGroup $destinationPortGroup -Datastore $destinationDatastore -server vcpbxt001.compute.rabobank.nl| out-null  -ErrorVariable $movevmerr

         if ($movevmerr -eq $null )  {

        Write-host " VM migration in progress ........." -ForegroundColor Magenta

        }

        Else   {

        Write-Host " Move-VM error $movevmerr"

        continue

        }

vmk(n) -- portgroup (OpaqueNetwork NDVS)

$
0
0

Hi Expert

i would like to get the source code of this view (in attached )  ,i accpet (powershell, powercli, RestAPI,esxCLI, ...)

at least i need to get a table with first colomn vmk(number) and in the second colomn the port group name ( but i am using OpaqueNetwork NDVS managed by NSX-T)

i tryed a lot of things but no way

 

please Help

PowerCLi script to Upload files into datastores for multiple hosts in parallel

$
0
0

Hello Friends,

 

Recently i've got a scenario where i have to upload the files into multiple hosts in their local datastores around 2000+ boxes. I'm trying below scripts to upload the files to selected 50 hosts in parallel. but somehow script is not running as per our expectation. Any help would be highly appreciated here.

 

Script object: master script should initiate both file upload scripts in parallel for multiple hosts at a time.

 

Master script:

===========

$hosts= Get-Content "C:\HostList.txt"

 

 

foreach ($esx in $hosts) {

 

Write-Host "Running File upload1 script on host: $esx ..."  -ForegroundColor Yellow

#.\Test_FileUpload.ps1 -HostName $esx -User "XXXX"  -Pswd "XXXX"  

Write-Host "Running File upload2 script on host: $esx ..."  -ForegroundColor Yellow

#.\Test_FileUpload2.ps1 -HostName $esx -User "XXX"  -Pswd "XXXX"

}

 

script2:Test_FileUpload.ps1

===========

Param(

[string]$HostName,

[string]$User,

[string]$Pswd

)

 

$fileName = "C:\Users\New folder\DELL-T330\ESXi670-202008001.zip"

#$tgtFolder = 'ISO'

$StartTime = Get-Date

 

 

Write-Host "************************************************" -ForegroundColor Cyan

Write-Host "Please wait while connecting the host: $HostName " -ForegroundColor Yellow

Write-Host "************************************************" -ForegroundColor Cyan

 

 

Connect-VIServer -Server $HostName -user $User -Password $Pswd

Write-Host "connected to the server: $HostName" -ForegroundColor Green

 

 

$datastores = Get-VMHost $HostName | Get-Datastore | where{$_.name -like "datastore*"}

 

 

    foreach($ds in $datastores){

   

    New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root "\" > $null

    Write-Host "New ISO folder has been created under DS: $ds " -ForegroundColor Green

     New-Item -Path DS:\ISO -ItemType Directory

    

     $tgtFolder ='ISO'

     New-PSDrive -Location $ds -Name DS1 -PSProvider VimDatastore -Root "\" > $null

  

    if(!(Test-Path -Path "DS1:/$($tgtFolder)")){

        New-Item -ItemType Directory -Path "DS1:/$($tgtFolder)" > $null

    }

    Write-Host "DS copy is in-progres.. Pls wait" -ForegroundColor Yellow

    Copy-DatastoreItem -Item $fileName -Destination "DS1:/$($tgtFolder)"

   

    Remove-PSDrive -Name DS -Confirm:$false

    Remove-PSDrive -Name DS1 -Confirm:$false

}

 

Write-Host " DS copy task has completed for host: $fileName" -ForegroundColor Green

 

$EndTime = Get-Date

$TotalTime = New-TimeSpan –Start $StartTime –End $EndTime #| select -expandproperty Seconds

Write-Host "************************************************" -ForegroundColor Cyan

Write-Host "Total time taken to complete the ISO copy: $TotalTime " -ForegroundColor Green

Write-Host "************************************************" -ForegroundColor Cyan

 

 

script3:Test_FileUpload2

==========

Param(

[string]$HostName,

[string]$User,

[string]$Pswd

)

 

$fileName = "C:\Users\New folder\DELL-T330\VMware-VMvisor-Installer-6.7.0.update03-16316930.x86_64-DellEMC_Customized-A06.zip"

#$tgtFolder = 'ISO'

$StartTime = Get-Date

 

 

Write-Host "************************************************" -ForegroundColor Cyan

Write-Host "Please wait while connecting the host: $HostName " -ForegroundColor Yellow

Write-Host "************************************************" -ForegroundColor Cyan

 

 

Connect-VIServer -Server $HostName -user $User -Password $Pswd

Write-Host "connected to the server: $HostName" -ForegroundColor Green

 

 

$datastores = Get-VMHost $HostName | Get-Datastore | where{$_.name -like "datastore*"}

 

 

    foreach($ds in $datastores){

   

    New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root "\" > $null

    Write-Host "New ISO folder has been created under DS: $ds " -ForegroundColor Green

     New-Item -Path DS:\ISO -ItemType Directory

    

     $tgtFolder ='ISO'

     New-PSDrive -Location $ds -Name DS1 -PSProvider VimDatastore -Root "\" > $null

  

    if(!(Test-Path -Path "DS1:/$($tgtFolder)")){

        New-Item -ItemType Directory -Path "DS1:/$($tgtFolder)" > $null

    }

    Write-Host "DS copy is in-progres.. Pls wait" -ForegroundColor Yellow

    Copy-DatastoreItem -Item $fileName -Destination "DS1:/$($tgtFolder)"

   

    Remove-PSDrive -Name DS -Confirm:$false

    Remove-PSDrive -Name DS1 -Confirm:$false

}

 

Write-Host " DS copy task has completed for host: $fileName" -ForegroundColor Green

 

$EndTime = Get-Date

$TotalTime = New-TimeSpan –Start $StartTime –End $EndTime #| select -expandproperty Seconds

Write-Host "************************************************" -ForegroundColor Cyan

Write-Host "Total time taken to complete the ISO copy: $TotalTime " -ForegroundColor Green

Write-Host "************************************************" -ForegroundColor Cyan

 

 

Regards,

Swamy Naveen

The module 'VMware.VimAutomation.Sdk' cannot be installed because the catalog signature in 'VMware.VimAutomation.Sdk.cat' does not match the hash generated from the module.

$
0
0

Unable to install VMware.PowerCLI module getting error as

PS C:\> Install-Module -name vmware.powerCLI -scope CurrentUser -Force -allowclobber
PackageManagement\Install-Package : The module 'VMware.VimAutomation.Sdk' cannot be installed because the catalog
signature in 'VMware.VimAutomation.Sdk.cat' does not match the hash generated from the module.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1661 char:21
+ ...          $null = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package],
   Exception
    + FullyQualifiedErrorId : InvalidCatalogSignature,ValidateAndGet-AuthenticodeSignature,Microsoft.PowerShell.Packag
   eManagement.Cmdlets.InstallPackage

My Powershell version details are as below.

PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.0
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.0
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Get VMXNET3 - Network DirectPath I/O Status

$
0
0

Hello Community, is there a way via script to get all VMs that have DirectPath I/O enabled?

convert-html command

$
0
0

Hi luc ,

can yu please check html command to get proper output .

 

 

 

$path1 = 'D:\hc'

$path = "D:\hc\compliance-$(Get-Date -Format 'yyyyMMdd-HHmm').html"

 

 

#(get-credential).password | ConvertFrom-SecureString | set-content "$path1\password.txt"

$password = Get-Content "$path1\password.txt" | ConvertTo-SecureString

$credential = New-Object System.Management.Automation.PsCredential("administrator@vsphere.local",$password)

connect-viserver -server "vcenter01" -Credential $credential

 

 

 

 

 

 

 

 

 

$head = @'

 

 

<style>

 

 

body { background-color:#dddddd;

 

 

       font-family:Tahoma;

 

 

       font-size:12pt; }

 

 

td, th { border:1px solid black;

 

 

         border-collapse:collapse; }

 

 

th { color:white;

 

 

     background-color:black; }

 

 

table, tr, td, th { padding: 2px; margin: 0px }

 

 

table { margin-left:50px; }

 

 

</style>

 

 

'@

 

 

 

 

 

 

 

 

$esxi=get-vmhost

$deviated_esxi=@()

foreach($e in $esxi)

 

 

{

$v=get-vmhost -Name $e

 

 

 

 

$accountunlocktime_minutes=(Get-AdvancedSetting -Entity $v -Name Security.AccountUnlockTime).value/60

 

 

if($accountunlocktime_minutes -ne "60"){

 

 

 

 

[PSCustomObject]@{

 

 

                esxinmae = $v

 

 

               

                accountunlocktime_minutes=$accountunlocktime_minutes

 

 

               

 

 

               

            }

 

 

            $deviated_esxi += $v

            }

 

 

 

 

}

 

 

 

 

 

 

 

 

$deviated_esxi|ConvertTo-Html -Property name -Fragment -PreContent '<h2>esxiwithlockdowntime not60mins </h2>' |

 

 

   Out-String

 

 

 

 

   ConvertTo-HTML -head $head -PostContent $deviated_esxi |

 

 

   Out-String | Out-File -FilePath $path


plink issues

$
0
0

any idea why this is not working

 

$esxhosts = get-vmhost -name (get-content esxhosts.txt)

#$root_pass = read-host -Prompt "Enter root PAssword"

$root_pass = Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File encryptedpassword.txt

$encrypted = ConvertTo-SecureString(Get-Content ".\encryptedpassword.txt")

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($encrypted)

$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

$cmd1 = '/etc/init.d/slpd stop'

 

foreach ($vmhost in $esxhosts) {

 

 

echo y | plink.exe $vmhost -pw $password -l root $cmd1 -batch

}

 

 

I keep getting this kind of prompt

 

Screen Shot 2020-10-21 at 1.39.04 PM.png

intellisense _powercli

$
0
0

Hi Luc,

 

 

 

Get-VMHostNetworkAdapter -VMHost $esxi -VMKernel|?{$_.

while typing above i was expecting ManagementTrafficEnabled as one of the listed properties but i did not find that .not sure if its a bug or someother thing but it is not the exptected

response .i need to write manually ...colud you suggest something on this

 

Get-VMHostNetworkAdapter -VMHost $esxi -VMKernel|?{$_.ManagementTrafficEnabled -eq "true"}

USB passthrough via CLI

$
0
0

Hi, i have a unusual task. I wanted to know how i can passthrough USB devices via CLI, while my VM is on.

 

Basically it always possible and always works fine via UI. 

 

As of today i can do this by editing .vmx file of my VM, adding path of usb device. But editing .vmx file is only possible when VM is off.

 

Could anybody help me with that ?

send multiple report attachment

$
0
0

Hi all,

 

Need help to modify sending email for report using .net method that can send multiple attachment

this is the original script : PowerCLI-1/CPReport-v2.1-Community-Edition.ps1 at master · voletri/PowerCLI-1 · GitHub

################################# PER CLUSTER RESILIENCE REPORT ##########################

 

# HEADER

$HTMLBody += CreateHeader ("CLUSTER RESILIENCE REPORT FOR <font color=" + $ColorArray[$ColorArrayIndex] + "><b> CLUSTER " + $ClusterTemp.Name + "</b></font>")

 

# INTRO TEXT

$HTMLBody += "<b>" + [String]$VMHostsInCluster.Count + " ESXi Hosts with a total of " + (GetTotalCPUCyclesInGhz ($VMHostsInCluster)) + " GHz on " +

(GetTotalNumberofCPUs ($VMHostsInCluster)) + " CPUs and " + (GetTotalMemoryInGB ($VMHostsInCluster)) + " GB of RAM </b><br>"

$HTMLBody += "<b>" + [String]$DatastoresInCluster.Count + " Datastores with a total of " + (GetTotalDatastoreDiskSpaceinGB ($DatastoresInCluster)) + `

" GB of disk space</b><br><br>"

 

#TABLE

$HTMLBody += CreateClusterResilienceTable ($ClusterTemp)

 

 

# CHART

if ($global:ArrayOfNames.count -gt 0){ # If HA Admission Control is set to a %, create a pie chart

Create-Chart -ChartType Pie -ChartTitle "Cluster Resilience Report" -FileName ("Cluster_" + ($ClusterTemp.Name -replace " ", "-") + `

"_Resilience_Report") -ChartWidth 850 -ChartHeight 750 -NameArray $global:ArrayOfNames -ValueArray $global:ArrayOfValues

$HTMLBody += "<IMG SRC=Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_Resilience_Report.png>"

$Attachments += "Cluster_" + ($ClusterTemp.Name -replace " ", "-") + "_Resilience_Report.png"

}

 

# CLEANUP

ReinitializeArrays

 

#-----------------------------------------------------------------------------------------------

# Change the color of the Header for the next Cluster

$ColorArrayIndex++

 

}

}

########################### SEND REPORT BY E-MAIL #################################

$HTMLBody += "</BODY>" # Close HTML Body

$HTMLPage = $HTMLHeader + $HTMLBody + $HTMLFooter

$HTMLPage | Out-File ((Get-Location).Path + "\report.html") # Export locally to html file

Write-Host "Report has exported to HTML file " + ((Get-Location).Path + "\report.html")

Send-Mailmessage -From $FromAddress -To $ToAddress -Subject $Subject -Attachments $Attachments -BodyAsHTML -Body $HTMLPage -Priority Normal -SmtpServer $SMTPServer -UseSSL -Credential (Get-Credential)

Write-Host "Report has been sent by E-mail to " $ToAddress " from " $FromAddress

 

Exit

 

 

What i already try is change to :

########################### SEND REPORT BY E-MAIL #################################

 

$HTMLBody += "</BODY>" # Close HTML Body

$HTMLPage = $HTMLHeader + $HTMLBody + $HTMLFooter

$HTMLPage | Out-File ((Get-Location).Path + "\report.html") # Export locally to html file

Write-Host "Report has exported to HTML file " + ((Get-Location).Path + "\report.html")

 

$message = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress

$att = new-object Net.Mail.Attachment($Attachments)

$message.Subject = $Subject

$message.IsBodyHTML = $true

$message.Body = $HTMLPage

$smtp = New-Object Net.Mail.SmtpClient($SMTPServer)

$message.Attachments.Add($att)

$smtp.Send($message)

 

Write-Host "Report has been sent by E-mail to " $ToAddress " from " $FromAddress

 

It can send the email but not the attachments and have error

Exception calling "Add" with "1" argument(s): "Value cannot be null.

Parameter name: item"

At D:\Drive_D\My Documents\VMware\Script\CPReport\CPReport-v2.1.ps1:920 char:1

+ $message.Attachments.Add($att)

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : ArgumentNullException

 

Thanks for all the help.

PowerCLI performance vs clicking 'Export' button in vsphere UI.

$
0
0

Hello!

I'm in the process of trying to automate some report gathering and data massaging that I've been tasked to do.  This has led me down the road into PowerCLI, and many posts and answers (especially LuciD's) have been very helpful! While I have several tasks that are pulling specific information about my cluster's health, etc - I've been asked to automate the 'Export' button.  I have a bit over 1800 machines in the cluster, and the 'export' button takes about half a second to generate what I'm looking for - but the same report (still missing a few columns, I'm a total newb) takes HOURS to run.  Am I missing something?  

If someone has figured out an efficient way to create this .csv file progmramatically? 

 

Thank you in advance,


Ewing

Software Acceptance Level

$
0
0

I'm trying to get the software acceptance level for some hosts and then provide a result

basicaly the script should collect the info and then compare it unfortunaly it's not working

 

$esxcli = Get-ESXCLI -VMHost -V2 -Server

$generatefile = ForEach($line in $esxcli) {$line.software.acceptance.get()}

$generatefile | Out-String | ForEach-Object { $_.Trim() } > "$FileHardening\Software_AcceptanceLevel-config.txt"

$generateerrorfile = foreach($line in (gc "$FileHardening\Software_AcceptanceLevel-config.txt")) {if ($line -like "*PartnerSupported*") {} else {$line}}

if ($generateerrorfile -eq $Null) {

Write-Log -FilePath $LogFile -Message "All Hosts have PartnerSupported Software Acceptance" -Level Success

}

else{

Write-Log -FilePath $LogFile -Message "Hosts with wrong Software Acceptance detected" -Level Warning

Write-Log -FilePath $LogFile -Message "You need to modify them manually" -Level Warning

Get-EsxCli Could not establish secure channel for SSL/TLS with authority

$
0
0

despite that I'm adding the below to my script, I have always the error message : Get-EsxCli Could not establish secure channel for SSL/TLS with authority

 

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls,[System.Net.SecurityProtocolType]::Tls11,[System.Net.SecurityProtocolType]::Tls12

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

 

has anyone encountered this kind of problem?


Ensure the ESXi shell is disabled

$
0
0

I'm trying to create a script to disable ESXi shell, as I'm in the obligation to get the configuration before any change things I made the script like this

 

#Collect configuration

Get-VMHost | Get-VMHostService | Where { $_.key -eq "TSM" } | Select VMHost, Key, Label, Policy | Out-String | ForEach-Object { $_.Trim() } > ".\ESXiShell.txt"

 

# Verification

$CheckESXi_Shell_Disabled = (gc .\HardeningESXi-Logs\ESXi_Shell_Disabled-Config.txt | ft Value | findstr /v " _$Null Value ----- _$Null") | where-object {$_ -notlike '*off*'} | foreach{$_.split(".")[0]}

 

function ESXiDisabled {

    if ($CheckESXiDisabled -eq "off") {

    Write-Log -Level Success -Message "All Hosts have ESXi shell disabled" -FilePath $LogFile

    }

    else {

    Write-Host -f red "Host(s) with ESXi Shell not set as required "

    Write-Log -Level Success -Message  "Fixing host(s)" -FilePath $LogFile

    $CheckESXiDisabled | ForEach-Object {Get-VMHost | Get-VMHostService | Where { $_.key -eq "TSM"} | Set-VMHostService -Policy Off

    }

}

}

ESXiDisabled

 

unfotunaly the script is not working as expected, if I change the policy from GUI I'm expecting that the script detect that and do change and if the policy is set to OFF script should say that and nothing is done

Can anyone tell me why this 'else' statement is not working?…

$
0
0

Hi all,

 

I have the following script to retrieve the tags from various vcenter servers however I cannot see why the 'else' statement in line 27 is throwing an error as not recognised?

 

I have checked the structure of the code many times now and cannot see any problems

 

Code attached

 

Many thanks in advance guys!

How can i find out Power off particular VM time through powercli

$
0
0

How can i find out Power off particular VM time through powercli

Datastore Load Report - Exclude DataStore

$
0
0

I have a report that shows all datastores in a DC and shows what percent is running on that datastore so I can check the load and keep it balanced manually if needed, but I added a cold storage datastore and it's showing up in this report, what is the best way to remove it:

 

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

#         Variables         #

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

$date=Get-Date -format "yyyy-MMM-d"

$datetime=Get-Date

$filelocation="\var\www\NAS-Loads\VDC-NAS-Load\VDC-NAS-Load-$date.htm"

 

 

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

# Add Text to the HTML file #

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

$Header = @"

<style>

TABLE {border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse;}

TH {border-width: 1px; padding: 3px; border-style: solid; border-color: black; background-color: #6495ED;}

TD {border-width: 1px; padding: 3px; border-style: solid; border-color: black;}

</style>

"@

 

$dcName = 'VDC'

$ds = Get-Datacenter -Name $dcName | Get-Datastore |

  where {$_.Type -eq 'VMFS' -and $_.ExtensionData.Summary.MultipleHostAccess}

$totalSpaceUsed = $ds | % {$_.CapacityGB - $_.FreeSpaceGB} | Measure-Object -Sum | select -ExpandProperty Sum

 

Get-Stat -Entity $ds -Stat 'disk.used.latest' -Realtime -MaxSamples 1 -Instance '' |

  ForEach-Object -Process {

  New-Object PSObject -Property @{

   Datastore   = $_.Entity.Name

   PercentofTotalSpaceGB = [math]::Round(($_.Value / 1MB) / $totalSpaceUsed * 100, 1)

  }

} |

 

  Sort-Object -Property Datastore |

  Select Datastore, PercentofTotalSpaceGB |

  ConvertTo-Html -Head $Header |

  Out-File $filelocation

 

Invoke-Item -Path .\report.html

vCheck health - Does this make any changes ?

$
0
0

Hi All,

 

I think the vcheck health script does not make any changes to vCenter , is that correct ? if yes will a read only account run it good idea ?

 

Thanks

List of Unused vCenter Roles

$
0
0

Hi all.

 

I'm working on a review of unused vCenter roles in our environment and found this script below.

 

Get-VIPermission | Select Role, Principal, Entity, UID | Export-CSV “E:\JCEM\Rights.csv”

 

However, it seems that it only getting the roles that are currently assigned.

 

Can anyone help how can I also pull the roles that are not being used?

 

Thanks

Overall VM Utilization summary

$
0
0

Hi All,

 

I'm trying to pull the VM utilization summary report for all the VM's in the below format, but it runs forever without any output. Can some experts help me resolve this issue.

 

NamevCPUUtilization % (Peak)Utilization % (Avg)Memory (GB)Utilization % (Peak)Utilization % (Avg)Disk Space (GB)Utilization % (Peak)Utilization % (Avg)vNICUtilization MBps (Peak)Utilization MBps (Avg)

 

 

 

# VM Utilisation Summary ###

 

$encrypted = Get-Content D:\Scripts\scriptsencrypted_paswd_admin.txt | ConvertTo-SecureString

$Cred = New-Object System.Management.Automation.PsCredential($userbane, $encrypted)

 

$Cred = New-Object System.Management.Automation.PsCredential($userbane, $encrypted)

 

 

$vCenters = (Get-Content "C:\Temp\VC2.txt")

 

$vms = Get-VM

$start = (Get-Date).AddHours(-24)

 

$performance = @()

 

foreach ($vcenter in $vcenters) {

 

  Connect-VIServer $vcenter -Credential $Cred

 

 

$performance += Get-Stat -Entity $vms -Start $start -ErrorAction SilentlyContinue |

 

Group-Object -Property {$_.Entity.Name} |

 

 

Select @{N='VM';E={$_.Name}},

 

 

    @{N='Cluster';E={(Get-Cluster -VM $_.Name)}},

    @{N='CPU(%)';E={"{0:N1}" -f ($_.Group | where{$_.MetricId -eq 'cpu.usage.average'} | Measure-Object -Property Value -Average | select -ExpandProperty Average)}},

 

 

    @{N='Memory(%)';E={"{0:N1}" -f ($_.Group | where{$_.MetricId -eq 'mem.usage.average'} | Measure-Object -Property Value -Average | select -ExpandProperty Average)}},

 

 

    @{N='Net(KBps)';E={"{0:N2}" -f ($_.Group | where{$_.MetricId -eq 'net.usage.average'} | Measure-Object -Property Value -Average | select -ExpandProperty Average)}},

 

 

    @{N='Disk(KBps';E={"{0:N2}" -f ($_.Group | where{$_.MetricId -eq 'disk.usage.average'} | Measure-Object -Property Value -Average | select -ExpandProperty Average)}}

 

 

 

   Disconnect-VIServer -Server $vcenter -Confirm:$false

 

 

}

 

    $performance | Export-Csv D:\script\VMperf.csv


Get-View PodStorageDrsEntry.StorageDrsConfig.VmConfig with UpdateViewData()

$
0
0

Hi,

 

is it possible to use UpdateViewData() method with Get-View on the ViewType "StoragePod" to Update the data of PodStorageDrsEntry.StorageDrsConfig.VmConfigfor the VM names without using another Get-View (Get-View -Id $_.Id -Property Name) calls? The extra Get-View calls cost us some valuable seconds which I would like to save and in almost all other places, UpdateViewData() also works fine. So I think I am missing something or doing something wrong.

 

Unfortunately I cannot get it to run with UpdateViewData(), f.e.:

 

$_.UpdateViewData("PodStorageDrsEntry.StorageDrsConfig.VmConfig.Vm.Name")
MhodInvocationExcption: Exception calling "UpdateViewData" with "1" argument(s): ""

 

Example Code:

 

$ViewProperties="Name",

"PodStorageDrsEntry.StorageDrsConfig.PodConfig",

"PodStorageDrsEntry.StorageDrsConfig.VmConfig"


$ViewType="StoragePod"


(Get-View-ViewType $ViewType-Property $ViewProperties).ForEach(

    {

        $_.UpdateViewData("ChildEntity.Name")

        [PSCustomObject][ordered]@{

            Name           = [string]$_.Name

            Datastores     = ($_.LinkedView.ChildEntity.Name) -join', '

            DatastoreIds   = ($_.LinkedView.ChildEntity.MoRef) -join', '

            DrsEnabledVms  = ((@($_.PodStorageDrsEntry.StorageDrsConfig.VmConfig).ForEach( { if ($_.Enabled-eq$true) { Get-View-Id $_.Vm-Property Name } })).Name) -join', '

            DrsDisabledVms= ((@($_.PodStorageDrsEntry.StorageDrsConfig.VmConfig).ForEach( { if ($_.Enabled-eq$false-or$_.Behavior-match"manual") { Get-View-Id $_.Vm-Property Name } })).Name) -join', '

        }

    }

)


(I have the same problem for other Api Types (f.e. in ClusterComputeResource -> $_.ConfigurationEx.DrsVmConfig)

(Perhaps LucD or mattboren can help?)

 

Thanks in advance,

Eize

Get-ESXCli get device smart info

$
0
0

When manually pulling the smart info using the NAA Identifier it works. But when it is stored in a variable, it doesn't. I'd like to be able to pull the smart info for all the devices from all the hosts in a cluster.

 

Snag_634c279.png

 

Snag_637e6bb.png

 

Thanks

VSS swicth - find missing portgroup & send alert in cluster

$
0
0

Hello

 

What is best way to monitor cluster continuously for a missing port group on vss in cluster & report it.

 

eg cluster of 3 nodes , someone created and added portgroup VLAN10 on host1 & host2, but on host3, it was added as Vlan10 .. so an email & vcenter alert should trigger stating the config issue which need attention on port-group consistency ..  i this host profiles can do it ? can vCheck script do it ?  i will put that to run each hr ... anyways a real time alert is noting like it

 

We do in linux world very easy with ansible or say puppet the "configuration managemnet"

 

Thanks

Error when ruuning PowerCLI from .Net application

$
0
0

Hi,

 

I have a .Net app which runs some PowerCLI scripts. I've recently had to rebuild my PC an LAB environment and now certain comands are throwing an error.

 

The error is : "Could not retrieve handler field info from the HttpClient .net type."

 

It only seems to happen with cetain cmdlets such as:

 

Start-VM

Stop-VM

Set-VM

New-VM

 

Which are the cmdlets which conflict with the Hyper-V module. I haven't installed the Hyper-V module and doing a (get-module -ListAvailable).path doesn't tell me its installed.

 

I'm using the latest version of PowerCLI , but have also tried installing older versions

 

My $psversiontable is:

 

Name                           Value

----                           -----

PSVersion                      5.1.18362.1110

PSEdition                      Desktop

PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

BuildVersion                   10.0.18362.1110

CLRVersion                     4.0.30319.42000

WSManStackVersion              3.0

PSRemotingProtocolVersion      2.3

SerializationVersion           1.1.0.1

 

Versions of .Net installed

>=4.x        : 4.8 or later

v4\Client    : Installed

v4\Full      : Installed

v3.5         : Installed

v3.0         : Installed

v2.0.50727   : Installed

v1.1.4322    : Not installed (no key)

 

I'm using vSphere 6.7

 

This only happens when running the scripts from my .Net app and was all working fine before I had to recreate my environment.

 

If i run the scripts from within PowerShell they run with no issue, which I know points to somekind of conflict with my app and not a PowerCli issus but im a bit lost as to know where to go next , so hoping someone can shed some light. Searching for the error online doesn't throw up anything.

 

thanks in advance

Get the list of ESXi servers /scratch locations path?

import-csv

$
0
0

Hi Luc,

 

i am getting very weird error .following code works fine till orange

however when i m trying to get vmhost to do further activities it throws error .

 

esxi1.localhost.com

get-vmhost : 28/10/2020 14:45:32 Get-VMHost VMHost with name

'esxi1.localhost.com ' was not found using the specified filter(s).

At line:6 char:1

+ get-vmhost -Name $v

+ ~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : ObjectNotFound: (:) [Get-VMHost], VimException

    + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimA

   utomation.ViCore.Cmdlets.Commands.GetVMHost

 

 

 

$esxis=import-csv "C:\Users\jvmishra\Desktop\fileroot.csv"

foreach($e in $esxis)

{

$v=$e.esxiname

$v

get-vmhost -Name $v

}

RVtool like

$
0
0

HI gurus

 

I am looking for a script that will bring up all the information that RVTools gets and export it, but on an specific folder instead of the entire env., is this even possible with pscli?

 

Thanks for the help


Get VMs with net adapter not connected

$
0
0

Hi all,

I'm trying to get all the VMs that are "connected" state(to exclude maintenance mode ones) and the "Connect at power on" network adapter setting disabled.

This is what I have but seems to be not working properly Im not getting any result even when I know there are VMs with this setting disabled:

 

 

Get-VM | Get-NetworkAdapter | Where-object {($_.ConnectionState.Connected ) -and ($_.ConnectionState.StartConnected -ne "True")}

 

Any idea?

Powershell - get datastore disk usage rather than total VM disk usage

$
0
0

Hi.  Thanks to LucD I am progressing with my script to get vCenter details but the one bit I am stuck on is with regard to the datastore disk usage particularly if a VM has more than one VMDK and they are on separate datastores.

 

At the moment, I am using the code below to get the datastore names:

 

(Get-View -Id $vm.Datastore -Property Name).Name -join "|"

 

and the code below to get the VM diskspace usage:

 

[math]::Round(($vm.Storage.PerDatastoreUsage.Committed | Measure-Object -Sum).Sum/1GB,1)

 

What I would like to do is get the disk size for each VMDK.  For example if a VM has 2 x VMDKs on separate datastores, I would like the report to show:

 

datastore1          50Gb

datastore2          30Gb

 

Any ideas please?

"Invoke-VMScript Failed to authenticate with the guest operating system using the supplied credentials." With open-vm-tools, credentials are correct.

$
0
0

Hello, I am trying to use Invoke-VMScript to run a specific command on Linux guest machines.

The command errors with the following output:

Invoke-VMScript : 29-10-2020 12:04:47    Invoke-VMScript 

Failed to authenticate with the guest operating system usin

g the supplied credentials.  

At line:1 char:1

+ Invoke-VMScript -VM <REDACTED HOSTNAME> -ScriptText "sudo /bin/b ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo    

: NotSpecified: (:) [Invoke-VMScript], InvalidGuestLogin

+ FullyQualifiedErrorId : Client20_VmGuestServiceImpl_RunScriptInGuest_ViError,VMware.VimAutomation.ViCore.Cm

   dlets.Commands.InvokeVmScript

 

In the linux host I'm currently trying I see the following in /var/log/audit/audit.log
type=USER_AUTH msg=audit(1603969482.812:4373542): pid=9477 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication grantors=? acct="sa_vmware" exe="/usr/bin/vmtoolsd" hostname=? addr=? terminal=? res=failed'

/var/log/vmware-vmsvc.log shows the following during the login:

[2020-10-29T11:20:18.672Z] [ message] [vix] VixTools_ProcessVixCommand: command 181
[2020-10-29T11:20:20.256Z] [ warning] [VCGA] PAM error: Authentication failure (7), mapped to VGAuth error 12
[2020-10-29T11:20:20.256Z] [ warning] [vix] VixToolsImpersonateUser: impersonation failed (3050)
[2020-10-29T11:20:20.256Z] [ message] [vix] VixToolsCreateTempFileInt: opcode 181 returning 3050
[2020-10-29T11:20:20.256Z] [ message] [vix] ToolsDaemonTcloReceiveVixCommand: command 181, additionalError = 4294967284

 

/etc/pam.d/vmtoolsd  Is the following:
auth       required     pam_shells.so
auth       substack     password-auth
auth       include      postlogin
account    required     pam_nologin.so
account    include      password-auth


with journalctl -xe I see

Oct 29 12:26:59 <REDACTED HOSTNAME> VGAuth[9477]: vmtoolsd: Username and password mismatch for 'sa_vmware'.

I am completely sure the password entered in the command is the same as the user password.

Managing RDM Disks in QE Environment

$
0
0

Hello Folks,

 

I am a QE engineer working with DellEMC PowerMax Storage. We work on SAN environment quite often and provision our storage LUNs to ESXi.

 

Question:

Is there an way to manage (add/remove) RDM disk in bulk ?

 

My UseCases:

- Add 50+ Raw Device Mapping (RDM) Disks to a VM

- Remove 50+ Raw Device Mapping (RDM) disks from a VM

- List Available RDM Disks which are not mapped to any VM yet

- List RDM Disks mapped to a VM

 

From Unisphere GUI, we can only add RDM Disks one by one. I believe there is no support for Bulk add or remove.

We frequently bring down the array and add/delete LUNs from storage backend for our testing. This results in VM being inaccessible or unable to boot once shutdown, since it is not able to reach the stale RDM disks.

 

I did explore for options, Found a command to add 1 RDM disk via PowerCLI. But I was hoping if there is anything like a RDM Disk Manager, something which helps us in quickly Add/Remove RDM disks in bulk to a VM.

 

Can someone please help me here ?

How to run script in Power CLI

$
0
0

I have powershell version 4.0 and Power CLI version 6.5 Release build 4624819. If I run one line command like  "Get-VMHostNetwork -VMHost $esx | Set-VMHostNetwork -DomainName $domainname -DNSAddress $dnspri , $dnsalt -Confirm:$false" it runs ok. But I have to make few change for 100+ servers so I have created below script. But, problem is PowerCLI is not understand the EACH loop or variables. Even if I put some variable in PowerCLI like $Test = I am Arif then , it does not understand what is $Test. I then imported Vmware.PowerCLI module to powershell and same problem there. Can someone pls help me urgently.

 

# PowerCLI Script to Configure DNS and NTP on ESXi Hosts

# PowerCLI Session must be connected to vCenter Server using Connect-VIServer.

 

# Prompt for Primary and Alternate DNS Servers

$dnspri = 1.1.1.1

$dnsalt = 2.2.2.2

 

# Prompt for Domain

$domainname = abc.com

 

#Prompt for NTP Servers

$ntpone = NTP.ABC.COM

$ntptwo = 3.3.3.3

$ntpthree = 4.4.4.4

 

$esxHosts = ESX01.abc.com

 

foreach ($esx in $esxHosts) {

 

   Write-Host "Configuring DNS and Domain Name on $esx" -ForegroundColor Green

   Get-VMHostNetwork -VMHost $esx | Set-VMHostNetwork -DomainName $domainname -DNSAddress $dnspri , $dnsalt -Confirm:$false

 

   

   Write-Host "Configuring NTP Servers on $esx" -ForegroundColor Green

   Add-VMHostNTPServer -NtpServer $ntpone , $ntptwo, $ntpthree -VMHost $esx -Confirm:$false

 

   Writ-Host "Setting up SearchDomain Name"

   Get-VMHost $esx |Get-VMHostNetwork |Set-VMHostNetwork -SearchDomain "autoexpr.com"

 

   Write-Host "Configuring NTP Client Policy on $esx" -ForegroundColor Green

   Get-VMHostService -VMHost $esx | where{$_.Key -eq "ntpd"} | Set-VMHostService -policy "on" -Confirm:$false

 

   Write-Host "Restarting NTP Client on $esx" -ForegroundColor Green

   Get-VMHostService -VMHost $esx | where{$_.Key -eq "ntpd"} | Restart-VMHostService -Confirm:$false

 

}

Write-Host "Done!" -ForegroundColor Green

Change MTU on physical ports without downTime

$
0
0

is there a way to change the MTU for physical NICs [vmnic] without downtime?

 

The issue is that MTU 9000 was enabled on vmkernel and not enabled on physical ports which is not recommended and such kind of configuration impact performance and I'm able to identify a high % of dropped packets

Restart information

$
0
0

Hello,


Can someone please help me to how to find the restart information (Windows servers) such as: Date and time and who performed the task

I can get this last reboot information. But here I am looking the reboot information for past 6 months

is it possible via a script ?


Datacenter migration script from standard to distributed portgroups with the same name

$
0
0

Hello friends,

I'm currently working on trying to migrating virtual machines to a new datacenter. Networks are identical (stretched) in both datacenters but we have to do a svmotion to move between them.

 

I've cobbled together a powercli script from various sources that basically imports today selected VM's through a CSV, then cycles through it while spawning new Move-VM's once the running sessions is under a predefined threshold. But, I'm running into issues with migrating systems that are on standard switches over to distributed switched. Port group names are all identical, so I figured I could just use the name element in the destinations port group. It seems to have worked ok on system with a single nic, but I started running into issues with multiple nics.

 

I ran across an article by Kyle Ruddy - Spotlight on the Move-VM Cmdlet including PowerCLI 6.5 Enhancements that showed you can pipe arrays. I also found an article that LucD was helping on which was more recent, move-vm script placing port groups on wrong adapters for VMs with multiple nics but have still been unable to resolve my issues.

 

Snipped of code for picking the network adapter:

 

      # Pick target port group based on source port group name. Cycle through for multiple network adapters

      $NetworkAdapter=Get-NetworkAdapter-vm$vm

      $targetpg= @()

      $NetworkAdapter.count |foreach-object {

      $targetpg+=Get-VDPortgroup-name$NetworkAdapter.networkname

   }

 

Move VM command:

Move-VM-VM$vm `

      -Destination$DestinationHost `

      -NetworkAdapter$NetworkAdapter `

      -PortGroup$targetpg  `

      -Datastore (Get-DatastoreCluster-Name$DestinationDatastore|Get-Datastore|Sort-Object-PropertyFreeSpaceGB-Descending|Select-First1) `

      -RunAsync-Confirm:$false

 

But when I am currently getting the following error:

 

Move-VM : 10/31/2020 2:12:56 PM Move-VM A specified parameter was not correct: RelocateSpec

At line:1 char:1

+ Move-VM -VM $vm `

+ ~~~~~~~~~~~~~~~~~

+ CategoryInfo          : NotSpecified: (:) [Move-VM], VimException

+ FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.MoveVM

 

I tried using the sdk method but never could get it to work with standard switch moves. 

 

Any insight or help would be much appreciated. Thanks!!

DistributedVirtualSwitchInfo with id 'xxx' does not exist

$
0
0

Hello there.

 

I am trying to create vmk intarfaces with New-VMHostNetworkAdapter cmlet, but gettin the error "DistributedVirtualSwitchInfo with id 50 02 5a 5c 8c fc 30 be-15 99 73 74 7d 87 b7 37' does not exist."

I've tried to specify vDS name in the cmdlet, tried to specify the variable, in which the switch object was stored (the result of Get-VirtualSwitch and Get-VDSwitch cmdlets), but still no luck.

 

Furthermore, the vDS key is the same, vCenter is complaining about:

 

PS C:\Windows\system32> $vswitch.key

50 02 5a 5c 8c fc 30 be-15 99 73 74 7d 87 b7 37

 

What is the problem?

use Get-VDPortgroup cmdlet in the VDS component

$
0
0

Hello

 

I'm using the below script to get VDS Port Group it's working fine but I'm getting the warring message:

 

WARNING: The output of the command produced distributed virtual portgroup objects. This behavior is obsolete and may change in the future. To retrieve distributed portgroups, use Get-VDPortgroup cmdlet in the VDS component. To retrieve standard portgroups, use -Standard.

 

I would like to understand why I'm getting this warrning and how I car relidiate using the similar way used in my script?

 

Get-VMHost -PipelineVariable ESX | Get-VirtualPortGroup | Select-Object @{N='VMHost';E={$esx.Name}},VirtualSwitch,Name,VlanId | Out-String | ForEach-Object { $_.Trim() } > ".\VDSportGroup.txt"

#Verify if VlanID is set to 0 or 1, if so, then Check Get-VirtualPortGroup-Config.txt

$CheckVlanID = (Get-Content .\VDSportGroup.txt | Format-Table VlanId | findstr /v " _$Null VlanId ----- _$Null") | where-object {$_ -like '*0*' -like '*1*'} | ForEach-Object{$_.split(".")[0]}

function VDSPort{

        if ($Null -eq $CheckVlanID) {

            Write-Log -StartTab 1 -LinesBefore 1 -Level Success -Message "All Hosts have VlanID configured with value between 2 and 4094 " -FilePath $LogFile

            }

        else {

            Write-Host -f red "Hosts with wrong VlanID detected"

            Write-Log -StartTab 1 -LinesBefore 1 -Level Success -Message "Check Get-VirtualPortGroup-Config file for host(s) $CheckVlanID" -FilePath $LogFile

            }

}

VDSPort

Template Update Script Not Finishing

$
0
0

I have a script that takes a template and converts it, updates the windows, then converts it back.  Script works great with Win2016 & 2019, but I had to make a win10 template and it won't convert it back.  Looking at it and I think the problem is that the VM will not start vmtools until someone logs into it and the script is designed to turn off the vm once it sees the tools are initialized.  I don't know what's going on in Window's world that makes this fail but unless I can find a magic wand to make it work I am thinking about making the script just ignore that and continue on.

 

Script:

 

#Update Template Parameters

 

    #Update Template Name

    $updateTempName = "TempWin10"

 

#---------------------

#Update Template

#---------------------

 

try {

    #Get Template

    $template = Get-Template $updateTempName

 

    #Convert Template to VM

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Converting Template: $($updateTempName) to VM" -PercentComplete 5 }

    [void]$log.appendline("Converting Template: $($updateTempName) to VM")

    $template | Set-Template -ToVM -Confirm:$false

 

    #Start VM

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Starting VM: $($updateTempName)" -PercentComplete 20 }

    [void]$log.appendline("Starting VM: $($updateTempName)")

    Get-VM $updateTempName | Start-VM -RunAsync:$RunAsync

 

    #Wait for VMware Tools to start

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Giving VM: $($updateTempName) 3200 seconds to start VMwareTools" -PercentComplete 35 }

    [void]$log.appendline("Giving VM: $($updateTempName) 3200 seconds to start VMwareTools")

    sleep 90

 

    #VM Local Account Credentials for Script

    $cred = New-Object System.Management.Automation.PSCredential $updateTempUser, $updateTempPass

 

    #Script to run on VM

    $script = "Function WSUSUpdate {

          param ( [switch]`$rebootIfNecessary,

                  [switch]`$forceReboot) 

        `$Criteria = ""IsInstalled=0 and Type='Software'""

        `$Searcher = New-Object -ComObject Microsoft.Update.Searcher

        try {

            `$SearchResult = `$Searcher.Search(`$Criteria).Updates

            if (`$SearchResult.Count -eq 0) {

                Write-Output ""There are no applicable updates.""

                exit

            }

            else {

                `$Session = New-Object -ComObject Microsoft.Update.Session

                `$Downloader = `$Session.CreateUpdateDownloader()

                `$Downloader.Updates = `$SearchResult

                `$Downloader.Download()

                `$Installer = New-Object -ComObject Microsoft.Update.Installer

                `$Installer.Updates = `$SearchResult

                `$Result = `$Installer.Install()

            }

        }

        catch {

            Write-Output ""There are no applicable updates.""

        }

        If(`$rebootIfNecessary.IsPresent) { If (`$Result.rebootRequired) { Restart-Computer -Force} }

        If(`$forceReboot.IsPresent) { Restart-Computer -Force }

    }

    WSUSUpdate -rebootIfNecessary

    "

   

    #Running Script on Guest VM

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Running Script on Guest VM: $($updateTempName)" -PercentComplete 50 }

    [void]$log.appendline("Running Script on Guest VM: $($updateTempName)")

    Get-VM $updateTempName | Invoke-VMScript -ScriptText $script -GuestCredential $cred

   

    #Wait for Windows Updates to finish after reboot

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Giving VM: $($updateTempName) 3200 seconds to finish rebooting after Windows Update" -PercentComplete 65 }

    [void]$log.appendline("Giving VM: $($updateTempName) 3200 seconds to finish rebooting after Windows Update")

    sleep 3200

 

    #Shutdown the VM

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Shutting Down VM: $($updateTempName)" -PercentComplete 80 }

    [void]$log.appendline("Shutting Down VM: $($updateTempName)")

    Get-VM $updateTempName | Stop-VMGuest -Confirm:$false

 

    #Wait for shutdown to finish

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Giving VM: $($updateTempName) 3200 seconds to finish Shutting Down" -PercentComplete 90 }

    [void]$log.appendline("Giving VM: $($updateTempName) 3200 seconds to finish Shutting Down")

    sleep 3200

   

    #Convert VM back to Template

    if($showProgress) { Write-Progress -Activity "Update Template" -Status "Convert VM: $($updateTempName) back to template" -PercentComplete 100 }

    [void]$log.appendline("Convert VM: $($updateTempName) back to template")

    Get-VM $updateTempName | Set-VM -ToTemplate -Confirm:$false

}

catch {

    [void]$log.appendline("Error:")

    [void]$log.appendline($error)

    Throw $error

    #stops post-update copy of template

    $updateError = $true

    }

#---------------------

#End of Update Template

#---------------------

Exclude a group of VMs in a get-filter regex

$
0
0

Hi. I am having issues excluding a group of VMs from a regex expression in a get-filter. I won't bore everyone and list everything I tried, which has exhausted me. Essentially I am using this call Get-View -ViewType "VirtualMachine" -Filter @{'Name'=???} and I am trying simply trying to find an expression that will get all VMs except say VMs that start with test* or dev* and such. I just cant get any expression to work. Thanks,,,

find VM that was deleted from vcenter

$
0
0

Trying to find a VM that was deleted from vcenter. Probablyt last 2 weeks

 

 

is this right?

 

Get-VIEvent-maxsamples ([int]::MaxValue) -Start (Get-Date).AddDays(–14) | where{$_-is[VMware.Vim.VmRemovedEvent]}

 

?

Invoke-VMScript Response status code does not indicate success: 403 (Forbidden)

$
0
0

Hi,

 

Hope you're all well.

 

I am using Invoke-VMScript to interact with Windows VMs.

 

Something strange is happening. On my Windows 10 machine every time I do an invoke-vmscript, it carries out the script successfully on the VM, but it does not ever bring back a success message or the correct output.

It only says "Invoke-VMScript Response status code does not indicate success: 403 (Forbidden)." Although the script runs as expected on the VM I am never given feedback from PowerShell of the output.

 

However, if I try the same things on Windows Server 2016 machine, the output comes back successfully.

 

Know what's wrong?

 

vSphere Client version 6.7.0.42000

 

VMware.CloudServices                    12.1.0.17002793

VMware.DeployAutomation                 7.0.0.15902843

VMware.ImageBuilder                     7.0.0.15902843

VMware.PowerCLI                         12.1.0.17009493

VMware.Vim                              7.0.1.16997275

VMware.VimAutomation.Cis.Core           12.1.0.16997582

VMware.VimAutomation.Cloud              12.0.0.15940183

VMware.VimAutomation.Common             12.1.0.16997174

VMware.VimAutomation.Core               12.1.0.16997984

VMware.VimAutomation.Hcx                12.1.0.17002966

VMware.VimAutomation.HorizonView        7.13.0.16985899

VMware.VimAutomation.License            12.0.0.15939670

VMware.VimAutomation.Nsxt               12.0.0.15939671

VMware.VimAutomation.Sdk                12.1.0.16997004

VMware.VimAutomation.Security           12.1.0.17009513

VMware.VimAutomation.Srm                12.1.0.17002371

VMware.VimAutomation.Storage            12.1.0.17001270

VMware.VimAutomation.StorageUtility     1.6.0.0      

VMware.VimAutomation.Vds                12.1.0.17001377

VMware.VimAutomation.Vmc                12.1.0.17008354

VMware.VimAutomation.vROps              12.0.0.15940184

VMware.VimAutomation.WorkloadManagement 12.1.0.17003628

VMware.VumAutomation                    12.1.0.16941488


Update VM template (non domain joined)

Convert 500+ thick disks to Thin

$
0
0

Hi,

 

I need a script which can covert thick disks to Thin, requirement is aa below.

 

1. Get VM name/Thick disks list, source datastore  and destination datastore from CSV file.

2. Move only the thick disks from the above VMs to destination data store by changing the provision type to thin.

3. Post that it has to migrate back the disk to source datastore.

Script has to run one after one.

 

I need your help to complete the above task. Kindly do the needful.

 

Best regards,

Sai Krishna

IMM Ip Address through PowerCLI

$
0
0

hello

 

I am exeucting following line from https://www.altaro.com/vmware/esxi-ilo-idrac-powercli/

Get-VMHostWSManInstance –Vmhost (Get-VMhost ESX01.tglab.lcl) –IgnoreCertFailures –Class OMC_IPMIIPProtocolEndpoint

 

but I am getting winrm error message

Get-WSManInstance : The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests. Consult the

logs and documentation for the WS-Management service running on the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the

destination to analyze and configure the WinRM service: "winrm quickconfig".

At line:3 char:1

+ Get-WSManInstance -ConnectionURI ("https`://" + $h.Name + "/wsman") - ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (:) [Get-WSManInstance], COMException

    + FullyQualifiedErrorId : Exception,Microsoft.WSMan.Management.GetWSManInstanceCommand

 

 

 

i can able to see wsman is enabled and service is started in esxi what could be issue? 

powercli Get-Task output language

$
0
0

I want to change the output(TaskName) language

Is a way to extract installed softwares and version for auditory with PowerCLI?

$
0
0

Hello,

         I have an audit. I need to extract for each vm an installed softwares and I don't know if exist a way through vmware cli.

 

Thanks and regards,

Tomás

SCSIcanonicalname?

$
0
0

Hi,

 

I am using the following script to keep track of RDMs in relation to migrations.

 

$DiskInfo= @()

$vm = Get-Cluster "CLUSTERNAME" | Get-VM

 

foreach ($VMview in Get-VM $vm | Get-View)

{

foreach ($VirtualSCSIController in ($VMView.Config.Hardware.Device | where {$_.DeviceInfo.Label -match "SCSI Controller"})) {

foreach ($VirtualDiskDevice in ($VMView.Config.Hardware.Device | where {$_.ControllerKey -eq $VirtualSCSIController.Key})) {

$VirtualDisk = "" | Select VMname, SCSIController, SCSI_ID, DiskName, DeviceName, DiskFile, DiskSize, type

$VirtualDisk.VMname = $VMview.Name

$VirtualDisk.SCSIController = $VirtualSCSIController.DeviceInfo.Label

$VirtualDisk.DiskName = $VirtualDiskDevice.DeviceInfo.Label

$VirtualDisk.SCSI_ID = "$($VirtualSCSIController.BusNumber) : $($VirtualDiskDevice.UnitNumber)"

$VirtualDisk.DeviceName = $VirtualDiskDevice.Backing.DeviceName

$VirtualDisk.DiskFile = $VirtualDiskDevice.Backing.FileName

$VirtualDisk.DiskSize = $VirtualDiskDevice.CapacityInKB * 1KB / 1GB

$DiskInfo += $VirtualDisk

}}}

$DiskInfo | sort VMname, Diskname | Out-GridView

 

Is there a way to add SCSI canonical name to this?

 

I am trying to wrap my head around calling these methods, is there a guide or comprehensive reference somewhere?

DNS

$
0
0

Hello,

 

Can someone please tell me:

 

I have a text file called 'Server_IP' and in that sheet it has all the IPs.

Is there anyway I can script and get the DNS names by doing nslookup of that IPs and get the result in excel sheet (Can save it in D drvie) like below:

 

(Column A)     (Column B)

Server IP         Server Name






Latest Images