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

Schedule a task – snapshot

$
0
0

Hi

 

I´m trying to create a vmware schedule task to snapshot a VM via powercli ( using CreateScheduledTask ).

 

As anyone been able to do that ?

 

Thanks


PowerCLI Add RDM back to VM after reboot

$
0
0

Sometimes when you power cycle a VM with 15 RDMs attached the VM boots back up with VMDKs instead of the correct RDMs, How can you export the RDMs as a list and when booting back up run a powercli that will remap all the same Physical RDMs back to the correct VM. Any help would be greatly appreciated.

 

Robert

looking for something like Alans vCheck for a View environment

$
0
0

I need a way to check the health of a View environment regularly.
So before  I waste a lot of time to reproduce something that may already exist I thought I 'd ask ...

 

Do you know any scripts to check the health state of a View environment ?
It does not need to go into the very details - a script that detects critical misconfigurations and other serious issues would do.

 

Thanks Ulli

List VMs with static macs

$
0
0

I was trying to find a way to list VMs with static macs along with thier assigned mac.  Exploring the virtualmachine view i've found where it says static but haven't been able to come up with a way to filter it out.  Is there any way to do this with powercli?

Recompose a single vm with powercli?

$
0
0

Need a bit of direction please.

I can get all info about a single vm, and the pool that it belongs to.

I can send a recompose to an entire pool

What I need to do is send a recompose to a single workstation.

 

Here are the scripts that I have been working with so far.

 

This gives me the machine name and the pool where this machine lives

ForEach ($vm in (Get-DesktopVM)) {If ($vm.user_displayname -match "joeuser") {Write-Host $vm.Name, $vm.pool_id}}

 

This will set the base image and snapshot for new machines that get created in the pool

Update-AutomaticLinkedClonePool -pool_id Train -parentvmpath "/vm/Discovered virtual machine/ViewComposerImages/General_Base" -parentsnapshotpath /08-28-2012/"08-28-2012 Train"

This will send a scheduled recompose to the entire pool

Get-DesktopVM -pool_id Train | Send-LinkedCloneRecompose -schedule "$RECTrain" -parentvmpath "/vm/Discovered virtual machine/ViewComposerImages/General_Base" -parentsnapshotpath /08-28-2012/"08-28-2012 Train" -forceLogoff $true -stopOnError $false

 

This pool contains 30 machines, what I need to do is send a recompose to just 1 machine in this pool

 

Thank you in advance for any assistance..

Need VM portgroup inventory

$
0
0

Hi,

 

I'm looking for VM portgroup inventory script that will list out the following,

 

VMname  VMX location |  NIC name  |  NIC type  | NIC MAC  |  Portgroup Name  |  Switch type  |  Switch name

 

Where,

 

NIC name ..... Name of the nic like "Network adapter 1"

NIC type........ Type like vmxnet3

Switch type.... Type of the switch either a dvSwitch or StandardSwitch

 

Please note this will be run in a vCenter 4 where a mix of ESX 3.5 and ESX(i) 4.1u1 are hosted.

 

Thanks in advance!

Need VM's VLAN inventory for each network adapter

$
0
0

Hi,

 

I'm looking for VM's VLAN inventory for each network adapter, the script will list out the following details in CSV file output.

 

 

VMname  |  Cluster Name |  NIC Name-1  |  VLAN Name  | NIC Name-2  |  VLAN Name  |

 


Thanks in advance!

An item with the same key has already been added.

$
0
0

I'm trying to create a new VM using the command:

 

get-vmhost [esx_server_name] | new-vm -name [vm_name] and get the following error:

 

New-VM : 10/01/2011 16:22:57    New-VM        An item with the same key has already been added.

   + CategoryInfo          : NotSpecified: (:) [New-VM], VimException
   + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM

 

I'm using Powershell v2 and Powercli 4.1.1 and my VMware environment is vSphere 4.0 U1

 

My code was working fine previously, so I'm just wondering if anyone come across this particular error before?

 

Many thanks


VM's and how many snapshots they have.

$
0
0

Is it possible to get a script to list all VM' in a virtual centre and list the number of snapshots for each VM, or list the VM's which have snapshots and list how many snapshots they have.

 

Is this possible.

 

Thanks

Creating list of VMs to exclude from script through .csv file?

$
0
0

Hi,

 

I have a script that runs everyday off hours to verify that my VMs respect certains things, such as having the "VM Tools Upgrade Policy" option checked. The script exports a list of VMs that DO NOT have this option enabled, and then later rectifies the problem. Now, for certain specific VMs, I do not want to have that option enabled, and would like to exclude them from that check. I'm trying to add a list of those VMs that I want to exclude from my VMTools_UpgradePolicy check script through a .csv file that contains their names. Here is what I have :

 

##############################################
#VMTools Upgrade during power cycle  - Report
##############################################
function Report_VMTools_UpgradePolicy {
$list = Import-Csv "C:\VMware\PowerCLI\Scripts\EXCLUDE LIST\EXCLUDE_vmtools_upgradepolicy.csv"
foreach ($entry in $list) {$exclude = Get-VM -Name $entry.Name}
$vms = Get-Vm | where {$_.Name -ne $exclude -and (Get-View -Id $_.Id).Config.Tools.ToolsUpgradePolicy -eq "manual"} | Select Name
$vms | Export-Csv "C:\VMware\PowerCLI\Scripts\REPORTS\vmtools_upgradepolicy.csv" -NoTypeInformation
}

 

The content of the EXCLUDE_vmtools_upgradepolicy.csv is as follow :

 

"Name"
"VM1"
"VM2"

"VM3"

 

I'm trying to get all VMs in my environment that have the ToolsUpgradePolicy -eq "manual" (unchecked), AND that do not match any of the names from my exclude list (VM1, VM2, VM3). My script so far will do what I want, except that only the last entry from my exclude list will be taken into account. VM1 and VM2 will still be reported as VMs that need to be processed.

 

I'm not sure I am taking the right approach with this, I will keep looking for a solution for what I want but any help would be appreciated! I prefer getting my exclude list from a separate file such as that "EXCLUDE_vmtools_upgradepolicy.csv", because I want the other administrators to be able to just open that .csv file and add any VMs to that list without having to touch my scripts.

 

Thanks!

 

Vince

Selected datastore report PowerCLI

$
0
0

Hi,

 

Please can someone suggest a script or modify below one, for only generating a report for particular datastores. I do not want a report for every single datastore in vCenter, only the particular ones.

 

 

=====================================================================

$fileloc = 'c:\output.htm'
$body = "This is Datastore Usage PowerCLI Export“
$mailfrom = "mail address"
$to = "mailaddress1, mailaddress2"
$subject = "This message is sent by PowerCLI script"
$smtpserver = 'IP Address of your SMTP server'

$datastores = get-vmhost  | Get-Datastore | Sort-Object Name
$myColCurrent = @()

foreach ($store in $datastores){
$myObj = "" | Select-Object Name, CapacityGB, UsedGB, PercFree, Type, ID, Accessible
$myObj.Name = $store.Name
$myObj.CapacityGB = "{0:n2}" -f ($store.capacityMB/1kb)
$myObj.UsedGB = "{0:N2}" -f (($store.CapacityMB - $store.FreeSpaceMB)/1kb)
$myObj.PercFree = "{0:N}" -f (100 * $store.FreeSpaceMB/$store.CapacityMB)
$myObj.Type = $store.Type
$temp = Get-View -Id $store.Id
$myObj.ID = Get-DSDevice $store
$myObj.Accessible = $store.Accessible
$myColCurrent += $myObj
}

# Export the output
$myColCurrent | ConvertTo-Html -title "Datastore Information" -body "<H2>Datastore Information.</H2>" | Out-File -Append $fileloc

==========================================================================

 

Thanks,

Argument with InvokeVMScript

$
0
0

I have two questions regarding InvokeVMscript - I have written a short script, but I couldn't code the quotes in the script. I tried to escape the quote but it didn't work. Ultimately I want to avoid typing the quotes on the arguments - myscript vmname "uname -a".

 

Part of the script:

 

param($vm,$script)

Invoke-VMScript -ScriptText $script -VM $vm -HostUser root -HostPassword $hostpasswd -GuestUser root -GuestPassword $guestpasswd

 

 

I found some code that can query vm tools status, how can I intergate them so Invoke-VMScript only execute if vmware tools is running?

 

Get-VM | select Name,
    @{N="Tools Status";E={
        if($_.Guest.Extensiondata.GuestState -eq "notRunning"){
            "Not running"        }
        else{
            $_.Guest.Extensiondata.ToolsVersionStatus.Replace("guestToolsNeedUpgrade","Out of date").Replace("guestToolsNotInstalled","Not installed").Replace("guestToolsCurrent","OK").Replace("guestToolsUnmanaged","Unmanaged")
        }
    }}

Deploy 200 VMs using script.

$
0
0

I have to deploy around 200 vms for a project. I have a customization specification that can be used. Please help me with a script that can feed from the server names in a text file. I will appreciate your suggestion and help.

PowerCLI output coming two times

$
0
0

Hello,

 

I am using the script below to generate the datastore report. This script was provided by the person called 'vlife' (thanks to him).

 

The problem I am facing is, the html output generated by this script is having two duplicate rows for same thing. Not sure where is it msising. See below, would appreciate if someone can help to edit this script.

 

 

DatastoreCapacityGBUsedGBFreeGBPercFree
Std_App187818628.35152.42
Std_App187818628.35152.42
Wyn_Standard_120001765.08234.6712
Wyn_Standard_120001765.08234.6712

 

 

======================================================================

 

$fileloc = 'c:\errors.htm'
$body = "Datastore Info“
$mailfrom = "xxx"
$to = "xxx"
$subject = "This message is sent by PowerCLI script"
$smtpserver = 'xxx'
Add-PSsnapin VMware.VimAutomation.Core
Connect-VIServer -Server 'vcenter' -User 'xxx' -Password 'xxx'

function UsedSpace
{
param($ds)
[math]::Round(($ds.CapacityMB - $ds.FreeSpaceMB)/1024,2)
}

function FreeSpace
{
param($ds)
[math]::Round($ds.FreeSpaceMB/1024,2)
}

function PercFree
{
param($ds)
[math]::Round((100 * $ds.FreeSpaceMB / $ds.CapacityMB),0)
}

$Datastores = Get-datastore -name "Datastore1", "Datastore2"
$myCol = @()
ForEach ($Datastore in $Datastores)
{
$myObj = "" | Select-Object Datastore, UsedGB, FreeGB, PercFree
$myObj.Datastore = $Datastore.Name
$myObj.UsedGB = UsedSpace $Datastore
$myObj.FreeGB = FreeSpace $Datastore
$myObj.PercFree = PercFree $Datastore
$myCol += $myObj
}

$a = "<style>"
$a = $a + "BODY{background-color:#CCFFFF;}"
$a = $a + "TABLE{border-width: 20px;border-style: ridge;border-bottom-color:#3399FF;border-right-color:#3399FF;border-top-color:#336633;border-left-color:#336633;border-collapse: collapse;}"
$a = $a + "TH{border-width: 3px;padding: 5px;border-style: ridge;border-color: black;background-color:#99FFFF}"
$a = $a + "TD{border-width: 3px;padding: 3px;border-style: ridge;border-color: black;background-color:#CCFFFF;text-align:center;}"
$a = $a + "</style>"

$myCol | Sort-Object PercFree |
ConvertTo-HTML -head $a -body "<H2>Datastore Usage</H2>" |
Out-File $fileloc

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($fileloc)
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$msg.From = $mailfrom
foreach($mailTo in $to){
$msg.To.Add($mailto)
}
$msg.Subject = $subject
$msg.Body = $body
$msg.Attachments.Add($att)
$smtp.send($msg)
$att.Dispose()
$msg.Dispose()
Start-Sleep -s 5
if (Test-Path $fileloc){Remove-Item -Path $fileloc -confirm:$false}

A simple script to find old snapshots and notify via email

$
0
0

I wrote this script to catch snapshots that myself or coworkers forgot to delete.  There are much more complex scripts out there but this one may be helpful to new PowerCLI users to get their feet wet due to it's simplicity.  I mentioned this script on vmworld.socialcast.com and got ALOT of responses, so here it is.

 

 

#Catch-Snap.ps1
#Todd Cash
#The Jackson Laboratory
#8.12.2010
#todd.cash@jax.org

#This script will connect to each Virtual Center server you list and check all virtual machines
#for snapshots over the $snapAgeLimit
#It is meant to find snapshots that you or your trusty coworkers forgot to cleanup
#This script is meant to be simple but functional working example for those just dipping into PowerCLI (It has saved me countless times)
#This script does not get all the child snaps and is not the most elegant ever written (VMWare vSphere PowerCLi Reference, Chapter 8 includes very good examples, worth every penny)

#if the PowerCLI snapin is not loaded, load it
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{
    Add-PsSnapin VMware.VimAutomation.Core
}

#######Begin Config#######

#snapshot age limit (in days)
$snapAgelimit='7'
#your smtp FQDN
$smtp = 'smtp.company.com'
#the address to send the email from
$smtpFrom = 'svc-vsphere@company.com'
#who to send the email to
$smtptos = ('you@company.com', 'coworker@company.com')
#your Virtual Center servers
$Viservers = ('vcenter01','vcenter02')

#######End Config#######
foreach ($viserver in $viservers){
    #connect to VI server as current user
    Connect-VIServer -Server $viserver -Protocol https

    #calculate metadata time stamp limit (how old it should be before processed)
    $currentDate = [System.DateTime]::Now
    $snapAgelimitdate = $currentDate.AddDays(- $snapAgelimit)

    #find and process the snapshots
    $snapShots = get-vm | get-snapshot | Select VM,Name,Created,Description, SizeMB
    foreach ($snapShot in $snapShots){

        $VM = $snapShot.VM
        $Name = $snapShot.Name
        $Created = $snapShot.Created
        $Description = $snapShot.Description
        $Size = $snapShot.SizeMB
        #ignore VEEAM restore points
        if ((!($VM)) -or ($Name -match "Restore Point")){
        continue
        }
        #check the creation date on the VM vs the agelimit
        "Checking $VM"
        if ($Created -lt $snapAgelimitdate){
            #getting the snapshot creator is a bit more complex.
            $taskMgr = Get-View TaskManager
            #define the number of tasks to return
            $numberofTasks = 999         
            #create a filter based on the snapshot creation time (5 seconds before $created)
            $filter = New-Object VMware.Vim.TaskFilterSpec
            $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
            $filter.Time.beginTime = (($Created).AddSeconds(-5))
            $filter.Time.timeType = "startedTime"
            #get all the tasks based on the filter
            $taskCollector = Get-View ($taskMgr.CreateCollectorForTasks($filter))
            #rewind to the begin time specified in the filter (setting equal to blah just keeps it's output off the screen)
            $blah = $taskCollector.RewindCollector
            #read in the first 999 tasks from our starting point (which is 5 seconds before $created)
            $allTasks= $taskCollector.ReadNextTasks($numberofTasks)
            #crank through those first 999 tasks
            foreach ($task in $alltasks){
                #find the createSnapshot  task for $VM
                if (($task.DescriptionId -eq "VirtualMachine.createSnapshot") -and ($task.EntityName -eq $VM)){
                    #Get the reason username which is our creator                      
                    $creator = $task.reason.username 
                }
            }  
            "$Name ($Description) on $VM is $Size MB and was created over $snapAgelimit days ago ($Created) by $creator."
            $body = "$Name ($Description) on $VM is $Size MB and was created over $snapAgelimit days ago ($Created) by $creator."
            #send email
            $SmtpClient = new-object system.net.mail.smtpClient
            $MailMessage = New-Object system.net.mail.mailmessage
            $SmtpClient.Host = $smtp
            $mailmessage.from = $smtpfrom
            foreach ($smtpto in $smtptos){
                $mailmessage.To.add($smtpto)
            }
            $mailmessage.Subject = "Old VM Snapshots Found”
            $mailmessage.Body = $body
            $smtpclient.Send($mailmessage)
  }
    }
    Disconnect-VIServer -confirm:$false
}  


Set-VMHostAuthentication

$
0
0

Hi all,

i'm scripting to set up a new ESXi5...works fine so far, but i can't join the ESXi to a Windows ActiveDirectory 2008 Domain.

This is what i'm trying:

 


get-vmHost ESXi01 | Get-VMHostAuthentication | Set-VMHostAuthentication -Domain $domain -JoinDomain:$true -Credential $global:vCred -Force:$true -Confirm:$false



and this is the output:

 

Set-VMHostAuthentication : Der Parametersatz kann mit den angegebenen benannten Parametern nicht aufgelöst werden.
Bei C:\Users\LB025304\Documents\PowerShell\Configure-ESXi_LEW_Trunk.ps1:998 Zeichen:70
+ $global:vmHost | Get-VMHostAuthentication | Set-VMHostAuthentication <<<< -Domain $domain -JoinDomain:$true -Credent
ial $global:vCred -Force:$true -Confirm:$false
+ CategoryInfo : InvalidArgument: (:) [Set-VMHostAuthentication], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,VMware.VimAutomation.ViCore.Cmdlets.Commands.Host.SetVMHostAuthenticat
ion


I know this worked sometimes, but doesn't anymore...

Any suggestions?

 

Thanks!

vNetwork Distributed Switch configuration

$
0
0

Hi,

can someone help me configure a vNetwork Distributed switch using powercli?

i need help with quite a few things:

  • Dicovery protocol should be enabled, using LLDP and use the both parameter.
  • Administrator contact information should be test test and the e-mail address test@home.test.
  • NIOC should be activated and i would like to change the shares value for the predefined groups and also create one user defined network resource pool called development.
  • change the uplink names

 

I have created the vNetwork Distributed switch with correct MTU and number of uplink ports using the vSphere Distributed Switch PowerCLI cmdlets.

 

Any help appreciated.

 

//Magnus

wait for a task to finish - but only for 10 minutes or so

$
0
0

Hi,

 

I found some code (and I can't remember where) to make a task wait until it's finished. I'm thinking that just in case this task is hung or something, it would be good to wait for a while - then give up and exit the script. The wait part is working perfectly.

 

so - first I deploy a vapp in vCloud director using one of velemental's unofficial cmdlets Instantiate-VApp

 

$deployedvapp1 = Instantiate-VApp -name $config1 -catalogname "class deployments" -VAppTemplateName $cat1 -orgvdcname "vs51 org vdc" -mode Clone

 

this part waits until it's finished - then continues the script:

 

if ( $deployedvapp1.Tasks.Task )
{    foreach($task in $deployedvapp1.Tasks.Task)
    {
    write-host "waiting for" $config1 "to finish deploying..." -fore green
    $task.Wait()
    }
} # end if "if" actions
else { write-host `n $config1 "is already done - no need to wait" -fore yellow -back black }

 

Is there an easy way to make it give up if there is a problem? In VB you can put a number inside $task.Wait()  - like $task.Wait(10000) but Powershell doesn't like this ;-)

 

Thanks.

Adding static iSCSI targets

$
0
0

Hi, I am attempting to add a few iSCSI targets to our hosts via vSphere PowerCLI.

 

I have an EqualLogic group setup and I already have several static iSCSI volmes mapped for datastores.  I need to add a handful more to each host.

 

But every time I attempt to use the new-iscsihbatarget cmdlet I get an error saying the target already exists.. which is, of course, true.  My EqualLogic group (target) does already exists with several different volumes already mapped.

 

I am looking for a way to add additional volumes statically from the same group without getting the error returned.

 

Has anyone else done this?

 

thanks in advance.

List total number of vCPU per ESX host to avoid CPU over allocation when deploying VM

$
0
0
Hi,
Can anyone please share your script to give a listing for all if VMHost / ESX CPU total count managed by VCenter that is available ?
this is for me to be able to determine whic VMhost I can deploy my VM into to avoid vCPU over allocation.
I understand that the best practice is maximum 4 single vCPU VM per core, so here's the example:
2 sockets x 6 core = 12 vCPU available
therefore there can be maximum of 12 x 4 = 48 vCPU total used maximum.
Viewing all 16717 articles
Browse latest View live


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