Quantcast
Channel: VMware Communities : Discussion List - VMware PowerCLI
Viewing all 14549 articles
Browse latest View live

Can we pull the Network IP address, DNS and default gateway for the VM's from power cli ?

$
0
0

HI All,

 

Can we pull the Network IP address, DNS and default gateway for the VM's from power cli for the specific lists of VM's?  E.g. C:\temp\vmlist

 

thanks

vmk


error execute powershell script

$
0
0

I have the following script that clones me a VM when I run it from powercli version 6.5 it works correctly but when I try from powershell version 5 it shows me the following error.

 

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

##Clonar VM

##Variables

$vcenter_server ="ip"

$vcenter_user ="user"

$vcenter_pwd ="passwd"

$VMsource = "SRV-SERVER"

$esxi = "172.16.1.51"

$newVMclone = "$($VMsource)-clone-$((Get-Date).ToString('MMddyyyy'))"

$oldCloneName = "$($VMsource)-clone-$((Get-Date).AddDays(0).ToString('MMddyyyy'))"

$ds = Get-Datastore | where{$_.Type -eq 'VMFS' -and $_.ExtensionData.Summary.MultipleHostAccess} | Sort-Object -Property FreeSpaceGB -Descending | select -First 1

$esx = Get-Cluster -VM $VMsource | Get-VMHost | Get-Random

 

 

##Connect to vCenter

connect-viserver -server $vcenter_server -User $vcenter_user -Password $vcenter_pwd

 

 

##Elimina VM de hasta 7 dias

Get-VM -Name $oldCloneName -ErrorAction SilentlyContinue | Remove-VM -DeletePermanently:$true -Confirm:$false

 

 

##Clone VM, disco virtual tipo thick y carpeta de almacenaiento de la VM

New-VM -VM $VMsource -Name $newVMclone -VMHost $esxi -DiskStorageFormat Thin -Location "Laboratorios"

 

 

## get the .Net View object of the clone VM

$viewCloneVM = Get-View -ViewType VirtualMachine -Property Name,Config.Hardware.Device -Filter @{"Name" = $sVMsource}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 

PS C:\Users\Marco\Desktop> .\clonacion.ps1

Get-Datastore : The term 'Get-Datastore' 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 C:\Users\Marco\Desktop\clonacion.ps1:10 char:7

+ $ds = Get-Datastore | where{$_.Type -eq 'VMFS' -and $_.ExtensionData. ...

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

    + CategoryInfo          : ObjectNotFound: (Get-Datastore:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

command works on windows, but fails on linux powercli

$
0
0

I try to create a VM from a Linux Powercli and get a error. Same Powercli version on a Windows OS works.

If the user has Admin rights it works on Linux too.

I also tried it with the newest Powercli Version, same Issue.

Could someone help me with this?

 

 

 

Linux:

new-vm -name myvm -ResourcePool mypool -Location myfolder

 

new-vm : 2/8/19 2:02:18 PM      New-VM

At line:1 char:1

+ new-vm -name myvm  -ResourcePool mypool -Location myfolder...

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

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

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

 

Win10:

 

new-vm -name myvm -ResourcePool mypool -Location myfolder

 

Name                 PowerState Num CPUs MemoryGB

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

myvm         PoweredOff 1        0.250

 

 

PowerCLI Version

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

   VMware PowerCLI 10.1.0 build 8346946

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

Component Versions

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

   VMware Cis Core PowerCLI Component PowerCLI Component 10.1 build 8377811

   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 10.1 build 8344055

Issues with Global get-tagassigment

$
0
0

We recently started running into an issue in one of our vCenters with a script that I had written to grab the inventory of VMs in our environment including the Tags associated with the VMs. We have 3 vCenters, all running 6.5, and 2 of the 3 vCenters run the script fine, but when we run the script against the 3rd vCenter, we get an error:

Get-TagAssignment : 5/14/2018 4:40:31 PM        Get-TagAssignment               com.vmware.vapi.std.errors.internal_server_error {'messages': [com.vmware.vapi.std.localizable_message {'id':
vapi.bindings.method.impl.unexpected, 'default_message': Provider method implementation threw unexpected exception: Read timed out, 'args': [Read timed out]}], 'data':}

At line:1 char:1
+ Get-TagAssignment
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-TagAssignment], CisException
    + FullyQualifiedErrorId : VMware.VimAutomation.ViCore.Impl.V1.Service.Tagging.Cis.TaggingServiceCisImpl.GetTagAssignment.Error,VMware.VimAutomation.ViCore.Cmdlets.Comma
   nds.Tagging.GetTagAssignment

The vCenter with the issues is our largest site, and has the most tags, so I believe we have possibly hit a limit of the number of results get-tagassignment can return as this script worked fine until a week ago when we added some more tags to the VMs.

I have looked at a few other threads on here, and in one of them LucD recommended using his rCIS module to get around a very similar issue. I have attempted to run the rCIS module and am getting an error with it as well:

Get-View : 5/14/2018 4:39:19 PM Get-View                You are not currently connected to any servers. Please connect first using a Connect cmdlet.
At FileLocation\Projects\VMWare\rCisTag\rCisTag.psm1:408 char:35
+ ...                   Entity = (Get-View -id $sMoRef -Property Name).Name
+                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [Get-View], ViServerConnectionException
    + FullyQualifiedErrorId : Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.DotNetInterop.GetVIView

I have verified that both get-tag and get-rcistag works fine, and using either get-tagassigment or get-rcistagassignment using the -entity filter works, but using either without a filter fails. unfortunately due to the way the code was written, using a filter on the get-tagassignment isnt easy to re-write

Below is the section of code that is calling the get-tagassignment and failing

 

foreach($tag in (Get-TagAssignment)){
    $tagCat += $tag.Tag.Category.Name
    $key = $tag.Entity.Name
    if($tagTab.ContainsKey($key)){
    ` $val = $tagTab.Item($key)
    }
    else{
        $val = @{}
    }
    $val.Add($tag.Tag.Category.Name,$tag.Tag.Name)
    $tagTab[$key] = $val
}

any assistance would be greatly appreciated

Get list of registered VM's that are in my test datastore then unregister them

$
0
0

I have a test datastore called "test-vmgarbage-nobackups".

 

How can I get a list of VM's that are registered in vCenter that live on my test datastore then unregister them from vCenter?

 

NOTE: there are some VM's that have disks on that datastore but the vmx file resides on another datastore. I don't want to touch those.

 

Thanks

General query

$
0
0

Friends I have the two following scritps the first one is constantly pinging the Ip of a VM at the moment that there is no ping a cloned VM is turned on

 

 

The second script simply clones a VM origena to that VM I ping with the first script

 

 

Well the inconvniente is the following:

 

 

Run the two scripts at the same time the ping script works correctly, then while cloning is done with the other script at the time of the cloning the sentence "else" of the first script is executed is like missing the vm ping but in this case it does not lose connection that could be happening...

 

 

SCRIPT PING

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

#IP VM origen

$VMIP= "172.16.6.200"

##Sentencia para verificacion de conexion a VM origen

do{

$i=1

$i++

##Ping hacia la IP de la VM Origen

$results = gwmi -query "SELECT * FROM Win32_PingStatus WHERE Address = '$VMIP'"

 

 

##Si tenemos conexion mostrara mensaje que la VM esta activa

if ($results.StatusCode -eq 0) {

Write-Host "$VMIP online"

}

##Caso contrario mostrara que esta offline, desctivara vNIC de la Origen y encendera la ultima VM clonada

else {

Write-Host "$VMIP offline"

##Coneccion a vCenter

connect-viserver -server $vcenter_server -User $vcenter_user -Password $vcenter_pwd

#Nombre de la VM Origen

$VMorigen= "SRV-SERVER"

#Nombre de la ultima VM clonada

$VMclone= "$($VMorigen)-$((Get-Date).ToString('MMddyyyy'))"

Get-VM -Name SRV-SERVER | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$false -Confirm:$false

GET-VM -Name $VMclone | Start-VM -Confirm:$False

##Desconnexion de vCenter

Disconnect-VIServer -Confirm:$false

##Para sentencia en caso de no tener conexion

break

}

}while($i -le 9999)

----------

 

SCRIPT CLONE VM

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

#Validacion en caso de noter certificado en el vcenter

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

##Coneccion a vCenter

connect-viserver -server $vcenter_server -User $vcenter_user -Password $vcenter_pwd

 

 

#Nombre de la VM Origen

$VMorigen = "SRV-SERVER"

# Ip o hostname de host en donde se clonara la VM

$esxi = "172.16.1.51"

#Nombre para VM clonada con fecha de clonacion

$newVMclone = "$($VMorigen)-$((Get-Date).ToString('MMddyyyy'))"

#Variable para que busque el clone de hace  un dia

$oldCloneName = "$($VMorigen)-$((Get-Date).AddDays(0).ToString('MMddyyyy'))"

#Datastore en donde se guardara la VM

$datastore=Get-datastore -Name 'Datastore-1'

#Parametro para que la VM se guarde en un Datastore compratido dentro de un cluster

$ds = Get-Datastore | where{$_.Type -eq 'VMFS' -and $_.ExtensionData.Summary.MultipleHostAccess} | Sort-Object -Property FreeSpaceGB -Descending | select -First 1

#Parametro para que la VM se guarde en cualquier host de lcluster

$esx = Get-Cluster -VM $VMorigen | Get-VMHost | Get-Random

 

 

##Elimina VM de hasta 1 dia en base al nombre del VM clonada

Get-VM -Name $oldCloneName -ErrorAction SilentlyContinue | Remove-VM -DeletePermanently:$true -Confirm:$false

 

 

##Clonacion de VM, disco virtual tipo thick y carpeta de almacenaiento de la VM

 

 

if(New-VM -VM $VMorigen -Name $newVMclone -VMHost $esxi -DiskStorageFormat Thin -Datastore $datastore -Location "Laboratorios"){

"DONE"

}else{

"Error al clonar la VM"

}

##Desconnexion de vCenter

Disconnect-VIServer -Confirm:$false

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

Horizon: QueryService_Create fails

$
0
0

Hi all,

 

I need your help getting QueryService_Create to work with Horizon 7.

 

Using PowerCLI  under Windows 7, with the following PS version:

 

pwsh >  $PSVersionTable

 

Name                           Value

----                           -----

PSVersion                      5.1.14409.1018

PSEdition                      Desktop

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

BuildVersion                   10.0.14409.1018

CLRVersion                     4.0.30319.42000

WSManStackVersion              3.0

PSRemotingProtocolVersion      2.3

SerializationVersion           1.1.0.1

 

The code fails at the last line with this error:

 

Exception calling "QueryService_Create" with "2" argument(s): "Object reference not set to an instance of an objectException calling "QueryService_Create" with "2" argument(s): "Object reference not set to an instance of an objectAt PowerShell\Horizon_03.ps1:14 char:1

+ $queryResults = $queyService.QueryService_Create($hvServices, $defn)

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

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

    + FullyQualifiedErrorId : NullReferenceException

 

Here is the code (I've already used connect-hvserver successfully before the code):

 

$queyService = New-Object VMware.Hv.QueryServiceService

$defn = New-Object VMware.Hv.QueryDefinition

 

$defn.queryEntityType = 'FarmSummaryView'

$queryResults = $queyService.QueryService_Create($hvServices, $defn)   # This is line 14 in the program

 

The code fragment is verbatim from this example:

# https://vdc-repo.vmware.com/vmwb-repository/dcr-public/2365e8a2-2a49-40c3-ae46-510d918c2fa1/86751889-022e-47c4-b2b9-8bc2e3fa6d21/queries-landing.html21

 

Any help would be greatly appreciated.

 

-Chris

invoke operation failing even with admin user

$
0
0

I am trying to create a user on windows machines but its failing  with this message "This operation requires an interactive window station" but if i login to the machine and open powershell as runasadmin and execute below script ($script)its working. Is there anyway to achieve this task over invoke-vm cmdlet.

The guest user which i am using while invoke-vm has administrative rights on the machine.

$script = @'
function Elevate-Process  {
param ([string]$exe = $(Throw "Pleave provide the name and path of an executable"),[string]$arguments)
$startinfo = new-object System.Diagnostics.ProcessStartInfo 
$startinfo.FileName = $exe
$startinfo.Arguments = $arguments 
$startinfo.verb = "RunAs" 
$process = [System.Diagnostics.Process]::Start($startinfo)
}
Elevate-Process -Exe powershell.exe -Arguments "-noninteractive -command 
$newUser = 'swops'
$pswd = 'Ann0tat10n'
$localusers=Get-LocalUser | Select Name
if($localusers -notcontains $newUser){
# Create user
$securePswd = ConvertTo-SecureString -AsPlainText -String $pswd -Force
New-LocalUser -Name $newUser -Password $securePswd -Confirm:$false
}
else{
# Change Password for Existing user
$localadministrator=[adsi]("WinNT://./swops, user")
$localadministrator.psbase.invoke("SetPassword", "$pswd")
Set-LocalUser -Name 'swops' -PasswordNeverExpires 1
net localgroup Administrators swops /ADD
}
"
'@
Invoke-VMScript -VM 'WUSALP810003' -ScriptText $script -ScriptType Powershell -GuestUser '' -GuestPassword '' |Select -ExpandProperty ScriptOutput

 


html_report_powercli

$
0
0

Hi Luc ,

 

Good morning ,

I had a discussion with you earlier to generate html report for a cluster .

i am trying to loop it on a list of clusters using import-csv.

However for some reasons not getting desired  output  .can you please check and modify it .

 

 

$vc=read-host "specify vcenter name"

$cred=Get-Credential

 

connect-viserver -server $vc -Credential $cred|out-null

 

$path = 'C:\Users\user1\Desktop\folder1'

 

 

 

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

 

'@

 

 

$clusters = Import-Csv -path  "C:\users\user1\desktop\folder1\names.csv"

 

 

foreach($line in $clusters)

{

 

$cluster = Get-Cluster -name $line.clustername

$clu = Get-Cluster -name $cluster|select name|convertto-html -property name -Fragment -PreContent '<h2>clustername </h2>'|out-string

 

$ds_all=get-datastore -RelatedObject $cluster

$syslog_server="10.x.x.x"

 

 

$ds = Get-Datastore -RelatedObject $cluster |

 

    Where-Object{($_.FreeSpaceGB)/($_.CapacityGB) -le 0.15} |

 

    Select Name |

 

    ConvertTo-Html -Property Name -Fragment -PreContent '<h2>DATASTORE WITH LESS THAN 15 PERCENT SPACE </h2>' |

 

    Out-String

 

 

 

$snap = Get-VM -location $cluster  | Get-Snapshot |

 

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

 

 

      ConvertTo-Html -Property Name,VM,Created -Fragment -PreContent '<h2>SNAPSHOT_INFO</h2>' |

 

    Out-String

 

 

  

 

 

 

$powered_off=get-vm -Location $cluster|?{$_.PowerState -eq "poweredoff"}|select name|

    ConvertTo-Html -Property Name -Fragment -PreContent '<h2>POWEREDOFF_VMS</h2>' |

 

    Out-String

 

 

   

 

 

 

$vmkernel_vmotion = Get-VMHost -Location $cluster|select name,@{N='vmkernel';E={$_|get-vmhostnetworkadapter -VMKernel|?{$_.vmotionenabled -eq "true"}}}| ConvertTo-Html -Property name,vmkernel -Fragment -PreContent '<h2>VMKERNEL_PORT_VMOTION</h2>' |

 

    Out-String

 

$syslog_server=Get-VMHost -Location $cluster|select name,@{N='syslogserver';E={Get-VMHostSysLogServer -VMHost $_}}|ConvertTo-Html -Property name,syslogserver -Fragment -PreContent '<h2>SYSLOGSERVER<h2>' | out-string

 

 

 

 

 

 

$windows_vm_tooldsupgrde_needed=get-vm -Location $cluster|?{$_.Guest.GuestFamily -eq 'windowsGuest' -and $_.ExtensionData.guest.toolsversionstatus -eq 'guesttoolsneedupgrade'}|select name|

ConvertTo-Html -Property Name -Fragment -PreContent '<h2>WINDOWS_VM_TOOLS_NEED_UPGRADE</h2>' |

 

    Out-String

 

 

$ntp = get-vmhost -Location $cluster|Get-VMHostService|?{$_.key -eq 'ntpd'}|select vmhost,key,running|ConvertTo-Html -Property vmhost,key,running -Fragment -precontent '<h2>NTP<h2>'|Out-String

$version=get-vmhost -location $cluster|select name,build,version,model|ConvertTo-Html -Property name,build,version,model -Fragment -PreContent '<h2>VERSION<h2>'|Out-String

 

 

 

 

 

$cluster_properties=Get-Cluster $cluster|select drsenabled,haenabled,HAAdmissionControlEnabled|ConvertTo-Html -Property drsenabled,haenabled,HAAdmissionControlEnabled -Fragment -PreContent '<h2>CLUSTERPROPERTIES<h2>'|Out-String

 

 

$datastore_cluster=Get-DatastoreCluster -Location(Get-Datacenter -Cluster $cluster)|select name|ConvertTo-Html -Property name -Fragment -PreContent '<h2>DATASTORECLUSTER<h2>'|Out-String

}

ConvertTo-HTML -head $head -PostContent $clu,$ds,$snap,$powered_off,$vmkernel_vmotion,$windows_vm_tooldsupgrde_needed,$ntp,$version,$cluster_properties,$datastore_cluster,$syslog_server|

Out-String | Out-File -FilePath "$path\test_11feb.html"

Using Get-View against many datacenters some with same named VMs

$
0
0

So I've run into a odd little issue and I'm stumped.

 

I've got a basic report built along the lines of foreach ($vm in $VMList)

{$VMStat = "" | Select-object VMName, DC, Cluster, Host, ....

 

Then one of the objects something like:

$VMStat.TotalMemoryGB = [math]::Round($vm.summary.config.memorysizemb*1MB/1GB,2)

 

Works fine on everything until I run into this non template VM that the other system admin guys leave around called dupW2k8 or whatever.   There are many of them one in each cluster of which there are many.

 

So if you do a get-vm dupW2k8  you get a list of 10+ VMs all with their own CPU and Memory but in my foreach loop this creates a problem in producing a report.  Any ideas on how to loop through or around them.   I guess I could create an ignore list or something but I'm sure there are others.   I don't manage the VM Farm I'm just working a report with read only access.

 

thanks for any suggestions

Register all VM's found in datastore into vCenter

$
0
0

OK, I have a datastore called "test-vmgarbage-nobackups" and it has about 15 VM folders in there as well as some folders that only have .vmdk's for other VM's.

 

Anyone have a quick and simple command that will look into my datastore and import my VM's into my vCenter Server?

 

I had a previous question asking how to remove them, now I want to put them back.

Get list of registered VM's that are in my test datastore then unregister them

 

Thanks

Horizon vCheck Plugin issue

$
0
0

Hi, I did reach out to the maintainer, but was wondering if someone else could take a look and hopefully share what I'm missing. The 14 Manually Desktop Pool Information plugin isn't working, and neither are any of the other ones, and I think its all the same problem. Running this set of code block

 

$queryservice=new-object vmware.hv.queryserviceservice

$defn = New-Object VMware.Hv.QueryDefinition

$defn.queryentitytype='MachineSummaryView'

$filter = New-Object VMware.Hv.QueryFilterEquals -Property @{ 'memberName' = 'base.name'; 'value' = "$pool.base.name" }

$queryResults = $queryService.QueryService_Create($Services1, $defn)

$desktops=$queryResults.results

 

Doesn't get desktops from the correct desktop pool, it seems to grab all the vms that have people logged into.The git repo is

 

vCheck-HorizonView/Plugins/20 Desktop at master · vCheckReport/vCheck-HorizonView · GitHub

 

Thanks for any help

Unable to retrieve hard disk sharing configuration

$
0
0

We have a few clustered VMs that use shared VMDK (Oracle RAC) with the hard disk sharing set to "Multi-writer". We are finding that we can only locate these VMs by looking at the VMX file but we don't want to grant permission to download the VMX files. Is there another way that we are missing?

 

We tried these two approaches and they do not return the expected "scsi0:2.sharing = "multi-writer"".

1.

$vm = Get-VM RAC01

Get-AdvancedSetting -Entity $vm | Sort-Object Name | FT -AutoSize

2.

$vm = Get-VM RAC01

$vmView = Get-View -VIObject $vm

$vmView.Config.ExtraConfig

Powershell to find and delete Stranded Items | vCloud Director 9.1

$
0
0

Hi All.



 

Is there any powershell script to automate the deletion of stranded items in vCloud Director 9.1?



 

Thanks in advance!



 

Alicia T

List virtualportgroups in a cluster count VMs and VMhosts

$
0
0

Get-Datacenter "CG-SO" | Get-Cluster|Get-VMHost |Get-VirtualPortGroup tells me the virtualportgroups and vlans.

NPR--10.1.202.0_24        key-vim.host.PortGroup-NPR-... 202

NPR--10.1.201.0_24        key-vim.host.PortGroup-NPR-... 201

NPR--10.1.113.0_24        key-vim.host.PortGroup-NPR-... 113

NPR--10.1.106.0_24        key-vim.host.PortGroup-NPR-... 106

 

I can get host and vm counts with the following:

 

Get-Cluster | Select Name, @{N="Host Count"; E={($_ | Get-VMHost).Count}},  @{N="VM Count"; E={($_ | Get-VM).Count}}

 

How do I combine the two to get the following?

Cluster                                         VirtualPortGroup          Vlan   VMhost Count   VM Count

CG-SO-PRE-DMZ-WINDOWS  NPR--10.1.106.0_24      106                  3                   50

 

I want to identify those virtual port groups no longer in use to evaluate if they need to be removed. We've had several vlans removed from our network infrastructure over the years.


gettingiproutes_and_creatingstaticroutes_powercli

$
0
0

Hi Luc,

 

i thought of starting a new discussion associated  below thred 

creating vmkernel port group_powercli

 

 

vmkernel ports for replication has already been created and assigned to replication vlan as per above post. .

 

created following function that will  find iproute on each esxi host of a cluster and at the same time add new static route to each esxi in same cluster.

can you please validate the orange part of the code .(whether datatype string is correct ?

 

 

function get-staticroute {

 

   [cmdletbinding()]

 

   param(

 

   [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]

 

   [string]$clustername,

   [Parameter(Mandatory=$true)]

 

        [string]$destinationnetwork,

        [Parameter(Mandatory=$true)]

 

        [string]$prefixlength,

        [Parameter(Mandatory=$true)]

 

        [string]$gateway

 

  

 

   )

  

  

   #$clustername=read-host "clustername"

  

   $cluster=get-cluster $clustername

   $vmhosts=get-vmhost -location $cluster

   $fragments = @()

   foreach($vmhost in $vmhosts)

   {

 

   $esxcli = Get-EsxCli -VMHost $vmhost -V2

   $staticrouteinfo=$esxcli.network.ip.route.ipv4.list.Invoke()

 

 

   $fragments += $vmhost.name

   $fragments += $staticrouteinfo

 

 

 

 

 

 

   }

 

   $fragments

 

   $newstaticroute=read-host "would yu like to add static route to all esxi in cluster"

   if($newstaticroute -eq 'y')

   {

   foreach($h in $vmhosts)

   {

 

   #New-VMHostRoute -vmhost $h -destination 172.16.9.0 -PrefixLength 25 -Gateway 172.16.9.1 -WhatIf

   New-VMHostRoute -vmhost $h -destination $destinationnetwork  -PrefixLength $prefixlength  -Gateway $gateway -WhatIf

 

 

   }

 

 

   }

 

   }

VMFS version through power cli

$
0
0

Hi All,

 

I want to pull the report for VMFS version for all cluster. Since we are planning to decommission  VMFS 5. The report should include  Hostname, Cluster name, VMFS version.

 

thanks

vmk

Remove vSAN files (VMDK's)

$
0
0

I'm trying to delete orphand VMDK's from a vSAN datastore.
but not able to find a solution.

I can find the files, but not delete them
ex
[vsanDatastore] cloudvolumes/apps/obsolete.vmdk

And option is to attach them to a new VM, and then delete the VM, but don't have the permissions to create an new VM.

 

br

A. Mikkelsen

Filter Cluster Hosts from Get-View Using Cluster Wildcard

$
0
0

We run a daily script checking the configuration and status of ESXi hosts on multiple vCenters (>100) using the following:

 

Foreach ($vC in $vCList){

 

$ESXiHosts = Get-View -viewtype hostsystem -property Name,OverallStatus,Summary,AlarmActionsEnabled,Config,TriggeredAlarm,VM,ConfigIssue | Sort-Object Name

 

}

 

Does anyone know how to modify the above Get-View command so that it filters out the ESXi hosts in clusters matching the *Build cluster wildcard?

Unable to exit from the script after validation

$
0
0

Hi,

 

I am unable to exit or continue from script after validation

 

Please help

 

$vms = Read-Host "Enter VM Name "

if ($vms | where $_.'VM PowerState' -eq 'PoweredOn') {Exit}

Write-Host "Cannot Continue When VM is Powered On" -ForegroundColor Red

else

{

Write-Host

$newsizeGB = Read-Host "Enter New Disk Size In GB "

}

 

Error

 

Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

At D:\myreports\vm1.ps1:146 char:18

+ if ($vms | where $_.'VM PowerState' -eq 'PoweredOn') {Exit}

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

    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand

 

Cannot Continue When VM is Powered On

else : The term 'else' 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 D:\myreports\vm1.ps1:148 char:1

+ else

+ ~~~~

    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

Viewing all 14549 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>