Quantcast
Channel: VMware Communities : All Content - VMware PowerCLI
Viewing all 16717 articles
Browse latest View live

Filtering using where-object and variable

$
0
0

Hi!

 

I want to filter my DRS rules using some specific parameters, the problem that i have is that when using the cmdlet "where-object' it doesn't filter anything.

 

All my DRS rules in cluster are composed like this:

 

exposition_cpd_VM_category_ = internet_london_VM_gold

 

 

$clusters= "Get-Cluster"

 

 

foreach($cluster in $clusters)

{

$log= Get-Cluster $cluster |Get-DrsRule |Where-Object {$_.Name -like *$exposition_$cpd_VM_$category_} | Select Name,Enabled,Type

Write-Host $log

}

 

Anyone can help me?

 

Best regards


display 2 annotations and their values

$
0
0

I run this and get one value, can I do similar and get 2?
get-vm|where-object {$_.powerstate -eq "poweredon"}|get-annotation -customattribute "location"|ft -auto

This returns something like this:

AnnotatedEntity        Name              Value
--------------------         ---------             -----------

server1                      location           data center

 

Sometimes I would like:

AnnotatedEntity        Name              Value                    Name                    Value    
--------------------         ---------             -----------                -----------                 ----------

server1                      location           data center           Host                      host13

 

I see that if I wildcard the -customattribute I get them all, so can I do less than all of them, and more than 1?

Need help on my snapshot script

$
0
0

Hi Guys,

Need help on adjusting my script below,

Still could not figure out how to,

  • make the html report to show on each vcenters that has snapshot and show this as content in email
  • how to retrieve creator of the snapshot and put in another column as what i have currently(currently i only have VM,Name,Description, Size, Created(date))?
  • how to mark the row of VM that has snapshot more than 72 hours with red color background?

 

vcenter A

VMNameDescriptionSizeCreated

 

vcenter B

VMNameDescriptionSizeCreated

 

vcenter C

VMNameDescriptionSizeCreated

Add-PSSnapin VMware.VimAutomation.Core -ErrorAction 'SilentlyContinue'

 

 

#parameters

$currentdate = (Get-Date).tostring("dd-MM-yyyy")

$VIServer = Get-Content -Path C:\Batch\Scripts\snapshots\vcenters.txt

$outputfilename = 'snapshot-report_' + $currentdate + '.html'

$outputfilepath = 'C:\scripts\Output\' + $outfilename

 

 

Write-Host "Connecting to VCenters" -ForegroundColor Yellow

Connect-VIServer $VIServer -wa 0

Write-Host "   Complete" -ForegroundColor Green

 

 

#Format of HTML table via the ConvertTo-HTML cmdlet

 

 

$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>

"@

 

 

 

 

# Main section

Write-Host "Getting Snapshot" -ForegroundColor Yellow

$Report = Get-VM | Get-Snapshot | Select VM,Name,Description,@{Label="Size";Expression={"{0:N2} GB" -f ($_.SizeGB)}},Created

If (-not $Report)

{  $Report = New-Object PSObject -Property @{

      VM = "No snapshots found on any VM's controlled by $VIServer"

      Name = ""

      Description = ""

      Size = ""

      Created = ""

   }

}

 

 

Write-Host "   Complete" -ForegroundColor Green

#$Report = $Report | Select VM,Name,Description,Size,Created | ConvertTo-Html -Head $Header -PreContent "<p><h2>Snapshot Report - $VIServer</h2></p><br>" | Set-AlternatingRows -CSSEvenClass even -CSSOddClass odd

 

 

$Report = $Report |

    Select VM,Name,Description,Size,Created |

    ConvertTo-Html -Head $Header -PreContent "<p><h2>Snapshot Report - $VIServer</h2></p><br>"

 

 

$smtpServer= 'a@abc.local'

$smtpSubject= 'VM snapshots report ' + $currentdate

$to= 'am@abc.com'

$from= 'vmteam@abc.com'

$ebody = ($Report | Out-String)

 

 

Write-Host "Sending Email" -ForegroundColor Yellow

 

 

#Try to send email

Send-MailMessage -To $to -From $from -Subject $smtpSubject -Body $ebody -BodyAsHtml -SmtpServer $smtpServer

 

 

Write-Host "   Complete" -ForegroundColor Green 

How to Get PARENT VM details from powerCLI using VMware.HV.Helper module?

$
0
0

I'm trying to understand how I can query a pool name and obtain the PARENT VM information for the pool.


Is that information gathered via one of these functions?:  Get-HVPool, Get-HVPoolSpec, Or Get-HVPoolSummary.  

 

Thank you

shutdown vm and wait till it is powered off and make changes

$
0
0

I am having trouble getting the system to shutdown and wait till it is actually in a state to make changes. I get errors  "the system is not a state... "
I think the issue is there is a delay from when the system shuts down to when you can actually make a change, such as number of processors.

Is there a better way than what I am trying below?

 

 

Get-VM -name $VMName* | Shutdown-VMGuest -Confirm:$false

if ($VMName.PowerState -eq "PoweredOn") {

   Write-Host "Shutting Down" $VMName

   Shutdown-VMGuest -VM $VMName

   #Wait for Shutdown to complete

   do {

      #Wait 5 seconds

      Start-Sleep -s 5

      $status = $VMName.PowerState

   }until($status -eq "PoweredOff")

}

VDS network port change

"Operation is not valid due to the current state of the object" during OVF configuration

$
0
0

Hello All,

 

I'm trying to deploy A10 Networks vThunder OVF through PowerCLI and facing some problem:

 

PowerCLI C:\> $ovfConfig.Common.eth1.label = "Data 1"

Operation is not valid due to the current state of the object.

At line:1 char:1

+ $ovfConfig.Common.eth1.label = "Data 1"

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

    + CategoryInfo          : OperationStopped: (:) [], InvalidOperationExcept

   ion

    + FullyQualifiedErrorId : System.InvalidOperationException

 

Unable to understand why this is happening. Could someone be able to point me in right direction?

 

-Subeh

PowerCLI command to fetch Portgroups created on vCenter

$
0
0

I'm trying to find a command using which i can fetch the list of portgroups created on DVS but unable to find. I could see the same one for listing the datastores:

 

PowerCLI C:\> get-datastore

 

 

Name                               FreeSpaceGB      CapacityGB

----                               -----------      ----------

datastore1121_1                        462.171       1,858.000

datastore1121_2                        669.733         931.250

datastore1121_3                        586.775         931.250

datastore1122_2                        593.934         924.000

datastore1122_3                      1,045.293       1,862.750

datastore1122_4                        461.737         931.250

 

Can someone please help me out with the similar command for fetching portgroups and how to use them while deploying a VM from OVF using powerCLI?


Unable to change the DNS for VM

$
0
0

Hi,

 

Please help with the below script as I am not able to change the DNS for VMs. I am able to change the network but, unable to update the DNS

 

Please help

 

$username = 'locadmin'

$password = 'pass@123'

 

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword

 

Connect-VIServer 192.168.1.100

 

$file = "C:\clients_mgmt.txt"

$vms = Get-Content $file

 

Get-VM $vms | Get-NetworkAdapter | Set-NetworkAdapter -NetworkName br1200 -Confirm:$false

 

ForEach ($vm in $vms) {

    Write-Host "$($vm.Name): " -ForegroundColor Yellow

    Invoke-Command -ComputerName $vm.Name -Credential $credential -ScriptBlock {

        $NewDnsServerSearchOrder = "192.168.1.13","192.168.1.14"

        $Adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -ne 'True' -and $_.DNSServerSearchOrder -ne $null}

       

        # Show DNS servers before update

        Write-Host "Before: " -ForegroundColor Green

        $Adapters | ForEach-Object {$_.DNSServerSearchOrder}

 

        # Update DNS servers

        $Adapters | ForEach-Object {$_.SetDNSServerSearchOrder($NewDnsServerSearchOrder)} | Out-Null

 

        # Show DNS servers after update

        $Adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DHCPEnabled -ne 'True' -and $_.DNSServerSearchOrder -ne $null}

        Write-Host "After: " -ForegroundColor Green

        $Adapters | ForEach-Object {$_.DNSServerSearchOrder}

    }

}

Automatic Detection of OS Reboot

$
0
0

Because of Spectre/Meltdown Mitigation we have to Upgrade the HW Version of many VMs.

There are different methods and it could also be done with PowerCLI:http://www.running-system.com/powercli-script-schedule-vms-to-upgrade-the-virtual-hardware-at-the-next-reboot/

To present the new CPU features to the virtual machine, the VM must be HW Version >=9 and there must be a cold boot(os reboot is not sufficent).

If I schedule the vm upgrade at next reboot(Web Client or powercli) the CPU features are visable after HW Upgrade without another reboot ! So the command used has to detect an os reboot, Upgrade HW and does a cold boot ?

 

We also have a lot of VMs that are alread HW Version 11. So only a cold boot is neccesary to present new cpu features. We want to combine it with os reboot after Windows patching.

Is there a possibility with powercli to detect a OS reboot, power off VM and then power on again ?

How do i get MAC address and IP in a format i can use in a script

$
0
0


Hi

 

I want to collect the IP and MAC from a specific MV for use elsewhere.

 

The 2 queries i have are

 

Get-VM $VMname | Get-NetworkAdapter | selectMacAddress

 

Get-VM $VMname | Select @{N=”IP Address”;E={@($_.guest.IPAddress[0])}}

 

They both return a header and the value

 

IP Address

----------

10.38.96.82

 

I just want the value that i can stick in a variable for use elsewhere - like so

 

$VMmac = (Get-VM $VMname | Get-NetworkAdapter | selectMacAddress )

 

What simple thing am i missing?

 

Assistance much appreciated

Exception has been thrown by the target of an invocation (vCenter login)

$
0
0

Hi,

 

I have a problem while logging in from VMWare.vim (PowerCLi) to vCenter.

I am connecting from the server to many vCenters and the problem appears by some of these servers NOT ALL.

 

my C# Code after I've loaded the VMWare.vim.dll looks :

 

 

Type vimType = Assembly.GetType("VMware.Vim.VimClient");
object vmc = System.Activator.CreateInstance(vimType);
vmc.GetType().InvokeMember("Connect", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, vmc, new object[] { serviceUrl });
vmc.GetType().InvokeMember("Login", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, vmc, new object[] { login, password });

 

I am facing this Error like I saied with some of the vCenters:

"Exception has been thrown by the target of an invocation"  , the error appears at line 4 of my code, I mean while connecting to the server is everything perfect, while logging in appears the error.

 

PowerCLI 6.5 is in use and .Net Framework 4.5.

 

thnx in advanced,

vcsa 6.5 trying to automate the backup - authentication failure

$
0
0

Hello

 

I tried to make the Backup-VCSAToFile work in my development environment.

 

vSphere 6.5 – Automate VCSA Backup » Brian Graf's Virtualization Blog

 

I'm stuck here:

A server error occurred: 'com.vmware.vapi.std.errors.unauthorized': Unable to authorize user (Server error id:

'vapi.security.authorization.invalid'). Check $Error[0].Exception.ServerError for more details.

In Zeile:1 Zeichen:1

 

What did I do?

Windows 7 VM, installed VMware Powershell 6.5

Started ISE

 

loaded modules

Import-Module VMware.VimAutomation.Core

Import-Module VMware.VimAutomation.Vds

Import-Module VMware.VimAutomation.Cloud

Import-Module VMware.VimAutomation.PCloud

Import-Module VMware.VimAutomation.Cis.Core

Import-Module VMware.VimAutomation.Storage

Import-Module VMware.VimAutomation.HorizonView

Import-Module VMware.VimAutomation.HA

Import-Module VMware.VimAutomation.vROps

Import-Module VMware.VumAutomation

Import-Module VMware.DeployAutomation

Import-Module VMware.ImageBuilder

Import-Module VMware.VimAutomation.License

 

loaded the script itself as module (necessary?)

 

connected to vcsa with connect-viserver

 

Used given example in the script with my parameters.

 

Then I get a pop up

(Connection to CisServer)

 

I don't know what that is.

 

If I use my credentials for the vCenter connection - AD authentication, I get that error

 

Backup-VCSAToFile:Aservererroroccurred:'com.vmware.vapi.std.errors.unauthorized':Unabletoauthorizeuser (Servererrorid:

'vapi.security.authorization.invalid').Check$Error[0].Exception.ServerError formoredetails.

InZeile:1Zeichen:1

 

 

Any hints?

Windows server 2012 r2 os customization is not working

$
0
0

Hi,

 

I am automating the OS deployment using VM template and OS customization spec. It deploys the VM but after a final power on Windows server 2012 r2 shows an error that installation got corrupt.

 

Refer the below error and the script.

 

Script:

--------------------------------------------------------

<#

.SYNOPSIS

   Script automates deployment of multiple vms loaded from pre-defined .csv file

.DESCRIPTION

   Script reads the .csv file, deploys vms from template, applies os customization spec then attempts to set up IP configuration

.PARAMETER

   none

.EXAMPLE

   trivia

#>

 

#variables

$ScriptRoot = Split-Path $MyInvocation.MyCommand.Path

$csvfile = "$ScriptRoot\vms.csv"

$vcenter_srv = 'homwpvs01.ad.bgep.co.uk'

$timeout = 180

$loop_control = 0

 

$vmsnapin = Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue

$Error.Clear()

if ($vmsnapin -eq $null)    

    {

    Add-PSSnapin VMware.VimAutomation.Core

    if ($error.Count -eq 0)

        {

        write-host "PowerCLI VimAutomation.Core Snap-in was successfully enabled." -ForegroundColor Green

        }

    else

        {

        write-host "ERROR: Could not enable PowerCLI VimAutomation.Core Snap-in, exiting script" -ForegroundColor Red

        Exit

        }

    }

else

    {

    Write-Host "PowerCLI VimAutomation.Core Snap-in is already enabled" -ForegroundColor Green

    }

 

# 32-bit PowerCLI is required to run *-OSCustomizationSpec cmdlets

if ($env:Processor_Architecture -eq "x86") {

 

    #Connect to vCenter

    Connect-VIServer -Server $vcenter_srv

 

    $vms2deploy = Import-Csv -Path $csvfile

   

    #deploy vms as per information in each line, wait for customization (a reboot) then wait for vmware tools to change ip settings

    foreach ($vm in $vms2deploy) {

       

        #validate input, at least vm name, template name and OS Customization Spec name should be provided

        if (($vm.name -ne "") -and ($vm.template -ne "") -and ($vm.oscust -ne "")){

           

            #check if vm with this name already exists (some funny results are produced once we deploy vm with duplicate name)

            if (!(get-vm $vm.Name -erroraction 0)){

                $vmhost = get-cluster $vm.cluster | get-vmhost -state connected | Get-Random

               

                #check if we want to attempt IP configuration, if "none" is written in .csv file (because we use DHCP for example) we deploy immediately, otherwise we insert IP into CustomizationSpec, then deploy

                if ($vm.ip -match ‘none’){

                    Write-Host "No IP configuration in .csv file, moving on" -ForegroundColor Yellow

                    write-Host "Deploying VM $($vm.name) to datastore cluster $.($vm.datastore-cluster)"

                       new-vm -name $vm.name -template $(get-template -name $vm.template) -vmhost $vmhost -oscustomizationspec $(get-oscustomizationspec -name $vm.oscust) -datastore $(get-datastorecluster -name $vm.datastore-cluster) -location $(get-folder -name $vm.folder) | Out-Null

                }

                else {

                   

                    #clone the "master" OS Customization Spec, then use it to apply vm specific IP configuration

                    $cloned_oscust = Get-OSCustomizationSpec $vm.oscust | New-OSCustomizationSpec -name "$($vm.oscust)_$($vm.name)"

                   

                    Set-OSCustomizationNicMapping -OSCustomizationNicMapping ($cloned_oscust | Get-OscustomizationNicMapping) -Position 1 -IpMode UseStaticIp -IpAddress $vm.ip -SubnetMask $vm.mask -DefaultGateway $vm.gw -Dns $vm.dns1,$vm.dns2 | Out-Null

                    write-Host "Deploying VM $($vm.name) to datastore cluster $($vm.datastore)"

                       new-vm -name $vm.name -template $(get-template -name $vm.template) -vmhost $vmhost -oscustomizationspec $cloned_oscust -datastore $(get-datastore -name $vm.datastore) -location $(get-folder -name $vm.folder) | Out-Null

                }

               

                #this is where we try to track deployment progress

                $loop_control = 0

                write-host "Starting VM $($vm.name)"

                Start-Sleep 300

                start-vm -vm $vm.name -confirm:$false | Out-Null

 

                write-host "Waiting for first boot of $($vm.name)" -ForegroundColor Yellow

                do {

                    $toolsStatus = (Get-VM -name $vm.name).extensiondata.Guest.ToolsStatus

                    Start-Sleep 3

                    $loop_control++

                } until ( ($toolsStatus -match ‘toolsOk’) -or ($loop_control -gt $timeout) )

 

                #wait another minute "just in case" feel free to remove this line

                Start-Sleep 60

               

                #clean-up the cloned OS Customization spec

                Remove-OSCustomizationSpec -CustomizationSpec $cloned_oscust -Confirm:$false | Out-Null

               

                if ($loop_control -gt $timeout){

                    Write-Host "Deployment of $($vm.name) took more than $($timeout/20) minutes, check if everything OK" -ForegroundColor red

                }

                else {

                Write-Host "$($vm.name) successfully deployed, moving on" -ForegroundColor Green

                }

            }

            else {

                Write-Host "$($vm.name) already exists, moving on" -ForegroundColor Red

            }

        }

        else {

            Write-Host "Check input file $csvfile for line with empty vm, template or OS customization spec value" -ForegroundColor Red

        }

    }

 

    Write-Host "All vms deployed, exiting" -ForegroundColor Green

    #disconnect vCenter

    Disconnect-VIServer -Confirm:$false

}

else {

Write-Host "This script should be run from 32-bit version of PowerCLI only, Open 32-bit PowerCLI window and start again" -ForegroundColor Red

}

-----------------------------------------------------------------------------------------------------

 

 

 

How to Disable / Enable a VM's Network Adapter DirectPath I/O Parameter

$
0
0

Hi!

 

 

There are examples on the internet on how to get this setting, like

 

(Get-VM -Name "a-vm-name" | Get-NetworkAdapter).ExtensionData.UptCompatibilityEnabled

 

but there is none on how to set it. I know I could use Onyx but my vCenter has overtaken it (6.0 --> 6.5). Maybe I can get a quicker answer here...

 

 

 

Thanks

Gregor


Input csv File to PowerCLI Script and Retain all Data

$
0
0

I have a powerCLI script that does the following:

 

Imports a csv (vmlist.csv) that looks like this:

 

VMnameDatacenterOwner
vm1parisjohn
vm2londonjim
vm3new yorkjoe

 

 

then I import the csv and add the CPU count as an additional row.  The problem is that multiple providers of input files provide info with different additional column names that all need to be preserved in the final output file.  The additional columns could be different based on the source and there could be any number of new columns with new data  in them in each new input file, all which need to be preserved in the output file.

 

How can I create a report that both adds a "NumCPU" column to the csv, and PRESERVES any other columns that are in the input file, and creates a new .csv with all the original data plus the numcpu count?

error while I run .ps script

$
0
0

I migrated from PowerCLI 6.3 to latest (10.11) in Windows 2012.

I create test.ps script but when I run it I got:

 

C:\Windows\System32\WindowsPowerShell\v1.0\powersell.exe -noe -c ". \"C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\" $true". : The term 'C:\Program Files (x86)\VMware\Infrastructure\vSpherePowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

At line:1 char:3

+ . "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scri ...

                                        

As if There was link to Initialize-PowerCLIEnvironmet.ps1 file but I'm not able to understand where is it?

 

This happens only if I click on script because if I open manually powershell by Windows link and I run command there is no problem, but I lost automatically mechanism!

 

Suggestions please?

How to trace a VM disk to a guest disk.

$
0
0

How to trace a VM disk to a guest disk

 

No voodoo involved.  If you’re a Linux person then the mechanics of this process should work for you also.  For Windows people I'll include some PowerShell code that should work in Server 2008 and later (requires PowerCLI, and uses WMI).

 

How to trace a disk:

  • IF THE DISK IS NOT a physical mode RDM then simply match the ddb.uuid (virtual disk uuid) of the vmdk to the disk serial number seen in the guest OS.  To get the virtual disk uuid in PowerShell you can call the queryvirtualdiskuuid method of the VirtualDiskManager managed object (example in code).  If you’re not an administrator in VMware then you’ll need System.View privilege, and on every datastore with a disk you want to inspect you’ll need the Datastore.FileManagement privilege.

 

  • IF THE DISK IS a physical mode RDM then it’s a little trickier but not bad.  In this case the disk serial reported in the guest should display the LUN serial number from the array - NOT the virtual disk uuid of the RDM vmdk.  For these you need to try to match the disk serial of the guest with the last 24 characters of the ScsiCanonicalName of the VM hard disk.  This may or may not be a 1-step process.  The environment where I do things is hosted on NetApp storage, and the LUN serial number from NetApp arrays is in ASCII, so in order to match to the ScsiCanonicalName the LUN serial number first needs to be converted to HEX.  Not sure how other storage vendors are formatting their LUN serial numbers so you may need to tweak.  I’ve coded the script below to hopefully work if you’re on some other array vendor and they either A) use a 12-character ASCII LUN serial number, or B) present a 24-chracter HEX LUN serial number.

 

Works great in my environment but certainly not claiming it will work everywhere.  What I know for sure:

  1. Works on Windows VMs with between 1 and 4 SCSI adapters.  (Based on the methodology # SCSI adapters should not matter, nor should their model.)
  2. Works with physical mode RDM disks presented from NetApp storage.  (Never tried with virtual mode but don't they should work, possibly minor adjustments required.)
  3. 2003 servers don’t work because the Win32_DiskDrive class of WMI didn't provide a SerialNumber property in that version (probably solvable if you must).
  4. If anything exists in the guest that masks the disk serial number then this will not work.
  5. This won't work somewhere and probably lots of places.  Interested to hear your stories either way.

 

This code is just hacked together.  No error handling - if it bombs it bombs.  Just connect to your VI server (script does NOT do this) and edit $vmName to match the server you want to check.

 

Enjoy

 

 

$vmName = "cheezburger"
## modification below here not necessary to run ##


#get windows disks via wmi
$cred = if ($cred){$cred}else{Get-Credential}
$win32DiskDrive  = Get-WmiObject -Class Win32_DiskDrive -ComputerName $vmName -Credential $cred

#get vm hard disks and vm datacenter and virtual disk manager via PowerCLI
#does not connect to a vi server for you!  you should already be connected to the appropraite vi server.
$vmHardDisks = Get-VM -Name $vmName | Get-HardDisk
$vmDatacenterView = Get-VM -Name $vmName | Get-Datacenter | Get-View
$virtualDiskManager = Get-View -Id VirtualDiskManager-virtualDiskManager

#iterates through each windows disk and assign an alternate disk serial number value if not a vmware disk model
#required to handle physical mode RDMs, otherwise this should not be needed
foreach ($disk in $win32DiskDrive)
{
  #add a AltSerialNumber NoteProperty and grab the disk serial number  $disk | Add-Member -MemberType NoteProperty -Name AltSerialNumber -Value $null  $diskSerialNumber = $disk.SerialNumber    #if disk is not a VMware disk set the AltSerialNumber property  if ($disk.Model -notmatch 'VMware Virtual disk SCSI Disk Device')  {    #if disk serial number is 12 characters convert it to hex    if ($diskSerialNumber -match '^\S{12}$')    {      $diskSerialNumber = ($diskSerialNumber | foreach {[byte[]]$bytes = $_.ToCharArray(); $bytes | foreach {$_.ToString('x2')} }  ) -join ''    }    $disk.AltSerialNumber = $diskSerialNumber  }
}

#iterate through each vm hard disk and try to correlate it to a windows disk
#and generate some results!
$results = @()
foreach ($vmHardDisk in $vmHardDisks)
{
  #get uuid of vm hard disk / and remove spaces and dashes  $vmHardDiskUuid = $virtualDiskManager.queryvirtualdiskuuid($vmHardDisk.Filename, $vmDatacenterView.MoRef) | foreach {$_.replace(' ','').replace('-','')}    #match vm hard disk uuid to windows disk serial number  $windowsDisk = $win32DiskDrive | where {$_.SerialNumber -eq $vmHardDiskUuid}    #if windowsDisk not found then try to match the vm hard disk ScsiCanonicalName to the AltSerialNumber set previously  if (-not $windowsDisk)  {    $windowsDisk = $win32DiskDrive | where {$_.AltSerialNumber -eq $vmHardDisk.ScsiCanonicalName.substring(12,24)}  }    #generate a result  $result = "" | select vmName,vmHardDiskDatastore,vmHardDiskVmdk,vmHardDiskName,windowsDiskIndex,windowsDiskSerialNumber,vmHardDiskUuid,windowsDiskAltSerialNumber,vmHardDiskScsiCanonicalName  $result.vmName = $vmName.toupper()  $result.vmHardDiskDatastore = $vmHardDisk.filename.split(']')[0].split('[')[1]  $result.vmHardDiskVmdk = $vmHardDisk.filename.split(']')[1].trim()  $result.vmHardDiskName = $vmHardDisk.Name  $result.windowsDiskIndex = if ($windowsDisk){$windowsDisk.Index}else{"FAILED TO MATCH"}  $result.windowsDiskSerialNumber = if ($windowsDisk){$windowsDisk.SerialNumber}else{"FAILED TO MATCH"}  $result.vmHardDiskUuid = $vmHardDiskUuid  $result.windowsDiskAltSerialNumber = if ($windowsDisk){$windowsDisk.AltSerialNumber}else{"FAILED TO MATCH"}  $result.vmHardDiskScsiCanonicalName = $vmHardDisk.ScsiCanonicalName  $results += $result
}

#sort and then output the results
$results = $results | sort {[int]$_.vmHardDiskName.split(' ')[2]}
$results | ft -AutoSize

find a host's parent (cluster)

$
0
0

I am using this code (courtesy of LucD) to find a cluster's parent.

 

$cl = Get-View -ViewType ClusterComputeResource -Property Name,Parent
$dc = Get-View -Id (Get-view -Id $cl.Parent -Property Name,Parent).Parent -Property Name
$dc.Name

 

I want to modify this in a way that it will give me a host's parent. I tried it like this, but no luck, because $cluster.name is always "host"

 

$hosts = Get-View -ViewType HostSystem -Property Name,Parent
$cluster = Get-View -Id (Get-view -Id $hosts.Parent -Property Name,Parent).Parent -Property Name
$cluster.Name

 

How can I achieve this?

VCheck and Storing passwords.

$
0
0

I have started with a new department at work, and delving into the VMware side of things.  I was tasked with setting up VCheck scripts to poll our environments. I managed to get these set up within all environments, but now I would like to have one location to store all the scripts and have them connect to several different Domains.  I Read a few articles on here that require you to create the password .xml file which I realized you have to use powerCLI and not powershell (Yes, I am a nube to this).  I can create the .xml file no issues, but calling the password file is giving me issues. I am having an issue understanding the disconnect between commands between PowerShell and PowerCLI.  New-VICredentialStoreItem creates the password file, and it wont work in Powershell, but when I invoke vCheck.Ps1 from within Powershell it doesn't recognize the Commands to call the password file. I am probably missing something really easy, or my basic understanding is completely false. 

 

I am calling the vCheck script via Task Scheduler and that works, but trying to call the password file is giving me issues. I have zero background in programming, so this is a tad confusing.

 

Thank you so much.

Viewing all 16717 articles
Browse latest View live