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

Trying to check if tools is running in order to reboot or reset VM

$
0
0

Hello,

 

I'm trying to reboot VM's in a specified folder, but I first want to check if the VM has tools running or not.  If it's running I want it to use the Restart-VMGuest, if it's not running and powered on I want to use Restart-VM and if it's powered off I want it to do nothing.  Below is a snippet of what I have:

 

$vmlocation = Get-VM -Location $myfolder | sort Name #Gets folder where VM's are located, if folder name is not unique in vCenter it will reboot VM's in all folders with same name
foreach ($vm in $vmlocation) {

$VMname = Get-VM -Name $vm | Select Name, @{N="Powerstate";E={($_).powerstate}} #Checking power state#
if ($VMname.Guest.ToolsStatus -eq "Running")
{
Write-Host "VM -->", $VMname.Name, "is powered on and tools running, script will restart the VM"
Restart-VMGuest -VM $VMname.Name -Verbose:$false -Confirm:$false  #Rebooting thru Guest OS, tools must be installed for this to work
}
elseif ($VMname.Powerstate -eq "PoweredOff")
{
Write-Host "VM-->", $VMname.Name, "is powered off, so ignoring"
}
else
{
Restart-VM -VM $VMname.Name -Verbose:$false -Confirm:$false #Restarts remaining VMs that don't have tools running
}
}

 

So for the most part this works for me.  I can get it to ignore the VM's that are powered off, however it just goes to do the Restart-VM each time instead of the Restart-VMGuest.  I know I'm missing something, but anytime I make a change it doesn't help.


Mount a datastore to secondary host.

$
0
0

Could someone help me if there is a command or a way to a secondary host apart from the one it was created.

VM's number by pool

$
0
0

Hello,

 

I did some investigations but i did not find a good answer to my problem (so i apologize if there is already a topic with the answer).

In the infrastructure we have many differents pools with few hundreds of VMs inside and I have to write a script that count the number of used VM and unused VM on each pool and export it inside a CSV.

 

I started using this command :

Get-ResourcePool | Select Name, @{N="VM#";E={$_.ExtensionData.Vm.Count}}

 

but i don't know to see unused VM and export the result in a good-looking CSV file.

 

I would appreciate some tips if someone can help me.

 

Best regards,

Need Help with Creating a Script.

$
0
0

Hello All,

 

I am currently trying to understand how to script for PowerCLI. I am trying to create a script that will create resource pools based on user names from active directory. At the moment I don't have access to the server I will being running on so I am trying to get the framework of the script down. Here is what I have so far:

 

#Specify vCenter, vCenter username, and vCenter password

$servername = " "

$username = " "

$pass = " "

 

 

Write-Host "Connecting......."

Connect -VIServer - server[$servername] -User[$username] -password[$pass]

Write-Host "Connected"

Write-Host " "

 

#Command to pull data from Active directory domain.

Get-VIAccount -Domain " "

 

# Create Resource Pool cmdlet

New-ResoucePool -Location <VIContainer> -LastNameFirstName <String>

[-CpuExpandableReservation[$false]][-CpuLimitMhz <Int64>]

[-CpuReservationMhz 500] [-CpuSharesLevel High]

[-MemExpandableReservation $false] [-MemLimitMB<Int64>]

[-MemLimitGB <Decimal>] [-MemReservationMB <Int64>]

[-MemReservationGB 5] [-MemSharesLevel High]

[-NumCpuShares <Int32>] [-NumMemShares <Int32>] [-Server <VIServer[]>]

[-WhatIf] [-Confirm] [<CommonParameters>]

 

Any help would be greatly appreciated

Create VMK with vmotion TCP Stack

$
0
0

Hey all,

 

Trying to create a vmkernal interface with TCP stack vmotion but doesn't seem to be an option. Also is it possible to choose the vmk id rather than it just incre

 

New-VMHostNetworkAdapter-VMHost$h-VirtualSwitchDSwitch-PortGroupDPortGroupVMK3-IP1.1.1.1-SubnetMask255.255.255.0-Mtu9000-VMotionEnabled$true

Script for getting Power off VMs date fails after a few VMs

$
0
0

Hi,

I have the script below that fails after about 5 VMs with 

Get-VIEvent : 11/10/2018 12:54:35       Get-VIEvent             Exception has been thrown by the target of an invocation.
At line:1 char:1
+ Get-VIEvent -Entity $VMs -MaxSamples ([int]::MaxValue) |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-VIEvent], VimException
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetEvent

 

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

$Report = @()

 

$VMs = get-vm |Where-object {$_.powerstate -eq "poweredoff"}

 

Get-VIEvent -Entity $VMs -MaxSamples ([int]::MaxValue) |

where {$_ -is [VMware.Vim.VmPoweredOffEvent]} |

Group-Object -Property {$_.Vm.Name} | %{

  $lastPO = $_.Group | Sort-Object -Property CreatedTime -Descending | Select -First 1

  $vm = Get-VM -Name $_.Name

  $row = '' | select VMName,Powerstate,PowerOFF

    $row.VMName = $vm.Name

    $row.Powerstate = $vm.Powerstate

    $row.PowerOFF = $lastPO.CreatedTime

    $report += $row

}

 

$report | Sort Name | Export-Csv -Path "C:\temp\Powered_Off_VMs11.csv" -NoTypeInformation -UseCulture

 

Any help would great.

Thanks

Michael

Unable to get VMs list whose drive space is greater than 80%

$
0
0

Hi,

 

Please help me with below script as I am unable to get VMs list whose drive space is greater than 80%

 

Below is the script

 

$VmInfo = ForEach ($VM in Get-VM)

{

($VM.Extensiondata.Guest.Disk | Select @{N="Name";E={$VM.Name}},

@{N="IPAddress";E={$VM.guest.IPAddress[0]}},

@{N="VM PowerState";E={@($VM.PowerState)}},

@{N="Operating System"; E={@($VM.guest.OSFullName)}},

@{N="Folder";E={$VM.Folder.Name}},

@{N="MountPoint";E={$_.DiskPath}},

@{N="Capacity(GB)";E={[math]::Round($_.Capacity/ 1GB)}},

@{N="FreeSpace(GB)";E={[math]::Round($_.FreeSpace / 1GB)}},

@{N="FreeSpace(%)";E={[math]::Round(((100* ($_.FreeSpace))/($_.Capacity)),0)}},

@{N="UsedSpace(GB)";E={[math]::Round(((($_.Capacity / 1GB))-($_.FreeSpace / 1GB)),0)}})

}

$VmInfo

error thrown when using remove-datastore cmdlet

$
0
0

I am running the command below

 

Remove-Datastore -Datastore datastore -VMHost host -Confirm:$False

 

the error gets thrown

 

Remove-Datastore A specified parameter was not correct - full error output attached (hostname has been blacked out)

 

am I missing something obvious?

 

Any help appreciated.


Script to move hosts from one cluster to another

$
0
0

Hello,

 

I'm trying to write a script to migrate multiple hosts from one cluster to another.  I'm not finding much luck on the google, so I'm hoping I can get help here.  Here's the basic script (sorry I don't know how to get the code to look all pretty):

 

#Datacenter
Get-Datacenter | select Name | Format-Table #Lists available datacenters
$mydatacenter = Read-Host "Choose a datacenter"

Get-Datacenter $mydatacenter | Get-Cluster | select Name | Format-Table
$fromcluster = Read-Host "Select a cluster to migrate hosts from"
$tocluster = Read-Host "Select a cluster to migrate the hosts to"

#ESX Hosts to migrate
Write-Host "Select the hosts that you want to migrate"
Get-Cluster $fromcluster | Get-VMHost | where {$_.ConnectionState -eq "Maintenance"} | sort Name | Select Name,ConnectionState,PowerState | Out-GridView -OutputMode Multiple #Lists hosts that are powered on and in "Maintenance" state

#Cluster to migrate to

foreach ($vmhost in $fromcluster)
{
Move-VMHost -VMHost $vmhost -Destination $tocluster -WhatIf
}

 

I basically get an error stating it couldn not find a VMhost with name <cluster name>.  What am I missing?  I feel like it's something so simple, but I'm still new enough to this that I can't quite figure it out just yet.

How can I list the resource associated with the output of Get-OMAlert |Get-OMRecommendaton?

$
0
0

I am new to PowerCli.  I've been experimenting with connectivity to vRops.

The command above lists all of the recommendations associated with the alerts, but does not have a way to output the resource it is associated with.

log_script_structure_powercli

$
0
0

Hi Luc ,

 

could you check the line in orange color and suggest how different strings(regular expressions as you mentioned in last post) are provided using read-host .

?or it has to be hard coded like the way in put in script.

 

 

 

 

 

$entity = Read-Host "Which entity?"

 

$target = New-Item -ItemType Directory -Force -Path "c:\users\jvm\desktop\T_script\logs"

 

if((Get-VM -ErrorAction SilentlyContinue).Name -contains $entity){

 

    Write-Host "It's a VM" -ForegroundColor Yellow

 

    $vm = Get-VM -Name $entity

 

    $ds = Get-Datastore -RelatedObject $vm

 

    New-PSDrive -Location $ds -Name DS -PSProvider VimDatastore -Root '\' | Out-Null

 

    #Get-ChildItem -Path DS:\

    Set-Location DS:\

cd $vm

 

#Get-ChildItem vmware.log

Copy-DatastoreItem -Item vmware.log -Destination $target

 

 

    Remove-PSDrive -Name DS -Confirm:$false

 

}

 

elseif(((Get-VMHost).Name | %{$_.Split('.')[0]}) -contains $entity){

 

    Write-Host "It's an ESXi" -ForegroundColor Green

    #specify domain starting with "."

    $domain=read-host "specify domain"

    $log_type=read-host "specify log type"

 

    $esxi_name = $entity+$domain

    $esxi_name

 

    get-log -VMHost $esxi_name -key $log_type | Select -ExpandProperty Entries|out-file -FilePath "$target\$entity.txt"

    $res1=read-host "do yu need log bundle""y/n"

    if($res1 -eq 'y')

    {

    write-host "generating log bundle" -ForegroundColor DarkCyan

    get-log -VMHost $esxi_name -Bundle -DestinationPath "c:\users\jvm\desktop\T_script\logs"

 

    }

    if($res1 -eq 'n')

    {

    Write-Host "......."

 

    }

 

    $res2=read-host "do yu want to check specific strings in" $log_type" y/n?"

    if($res2 -eq 'y')

    {

     $match = ".*(?=.*2018-10-15)(?=.*device)(?=.*failed).*"

 

     get-log -VMHost $esxi_name  -key $log_type | Select -ExpandProperty Entries | where{$_ -match $match}|out-file $esxi_name-vmkernellog_match.txt

    }

 

    }

Pull list of VMs by Name, and sys.osuptime.latest

$
0
0

Hello

 

I am trying to pull a list of VMs with their Get-Stat for uptime and the VM name. I am having a little trouble getting these in a clean manner.

 

Below is what works fine for pulling a single VM uptime

 

Get-Stat -Entity testvm -Stat 'sys.osuptime.latest' -Realtime -MaxSamples 1 -ErrorAction SilentlyContinue | Select @{N='Uptime (d.hh:mm:ss)';E={[timespan]::FromSeconds($_.value)}}

 

But I would like to put a Get-Folder or Get-VM 'format of vm names' | <then the above code> to output to a more digestible format like Name | Uptime (d.hh:mm:ss) .

Trying to create a script to move VM's serially from multiple datastores to one datastore

$
0
0

So I've been tasked with moving VM's from multiple old datastores to one new datastore.  Unfortunately the way things were setup (not my doing) was a convoluted mess.  I basically want to connect to a host, get the list of VM's on it and migrate them to the new datastore that will also be mounted on that host.  So far I've come up with something like this:

 

Get-Datacenter | select Name | Format-Table #Lists available datacenters
$mydatacenter = Read-Host "Choose a datacenter"
Get-Datacenter $mydatacenter | Get-VMHost | where {$_.ConnectionState -eq "Connected"} | sort Name | Select Name,ConnectionState,PowerState | Format-Table  #Lists available hosts in the chosen datacenter
$esxhost = Read-Host "Select the host to migrate VM's in"
Get-Datastore -VMHost $esxhost | sort Name | Format-Table
$destinationdatastore = Read-Host "Select the datastore to migrate VM's to"
$selectedvms = Get-VMHost $esxhost | Get-VM | sort Name | Out-GridView -OutputMode Multiple #Opens a new window allowing you to select multiple VM's

if($selectedvms){
foreach ($vm in $selectedvms)
{
Move-VM -VM $vm.Name -Destination $destinationdatastore #Moves to the new datastore
}
}

 

But when I try to run it, it winds up failing on the migration.  I'm not sure what I'm missing on this.  I do plan on making a change to look for the NFS datastore to migrate to, but for now I'm doing a quick test from a NFS storage to a local storage.  The error I get is below:

 

Move-VM : 10/15/2018 12:12:38 PM        Move-VM         Could not find VIContainer with name 'datastore_localhost'.     

At C:\Users\emcclure\Desktop\GenScripts\GeneCMMigrateVMs.ps1:34 char:2

+     Move-VM -VM $vm.Name -Destination $destinationdatastore #Moves to ...

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

    + CategoryInfo          : ObjectNotFound: (datastore_localhost:String) [Move-VM], VimException

    + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle

   ts.Commands.MoveVM

Script for reporting and removing VMs older than 2 weeks.

$
0
0

Hi guys,

 

I need some help in putting a script together that will remove all powered off virtual machines that have been powered off longer than 14 days and will send out an e-mail with the virtual machines that were removed. Using the code below I am able to retrieve the desired virtual machines that match the date but can't seem to be able to use the same variables to pipe them into the Remove-VM commandlet.

 

Code:

$vms = Get-VM | where {$_.PowerState -eq "PoweredOff"}

$vmPoweredOff = $vms | %{$_.Name}

$events = Get-VIEvent -Start (Get-Date).AddDays(-14) -Entity $vms | where{$_.FullFormattedMessage -like "*is powered off"}

 

Send-MailMessage -From virtualadmin@company.com -To vadmin@company.com -SmtpServer smtprelay.company.com

-Subject "Removed $($14day) VM" -Body ($vmNames | Out-String) ----> The body would only include the virtual machines that were removed.

 

Much appreciated. Thanks!!

Datastore Capacity Load

$
0
0

Hey all,

Looking if anyone has a script to use the total disk used to calculate the percent load on each datastore in a DC and export in a html page.

Any tips would be great,

Andy


Get VMs with 3D enabled

$
0
0

Hello,

 

I need to make sure that the 3D acceleration is disabled on all VMs, but this script didn't work for me. I'm using PowerCLi v10

 

Get-View -ViewType VirtualMachine -Property Name,Config.Hardware.Device | `

  ForEach-Object {

    $VM = $_

    $VM.Config.Hardware.Device | `

    Where-Object {$_.GetType().Name -eq "VirtualMachineVideoCard"} | `

    Select-Object -property @{N="VM";E={$VM.Name}},Enable3DSupport

  } | Where-Object {$_.Enable3DSupport}

Add second DNS server to VMs

$
0
0

Hi All

 

Currently i have a resource pool where the VM's only have one DNS entry

 

I need to create a script to add the second DNS entry (not change the first one, just leave it as it is)

 

I have started with the below  to connect to VC, take the resouce pool in question and get all the VM's in that resource pool. Then for each VM in vms i will run an invoke vmscript command , does anyone how the syntax to add the second dns server ?

 

 

 

# Connect to vCenter silently

#

try {

Write-Host "Connecting to..." $vCenter -ForegroundColor Yellow

Connect-VIServer -Server $vCenter -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null

if ($? -eq $false) {throw $error[0].exception}

}

catch [Exception]{

exit

}

 

$rp = Read-Host -Prompt "What Resource Pool do you want to gather information for "

 

 

$vms = get-resourcepool -Name $rp | get-vm | where {$_.Powerstate -eq 'Poweredon'}

 

foreach ($vm in $vms){

invoke-vmscript -vm $vm -ScriptText ......

}

How to find Orphaned VMDK files

$
0
0

How can we find out Orphaned VMDK files in all the Data-stores.

physicalnics_esxi_in cluster_powercli

$
0
0

Hi Luc,

 

could you suggest how to get proper output on console using following script.below works fine but even with join operator output is not fully displayed .

 

$cluster=read-host -Prompt "cluster name"

foreach($esxi in (get-vmhost -Location $cluster))

{

$esxi_name = get-vmhost $esxi

$esxi_name|select name,model,@{N='pNIC';E={(Get-VMHostNetworkAdapter -Physical -VMHost $_).Name -join '|'}},@{N = 'linkspeed';E={$spec=Get-VMHostNetworkAdapter -VMHost $_

 

 

                                                                                                                                  $spec.extensiondata.linkspeed.speedMb -join '|'

                                                                                                                                

 

 

}}

 

 

getting following output name is not shown here .

 

 

is the above method not sufficient enough for larger numbers .do we need to use add-psobject method??

Group the Files in multiple folders and write size and folder name in output

$
0
0

Is it possible to get these information through powercli?

I have a datastore which contains multiple file Like .iso, .zip,.exe,.vib etc. These files are distributed in multiple folders.

As I know the extensions I will give them as input

Ex:

$Extension1= '.iso',.exe

$Extension2=.zip,.vib

 

Here I am expecting output - similar files in $Extension1 should group and write output as below

Path

Object count= like .iso count or .zip files count

Extension = .zip or .vib

Size= how much size in MB

and folder name like $Extension1 belongs to image folder name

$Extension2 belongs to Executable folder name (These folder names are different in the datastore but while writing in output it should write with this name.)

Viewing all 14549 articles
Browse latest View live


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