lukeglazebrook's Posts

How can I easily check if I am maxing out the queue depth for my storage adapter?  I already know how to check its maximums, just trying to find a bottle neck.  I already know the LUN is getting ... See more...
How can I easily check if I am maxing out the queue depth for my storage adapter?  I already know how to check its maximums, just trying to find a bottle neck.  I already know the LUN is getting hammered (see screenshot) compared the others but the storage guy says that the storage should be abel to handle it. Thanks in advance
Wow thanks mate, I just tried to amend it so it exports to a CSV by adding the following...  Can you please educate me please and tell me how I am being a dipstick
Hi, I suspect someone has done something like this before, I have been asked to by the licencing manager if I could pull a report for the entire estate providing the following criteria... -... See more...
Hi, I suspect someone has done something like this before, I have been asked to by the licencing manager if I could pull a report for the entire estate providing the following criteria... - All VM's - Their respective cluster - The socket configuration - Core configuration I Had a bit of a look on the internet and surprisingly not found this, wondered if anyone could kindly share if they have done something similar (I'm sure someone must have).  Licencing is not my specialist area to be honest and I'm also not sure its the licencing managers either so hopefully I will provide what he is after. 
"Ah, but wait, you seem to do the first Get-Datastore (there are two in the script, but I guess you know) before you do the COnnect-VIServer, that will not work. Unless I'm missing something her... See more...
"Ah, but wait, you seem to do the first Get-Datastore (there are two in the script, but I guess you know) before you do the COnnect-VIServer, that will not work. Unless I'm missing something here" You are a legend among human beings, it worked first time after the change.  One thing I failed to mention was that the script was failing mainly when its was called via a wrapper script from OpenSSH.  It 99% of the time when it was called via OpenSSH changed the order of things as you suggested and now its working. And when are you going to take a day off mate?  I hope VMware pay you?
It the error is also states "You cannot call a method on a null-valued expression" At C:\Users\matadm\createRP_TSD.ps1:128 char:1 + $ds.ExtentionData.RefreshDatastoreStorageInfo() I'm guessi... See more...
It the error is also states "You cannot call a method on a null-valued expression" At C:\Users\matadm\createRP_TSD.ps1:128 char:1 + $ds.ExtentionData.RefreshDatastoreStorageInfo() I'm guessing its failing to retrieve information, however I definitely works sometimes. I tested this all over Xmas and it was flawless but now I'm back to this again
I have a script that appears to be working intermittently, generally it fails on character 1 line 128 (highlighted below) I think the VC is not coming back with the information and consequently t... See more...
I have a script that appears to be working intermittently, generally it fails on character 1 line 128 (highlighted below) I think the VC is not coming back with the information and consequently the script is failing on the catch... else {   Write-Host "There is insufficient space on the target datastore. Please increase Space to continue"   Write-Output "There is insufficient space on the target datastore. Please increase Space to continue" >> $logfile   Write-Host "Exiting with code 1"   Write-Output "Exiting with code 1" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure1 -SmtpServer $SMTPServer -port $SMTPPort   exit 1 The architect has suggested that it might be a race condition, can anyone with significantly more experience than me (that's pretty anyone) suggest an alteration that may well overcome this?  I suppose I could put pauses in but I'm not 100% where would be the best place to do it or if that might be the mickey mouse method? Error # ============================================================================================== # NAME: CloneVMs # # AUTHOR: Luke # DATE  : 09/10/2015 # # COMMENT: Creates a clone/backup of the VMs outlined in the text and names them using the # passed param.  VM's will be named as per the following example VM1-12345678      # # # # * Software Dependencies: * # - Microsoft PowerShell * # - VMWare PowerCLI * # ============================================================================================== # Parameters # ============================================================================================== # The below parameter supplied by Control-M refers to cycle and recovery point prefix, # the date can be added automatically however this functionality has been disabled. param ([string]$CYRPYYMMDD) # ============================================================================================== # Functions # ============================================================================================== #Function to allow you to check if a command is loaded Function Check-Command($cmdname) {     return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue) } # ============================================================================================== # Varibles # ============================================================================================== # Add the vmware snapin for powershell # Add-PSSnapin VMware.VimAutomation.Core # Add the vmware snapin for powershell (stops you seeing the error messages) if (Check-Command "Connect-VIServer") {   Write-Host "Automation Tool already loaded" } else {   #If not already loaded load the snapin   Write-Host "Loading Automation Tools"   Add-PSSnapin VMware.VimAutomation.Core } # backup = true appends date; false creates a clone with the same name. $backup = "True" # debug - true : will not clone vm; FALSE will clone the vm. $debug = "FALSE" # Target Datastore $targetdatastore = "LUN9_BASIC_MATADM_ONLY" #Refers to the percentage of free space for the DS space check $freePerc = 10 # Target location - existing folder in vcenter structure, where the clones will be place $targetlocation = "TSD DMAT For ControlM BackUp Cycles" # Set date $datestart = (get-date -uformat %Y%m%d) # Name a logfile to capture results. $logfile = $datestart + "_VMClones_bulk.txt" # write-output "New Log ($datestart) - ($logfile)" >> $logfile # Gets the list of VMs from the file associated with this script $VmFileList = Get-Content VmsToCloneList.list | Select-Object -Skip 3 # $ds = Get-Datastore -Name $targetdatastore #Email varibles $From = "" $To = "" $Cc = "" #$Attachment = "C:\temp\Some random file.txt" $Subject = "!! TEST DMAT createRP TEST !!" $BodySuccess = "A DMAT VM has sucessfully backed up to the specified destination datastore and inventory organisational folder within vSphere" $BodyFailure1 = "The combined provisioned VMDK usage of the VM's exceeds the capacity of the destination datastore or the datstore does not exist, exiting with code 1" $BodyFailure2 = "There is insufficient space on the target datastore, increase Space to continue, Exiting with code 1" $BodyFailure3 = "A VM by the name specified cant be found perhaps it does not exists? Exiting with code 1" $SMTPServer = "" $SMTPPort = "25" # Establish Connection $Creds = Get-VICredentialStoreItem -Host 127.0.0.1 -File C:\Users\matadm\PS_ITC_BAS.xml Connect-VIServer 127.0.0.1 -User $Creds.User -Password $Creds.Password # Gets the VM total ProvisionedSpaceGB for all VM's in the list.  # Additionally ensures whitespaces and hashes are ignored effectively # creating a clean list which calculates/creates the varible required for validation check 1  $vmCleanedList = New-Object system.Collections.ArrayList # Loop through our VM file List and clean is up, check for incorrectly specified VM's ForEach ($vmname in $VmFileList) {   if ([string]::IsNullOrWhiteSpace($vmname) -or $vmname.StartsWith("#"))   {   write-host("Invalid machine name - $vmname")   }   else   {   #Should trim vmname to ensure we have no spaces front or end   $vm = Get-VM $vmname   $vmCleanedList.Add($vmname)   $TotalRequiredGB += $vm.ProvisionedSpaceGB   }   Write-Host "Total Required = $TotalRequiredGB" } # ============================================================================================== # Validation checks Prior to starting the clone script # ============================================================================================== # Refreshes the datastore storage infomation prior. $ds.ExtensionData.RefreshDatastoreStorageInfo() # Validation check 1, Checks if the combined provisioned VMDK usage of the VM's exceeds the capacity of the destination datastore? if(($ds.FreeSpaceGB -gt $TotalRequiredGB)) {   Write-Host "Continue with your script" } else {   Write-Host "There is insufficient space on the target datastore. Please increase Space to continue"   Write-Output "There is insufficient space on the target datastore. Please increase Space to continue" >> $logfile   Write-Host "Exiting with code 1"   Write-Output "Exiting with code 1" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure1 -SmtpServer $SMTPServer -port $SMTPPort   exit 1 } $ds = Get-Datastore -Name $targetdatastore # Validation check 2, do you have X % free datatstorespace? if((($ds.FreeSpaceGB/$ds.CapacityGB)*100) -ge $freePerc) {     Write-Host "Continue with your script" } else {     Write-Host "There is less than X% space free on the datastore. Please increase Space to continue"      Write-Output "There is less than X% space free on the datastore. Please increase Space to continue" >> $logfile     Write-Host "Exiting with code 2"     Write-Output "Exiting with code 2" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure2 -SmtpServer $SMTPServer -port $SMTPPort     exit 2 } #Hack + duplication of effort #$VmListFile = Get-Content VmsToCloneList.list | Select-Object -Skip 3 ForEach ($vmname in $vmCleanedList)             {                         # The VM Object                         $vm = Get-VM -Name $vmname                         # Target Host - use the same host as the current VM ( this is faster than cloning across hosts ).                         $targethost = $vm.vmhost.name                         # Target VM Name - name if BACKUP is FALSE                         $vmtarget = $vmname                         #                         $datastore = get-datastore $targetdatastore -vmhost $targethost # ============================================================================================== # Begin the actual cloning script # ==============================================================================================                         if ($vm -ne $null)                                     {                                                 Write-Host "A VM named $VM exists. Starting clone"                                                 Write-output "A VM named $VM exists. Starting clone"  >> $logfile                                     }                         else                                     {                                                 Write-Host "A VM by the name specified cant be found perhaps it does not exists?"                                                 Write-Output "A VM by the name specified cant be found perhaps it does not exists?" >> $logfile                                                 Write-Host "Exiting with code 3"                                                 Write-Output "Exiting with code 3" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure3 -SmtpServer $SMTPServer -port $SMTPPort                                                 exit 3                                     }                         if ($backup -eq "TRUE")                                      {                                                 # Clone the VM to backup_vmname_todaysdate                                                 $vmtarget = $vmtarget + "-" + $CYRPYYMMDD #+ "-" + $datestart                                     }                         # nice colors if you are watching the script run                         write-host -foregroundcolor green "Cloning $vm to $vmtarget"                         write-output -foregroundcolor green "Cloning $vm to $vmtarget" >> $logfile                         new-vm -name $vmtarget -vm $vm -vmhost $targethost -datastore $datastore -Location $targetlocation -DiskStorageFormat thin   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodySuccess -SmtpServer $SMTPServer -port $SMTPPort              } Write-Host "Complete" Exit 0 # COMPLETED
I have a follow up question if your around mate, the script seems to work great now.  Just one strange issue, on rare occasions during testing the script will begin cloning all machines simultane... See more...
I have a follow up question if your around mate, the script seems to work great now.  Just one strange issue, on rare occasions during testing the script will begin cloning all machines simultaneously rather than one by one.  Are you able to speculate why that might occasionally happen?  Hope you you had a nice Xmas incidentally assuming that's something you celebrate, unfortunately I was working
And if anyone has any insight or even a theory as to why this might be happening I would appreciate your opinion, below is an example of the script... # =====================================... See more...
And if anyone has any insight or even a theory as to why this might be happening I would appreciate your opinion, below is an example of the script... # ============================================================================================== # NAME: RecoverVMs # # AUTHOR: Luke Glazebrook # DATE  : 09/10/2015 # # COMMENT: Recovers cloned VMs and uses passed param to specify which cycle of VMs to restore, #   and removes the -$CYRPYYMMDD ammendment at the end of the VM name.     #  # # # * Software Dependencies: * # - Microsoft PowerShell * # - VMWare PowerCLI * # ============================================================================================== # Parameters # ============================================================================================== # The below parameter supplied by Control-M refers to cycle and recovery point prefix, # the date can be added automatically however this functionality has been disabled. param ([string]$CYRPYYMMDD) # ============================================================================================== # Functions # ============================================================================================== #Function to allow you to check if a command is loaded Function Check-Command($cmdname) {     return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue) } # ============================================================================================== # Varibles # ============================================================================================== # Add the vmware snapin for powershell # Add-PSSnapin VMware.VimAutomation.Core # Add the vmware snapin for powershell (stops you seeing the error messages) if (Check-Command "Connect-VIServer") {   Write-Host "Automation Tool already loaded" } else {   #If not already loaded load the snapin   Write-Host "Loading Automation Tools"   Add-PSSnapin VMware.VimAutomation.Core } # backup = true appends date; false creates a clone with the same name. $backup = "True" # debug - true : will not clone vm; FALSE will clone the vm. $debug = "FALSE" # Target Datastore $targetdatastore = "LS-H249-DS1-320GB" #Refers to the percentage of free space for the DS space check $freePerc = 5 # Target location - existing folder in vcenter structure, where the clones will be place $targetlocation = "ProdFolder" # Set date $datestart = (get-date -uformat %Y%m%d) # Name a logfile to capture results. $logfile = $datestart + "_VMClones_bulk.txt" # write-output "New Log ($datestart) - ($logfile)" >> $logfile # Gets the list of VMs from the file associated with this script $VmFileList = Get-Content VmsToCloneList.list # $ds = Get-Datastore -Name $targetdatastore #Email varibles $From = "vCenter@lbase.homeip.net" $To = "luke@lbase.homeip.net" $Cc = "luke@lbase.homeip.net" #$Attachment = "C:\temp\Some random file.txt" $Subject = "!! TEST DMAT Report TEST !!" $BodySuccess = "The DMAT VMs have been sucessfully recovered to the specified destination datastore and inventory organisational folder within vSphere" $BodyFailure1 = "The combined provisioned VMDK usage of the VM's exceeds the capacity of the destination datastore, exiting with code 1" $BodyFailure2 = "There is insufficient space on the target datastore, increase Space to continue, Exiting with code 2" $BodyFailure3 = "A VM by the name specified cant be found perhaps it does not exists? Exiting with code 3" $SMTPServer = "192.168.0.101" $SMTPPort = "25" # Establish Connection Connect-VIServer -Server 127.0.0.1 -User administrator@blah -Password blah # ============================================================================================== # Deletes current working test VMs in preperation for the recovery of the backup clones # ============================================================================================== foreach($vm in $VmFileList){ $active = Get-VM $vm if($active.PowerState -eq "PoweredOn"){ Stop-VM -VM $vm -Confirm:$false Start-Sleep -Seconds 10 Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} else {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} } # ============================================================================================== # Gets the VM total ProvisionedSpaceGB for all VM's in the list.  # Additionally ensures whitespaces and hashes are ignored effectively # creating a clean list which calculates/creates the varible required for validation check 1 # ==============================================================================================   $vmCleanedList = New-Object system.Collections.ArrayList # Loop through our VM file List and clean is up, check for incorrectly specified VM's ForEach ($vmname in $VmFileList) {   if ([string]::IsNullOrWhiteSpace($vmname) -or $vmname.StartsWith("#"))   {   write-host("Invalid machine name - $vmname")   }   else   {   #Should trim vmname to ensure we have no spaces front or end   $vm = Get-VM $vmname   $vmCleanedList.Add($vmname)   $TotalRequiredGB += $vm.ProvisionedSpaceGB   }   Write-Host "Total Required = $TotalRequiredGB" } # ============================================================================================== # Validation checks Prior to starting the clone script # ============================================================================================== # Validation check 1, Checks if the combined provisioned VMDK usage of the VM's exceeds the capacity of the destination datastore? if(($ds.FreeSpaceGB -gt $TotalRequiredGB)) {   Write-Host "Continue with your script" } else {   Write-Host "There is insufficient space on the target datastore. Please increase Space to continue"   Write-Output "There is insufficient space on the target datastore. Please increase Space to continue" >> $logfile   Write-Host "Exiting with code 1"   Write-Output "Exiting with code 1" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure1 -SmtpServer $SMTPServer -port $SMTPPort   exit 1 } $ds = Get-Datastore -Name $targetdatastore # Validation check 2, do you have X % free datatstorespace? if(($ds.FreeSpaceGB/$ds.CapacityGB*100) -ge $freePerc) {     Write-Host "Continue with your script" } else {     Write-Host "There is less than X% space free on the datastore. Please increase Space to continue"      Write-Output "There is less than X% space free on the datastore. Please increase Space to continue" >> $logfile     Write-Host "Exiting with code 2"     Write-Output "Exiting with code 2" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure2 -SmtpServer $SMTPServer -port $SMTPPort     exit 2 } #Hack + duplication of effort #$VmListFile = Get-Content VmsToCloneList.list | Select-Object -Skip 3 ForEach ($vmname in $vmCleanedList)             {                         # The VM Object   $RemoveCYRPYYMMDD = $vmname + "-" + $CYRPYYMMDD                         $vm = Get-VM -Name $RemoveCYRPYYMMDD                         # Target Host - use the same host as the current VM ( this is faster than cloning across hosts ).                         $targethost = $vm.vmhost.name                         # Target VM Name - name if BACKUP is FALSE                         $vmtarget = $vmname                         #                         $datastore = get-datastore $targetdatastore -vmhost $targethost # ============================================================================================== # Begin the actual cloning script # ==============================================================================================                         if ($vm -ne $null)                                     {                                                 Write-Host "A VM named $VM exists. Starting clone"                                                 Write-output "A VM named $VM exists. Starting clone"  >> $logfile                                     }                         else                                     {                                                 Write-Host "A VM by the name specified cant be found perhaps it does not exists?"                                                 Write-Output "A VM by the name specified cant be found perhaps it does not exists?" >> $logfile                                                 Write-Host "Exiting with code 3"                                                 Write-Output "Exiting with code 3" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure3 -SmtpServer $SMTPServer -port $SMTPPort                                                 exit 3                                     }                         if ($backup -eq "TRUE")                                      {                                                 # Clone the VM to backup_vmname_todaysdate                                                 $vmtarget #= $vmtarget + "-" + $CYRPYYMMDD #+ "-" + $datestart                                     }                         # nice colors if you are watching the script run                         write-host -foregroundcolor green "Cloning $vm to $vmtarget"                         write-output -foregroundcolor green "Cloning $vm to $vmtarget" >> $logfile                         new-vm -name $vmtarget -vm $vm -vmhost $targethost -datastore $datastore -Location $targetlocation -DiskStorageFormat thin   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodySuccess -SmtpServer $SMTPServer -port $SMTPPort              } Write-Host "Complete" Exit 0 # COMPLETED
I have a script that performs a space check prior to cloning some VM's onto a datastore.  Sometimes it appears to fail (well it exits by design) and behaves as if there was insufficient space.  I... See more...
I have a script that performs a space check prior to cloning some VM's onto a datastore.  Sometimes it appears to fail (well it exits by design) and behaves as if there was insufficient space.  If however I manually refresh the datastore properties by clicking the button shown in the screenshot prior it sppears to work consistently.  Can someone please provide an example if how I can essentially press this button for a specific datastore in PowerCLi so I can incorperate it into my script. Thanks  
No a fresh clone, not linked. Basically VM's form a list are cloned as emergency backups just in case (thats a seperate script and works fine, they get cloned to a specific datastore).  This s... See more...
No a fresh clone, not linked. Basically VM's form a list are cloned as emergency backups just in case (thats a seperate script and works fine, they get cloned to a specific datastore).  This script is the rollback/restore script which clones the clones back to production and amends the VM name (removing the version & date e.g VM1_1 151221) should everything go horribly wrong.  I just need the below to recover back to a datastore cluster called "TestCluster" rather than the specific datastore   Been hacking it to bits with no joy, my most recent attempt resulted in the error below after having removed lines related to the "Validation checks prior" (Non working script # ============================================================================================== # NAME: RecoverVMs # # AUTHOR: Luke Glazebrook # DATE  : 09/10/2015 # # COMMENT: Recovers cloned VMs and uses passed param to specify which cycle of VMs to restore, #  and removes the -$CYRPYYMMDD ammendment at the end of the VM name. # # # # * Software Dependencies: * # - Microsoft PowerShell * # - VMWare PowerCLI * # ============================================================================================== # Parameters # ============================================================================================== # The below parameter supplied by Control-M refers to cycle and recovery point prefix, # the date can be added automatically however this functionality has been disabled. param ([string]$CYRPYYMMDD) # ============================================================================================== # Functions # ============================================================================================== #Function to allow you to check if a command is loaded Function Check-Command($cmdname) {     return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue) } # ============================================================================================== # Varibles # ============================================================================================== # Add the vmware snapin for powershell # Add-PSSnapin VMware.VimAutomation.Core # Add the vmware snapin for powershell (stops you seeing the error messages) if (Check-Command "Connect-VIServer") {   Write-Host "Automation Tool already loaded" } else {   #If not already loaded load the snapin   Write-Host "Loading Automation Tools"   Add-PSSnapin VMware.VimAutomation.Core } # backup = true appends date; false creates a clone with the same name. $backup = "True" # debug - true : will not clone vm; FALSE will clone the vm. $debug = "FALSE" # Target Datastore $targetdatastore = "TestCluster" #Refers to the percentage of free space for the DS space check $freePerc = 5 # Target location - existing folder in vcenter structure, where the clones will be place $targetlocation = "ProdFolder" # Set date $datestart = (get-date -uformat %Y%m%d) # Name a logfile to capture results. $logfile = $datestart + "_VMClones_bulk.txt" # write-output "New Log ($datestart) - ($logfile)" >> $logfile # Gets the list of VMs from the file associated with this script $VmFileList = Get-Content VmsToCloneList.list # $ds = Get-Datastore -Name $targetdatastore #Email varibles $From = "vCenter@lbase.homeip.net" $To = "luke@lbase.homeip.net" $Cc = "luke@lbase.homeip.net" #$Attachment = "C:\temp\Some random file.txt" $Subject = "!! TEST DMAT Report TEST !!" $BodySuccess = "The DMAT VMs have been sucessfully recovered to the specified destination datastore and inventory organisational folder within vSphere" $BodyFailure1 = "The combined provisioned VMDK usage of the VM's exceeds the capacity of the destination datastore, exiting with code 1" $BodyFailure2 = "There is insufficient space on the target datastore, increase Space to continue, Exiting with code 2" $BodyFailure3 = "A VM by the name specified cant be found perhaps it does not exists? Exiting with code 3" $SMTPServer = "192.168.0.101" $SMTPPort = "25" # Establish Connection Connect-VIServer -Server 127.0.0.1 -User administrator@lbase -Password omega1 # ============================================================================================== # Deletes current working test VMs in preperation for the recovery of the backup clones # ============================================================================================== foreach($vm in $VmFileList){ $active = Get-VM $vm if($active.PowerState -eq "PoweredOn"){ Stop-VM -VM $vm -Confirm:$false Start-Sleep -Seconds 10 Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} else {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} } # ============================================================================================== # Gets the VM total ProvisionedSpaceGB for all VM's in the list. # Additionally ensures whitespaces and hashes are ignored effectively # creating a clean list which calculates/creates the varible required for validation check 1 # ============================================================================================== $vmCleanedList = New-Object system.Collections.ArrayList # Loop through our VM file List and clean is up, check for incorrectly specified VM's ForEach ($vmname in $VmFileList) {   if ([string]::IsNullOrWhiteSpace($vmname) -or $vmname.StartsWith("#"))   {   write-host("Invalid machine name - $vmname")   }   else   {   #Should trim vmname to ensure we have no spaces front or end   $vm = Get-VM $vmname   $vmCleanedList.Add($vmname)   $TotalRequiredGB += $vm.ProvisionedSpaceGB   }   Write-Host "Total Required = $TotalRequiredGB" } #Hack + duplication of effort #$VmListFile = Get-Content VmsToCloneList.list | Select-Object -Skip 3 ForEach ($vmname in $vmCleanedList)             {                         # The VM Object   $RemoveCYRPYYMMDD = $vmname + "-" + $CYRPYYMMDD                         $vm = Get-VM -Name $RemoveCYRPYYMMDD                         # Target Host - use the same host as the current VM ( this is faster than cloning across hosts ).                         $targethost = $vm.vmhost.name                         # Target VM Name - name if BACKUP is FALSE                         $vmtarget = $vmname                         #                         $datastore = get-datastore $targetdatastore -vmhost $targethost # ============================================================================================== # Begin the actual cloning script # ==============================================================================================                         if ($vm -ne $null)                                     {                                                 Write-Host "A VM named $VM exists. Starting clone"                                                 Write-output "A VM named $VM exists. Starting clone"  >> $logfile                                     }                         else                                     {                                                 Write-Host "A VM by the name specified cant be found perhaps it does not exists?"                                                 Write-Output "A VM by the name specified cant be found perhaps it does not exists?" >> $logfile                                                 Write-Host "Exiting with code 3"                                                 Write-Output "Exiting with code 3" >> $logfile   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodyFailure3 -SmtpServer $SMTPServer -port $SMTPPort                                                 exit 3                                     }                         if ($backup -eq "TRUE")                                     {                                                 # Clone the VM to backup_vmname_todaysdate                                                 $vmtarget #= $vmtarget + "-" + $CYRPYYMMDD #+ "-" + $datestart                                     }                         # nice colors if you are watching the script run                         write-host -foregroundcolor green "Cloning $vm to $vmtarget"                         write-output -foregroundcolor green "Cloning $vm to $vmtarget" >> $logfile                         new-vm -name $vmtarget -vm $vm -vmhost $targethost -datastore $datastore -Location $targetlocation -DiskStorageFormat thin   Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `   -Body $BodySuccess -SmtpServer $SMTPServer -port $SMTPPort        } Write-Host "Complete" Exit 0 # COMPLETED Fails with the below... PS C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN> .\restoreRP_TSDBeta1.ps1 "1 151221" Automation Tool already loaded Get-Datastore : 12/17/2015 2:05:58 PM    Get-Datastore        Datastore with name 'TestCluster' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:67 char:7 + $ds = Get-Datastore -Name $targetdatastore +      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-Datastore], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetDat   astore Name                          Port  User ----                          ----  ---- 127.0.0.1                      443  LBASE\Administrator Get-VM : 12/17/2015 2:05:59 PM    Get-VM        VM with name '#' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:11 + $active = Get-VM $vm +          ~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Could not find VirtualMachine with name '#'. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (#:String) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle   ts.Commands.RemoveVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : 12/17/2015 2:05:59 PM    Get-VM        VM with name '# List of VM's for DMAT ' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:11 + $active = Get-VM $vm +          ~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Could not find VirtualMachine with name '# List of VM's for DMAT '. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (# List of VM's for DMAT :String) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle   ts.Commands.RemoveVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : 12/17/2015 2:05:59 PM    Get-VM        VM with name '#' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:11 + $active = Get-VM $vm +          ~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Could not find VirtualMachine with name '#'. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (#:String) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle   ts.Commands.RemoveVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : 12/17/2015 2:05:59 PM    Get-VM        VM with name 'yVM1' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:11 + $active = Get-VM $vm +          ~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Could not find VirtualMachine with name 'yVM1'. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (yVM1:String) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle   ts.Commands.RemoveVM Remove-VM : 12/17/2015 2:05:59 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : 12/17/2015 2:06:00 PM    Get-VM        VM with name 'yVM2' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:11 + $active = Get-VM $vm +          ~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:06:00 PM    Remove-VM        Could not find VirtualMachine with name 'yVM2'. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (yVM2:String) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_ObjectNotFound,VMware.VimAutomation.ViCore.Cmdle   ts.Commands.RemoveVM Remove-VM : 12/17/2015 2:06:00 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:18 + $active = Get-VM $vm +                  ~~~     + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValidationException     + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:06:00 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:95 char:18 + $active = Get-VM $vm +                  ~~~     + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValidationException     + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM Remove-VM : 12/17/2015 2:06:00 PM    Remove-VM        Value cannot be found for the mandatory parameter VM At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:101 char:2 + {Remove-VM -VM $vm -DeleteFromDisk -Confirm:$false -RunAsync} +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : NotSpecified: (:) [Remove-VM], VimException     + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.RemoveVM Invalid machine name - # Total Required = Invalid machine name - # List of VM's for DMAT Total Required = Invalid machine name - # Total Required = Get-VM : 12/17/2015 2:06:00 PM    Get-VM        VM with name 'yVM1' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:124 char:9 +        $vm = Get-VM $vmname +              ~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM 0 Total Required = Get-VM : 12/17/2015 2:06:00 PM    Get-VM        VM with name 'yVM2' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:124 char:9 +        $vm = Get-VM $vmname +              ~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM 1 Total Required = Invalid machine name - Total Required = Invalid machine name - Total Required = get-datastore : 12/17/2015 2:06:01 PM    Get-Datastore        Datastore with name 'TestCluster' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:152 char:38 +                        $datastore = get-datastore $targetdatastore -vmhost $tar ... +                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-Datastore], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetDat   astore A VM named yVM1-1 151221 exists. Starting clone yVM1 Cloning yVM1-1 151221 to yVM1 New-VM : Cannot validate argument on parameter 'Datastore'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:182 char:87 + ... ost -datastore $datastore -Location $targetlocation -DiskStorageFormat thin +                    ~~~~~~~~~~     + CategoryInfo          : InvalidData: (:) [New-VM], ParameterBindingValidationException     + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM get-datastore : 12/17/2015 2:06:11 PM    Get-Datastore        Datastore with name 'TestCluster' was not found using the specified filter(s). At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:152 char:38 +                        $datastore = get-datastore $targetdatastore -vmhost $tar ... +                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : ObjectNotFound: (:) [Get-Datastore], VimException     + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetDat   astore A VM named yVM2-1 151221 exists. Starting clone yVM2 Cloning yVM2-1 151221 to yVM2 New-VM : Cannot validate argument on parameter 'Datastore'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At C:\Users\administrator.LBASE\Desktop\SCRIPTS GOLDEN\restoreRP_TSDBeta1.ps1:182 char:87 + ... ost -datastore $datastore -Location $targetlocation -DiskStorageFormat thin +                    ~~~~~~~~~~     + CategoryInfo          : InvalidData: (:) [New-VM], ParameterBindingValidationException     + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM
But my objective is to create a clone of a VM that already exists and deposit it in a storage cluster, ultimately removing removing a date stamp off the end of the name.  "New-VM" doesn't look li... See more...
But my objective is to create a clone of a VM that already exists and deposit it in a storage cluster, ultimately removing removing a date stamp off the end of the name.  "New-VM" doesn't look like its cloning the VM named "PreExistingVM1" it looks more like its creating a new one to me unless I have miss-understood.  Do you think I should retry the very original script (now I have updated PowerCLI) and simply replace the datastore variable with the name of the storage cluster instead?
I know I am getting my syntax wrong somehow.  I knocked up a VM named "PreExistingVM" and ran the script and got the following error which I sort of partially expected.  How do I tell it the name... See more...
I know I am getting my syntax wrong somehow.  I knocked up a VM named "PreExistingVM" and ran the script and got the following error which I sort of partially expected.  How do I tell it the name it needs to be given? ...  (just a point to highlight I did upgrade my PowerCLI V6 R3, apologies if you would have rather I did not do that.  I initially got the impression you were recommending it) # ============================================================================================== # Functions # ============================================================================================== #Function to allow you to check if a command is loaded Function Check-Command($cmdname) {     return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue) } if (Check-Command "Connect-VIServer") {   Write-Host "Automation Tool already loaded" } else {   #If not already loaded load the snapin   Write-Host "Loading Automation Tools"   Add-PSSnapin VMware.VimAutomation.Core } # Establish Connection Connect-VIServer -Server 127.0.0.1 -User administrator@lbase -Password omega1 New-VM -Name PreExistingVM1 -VMHost (Get-VMHost -Name 192.168.0.249) -Datastore TestCluster
I went ahead and updated to the latest version mate V6 RC3 same as yours, I don't see it installed on our production VC so I will use the same version there also.  When I get an opportunity I wil... See more...
I went ahead and updated to the latest version mate V6 RC3 same as yours, I don't see it installed on our production VC so I will use the same version there also.  When I get an opportunity I will retest and let you know the results, thanks for your assistance I'm extremely grateful.  
I'm pretty sure the VM's were removed from the inventory prior to yanking the plug on the storage, it was a bit of a communication break down between me and the storage guy (more my fault tbh).  ... See more...
I'm pretty sure the VM's were removed from the inventory prior to yanking the plug on the storage, it was a bit of a communication break down between me and the storage guy (more my fault tbh).  I'm just wondering what would be the consequences of right clicking the datastore and un-mounting as I usually would? Is there a procedure for dealing with this sort of scenario?  Its not ideal I know, I know the procedure very well and I have done it a thousand times.  The trouble is downtime is difficult and so are vMotions due to silly individuals purchasing the wrong licences.
I have 3 hosts (version 5.0 build 1476327) that are showing the datastores present but the backing device has now gone.  Oddly others in the same cluster are fine, I'm mildly concerned about the ... See more...
I have 3 hosts (version 5.0 build 1476327) that are showing the datastores present but the backing device has now gone.  Oddly others in the same cluster are fine, I'm mildly concerned about the host crashing due to a APD condition.  Unfortunately evacuating the hosts is probably not an option due to licensing, can anyone advise of the best/safest course of action. 
Just to be clear mate, you test script did create the VM.  Do you still think its the PowerCLI version, I will update it if thats what your suggesting.
Hmm, which makes me wonder why it doesn't work in the main script? 
This I might have made a booboo and forgot to load the snap-in etc PowerCLI version I knocked up the below script to perform your test mate and indeed I did see vCenter saying "Applying D... See more...
This I might have made a booboo and forgot to load the snap-in etc PowerCLI version I knocked up the below script to perform your test mate and indeed I did see vCenter saying "Applying DRS recommendations" and a mysterious VM was created named Test   Apologies for being a doofus # ============================================================================================== # Functions # ============================================================================================== #Function to allow you to check if a command is loaded Function Check-Command($cmdname) {     return [bool](Get-Command -Name $cmdname -ErrorAction SilentlyContinue) } if (Check-Command "Connect-VIServer") {   Write-Host "Automation Tool already loaded" } else {   #If not already loaded load the snapin   Write-Host "Loading Automation Tools"   Add-PSSnapin VMware.VimAutomation.Core } # Establish Connection Connect-VIServer -Server 127.0.0.1 -User administrator@lbase -Password omega1 New-VM -Name Test -VMHost (Get-VMHost -Name 192.168.0.249) -Datastore TestCluster