Quantcast
Channel: VMware Communities : Discussion List - Automation Tools
Viewing all 9071 articles
Browse latest View live

Get-Vm : Value cannot be null

$
0
0

With PowerCli 11, I got Value cannot be null

 

Get-Vm : Value cannot be null.

Parameter name: format

At line:1 char:1

+ Get-Vm *

+ ~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Get-VM], ArgumentNullException

    + FullyQualifiedErrorId : System.ArgumentNullException,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

 

 

I got this error on almost all commands.

After some digging, I got this error only if I change windows display language (in my case from french to english). Currently running Windows 10 1709

 

Could anyone can confirm this a bug with PowerCLI?


Disk consolidation script -- Need help testing

$
0
0

Recently we encountered an issue where a team member mistakenly did not delete a snapshot following some maintenance on a VM.  Long story short, the snapshot ballooned into more than 2TB and took many hours to consolidate.  Aside from the obvious of "don't forget to delete snapshots", we're looking for ideas on ways to prevent this from happening.

 

One idea that our manager wanted us to pursue was to have a script which would routinely scan for VMs showing the "Disk Consolidation Needed" warning. It would then alert us, and start the consolidation process. This wasn't complicated to write, but I'm having trouble getting a VM into the "Disk Consolidation Needed" state to test it.

 

Also, any other ideas on better ways to handle this are certainly welcome.

 

Script code:

 

# Overview: Check vCenter(s) for any VMs with disks needing consolidation. If it finds any, attempt to consolidate them.

 

# Notes: Since we don't specify a credential pair to connect with, it will attempt to connect as the current script environment's user.


# Load PowerCLI Module

Import-Module -Name VMware.VimAutomation.Core


##### Variables #####

$vCenters = @('XXXX', 'YYYY')

$logpath = "$env:SystemDrive\Windows\Temp\VM_Consolidation.log"

############


<#

.SYNOPSIS

Logs messages to a file


.DESCRIPTION

Receives messages and logs them to an output file.


.PARAMETERmsg

The message to be written


.EXAMPLE

Write-Log 'Write this to the logfile'


.NOTES

Requires $logfile to be configured as the path to the output log file

#>

functionWrite-Log {

  param($msg)

  "$(Get-Date-Format G) : $msg" | Out-File -FilePath $logpath -Append -Force

}


foreach ($vCenterin$vCenters) {

  try {

   Connect-VIServer$vCenter -ErrorAction Stop

  } catch {

   Write-Log'Cannot connect to $vCenter'

  }

}


if ($Global:DefaultVIServers.Count -gt 0) {

  $VMsNeedingConsolidation = Get-VM | Where-Object {$_.ExtensionData.Runtime.consolidationNeeded}


  if ($VMsNeedingConsolidation -gt 0){

   Write-Log"VMs needing consolidation: $VMsNeedingConsolidation"


   $VMsNeedingConsolidation | ForEach-Object {

   Write-Log"Needs consolidation $_ "

  $_.ExtensionData.ConsolidateVMDisks_Task()

  }

  }

}

help needed stringing parameters together - powercli.

$
0
0

Hi,

I have this string that half works.

i am unable to sting together to get the .config and .guest and .guest.net all in one command string.

 

any suggestions.

 

> Get-VM -name "System1" | Sort | Get-View -Property @("Name", "Config.ChangeVersion", "guest.guestfullname", "Guest.hostname", "guest.ipaddress", "guest.gueststate", "guest.net.network") | Select -Property Name, @{N="ChangeVersion";E={$_.Config.ChangeVersion}}, @{N="Running OS";E={$_.Guest.GuestFullName}}, @{N="Hostname";E={$_.Guest.hostname}}, @{N="IP Address";E={$_.Guest.ipaddress}}, @{N="State";E={$_.Guest.gueststate}}, @{N="Network";E={$_.Guest.net.network}} | Format-Table -AutoSize

 

it should give me screen output of: but only give first three fields.

 

NameChangeVersion          Running OS                        Hostname IP Address State Network
-----------------          ----------                        -------- ---------- ----- -------

System1 2019-03-13T16:46:29.301502Z Microsoft Windows Server 2016 (64-bit)

 

goal to get

     name, changeVersion, guestfullname, hostname, ipaddress, gueststate, guest.net.network

 

thanks.

PowerCLI snapshot reports

$
0
0

I'm struggling with two scripts that I would like to combine, but need assistance. Essentially one outputs html (this i need), the other has information that i also need:

VMSnapNameDaysOldCreatorSizeGBCreated

Description

 

 

Here are the scripts:

# HTML formatting

$a = "<style>"

$a = $a + "BODY{background-color:white;}"

$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"

$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: LightBlue}"

$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;foreground-color: black;background-color: white}"

$a = $a + "</style>"

 

 

# Main section of check

Write-Host "Checking VMs for for snapshots"

$date = get-date

$datefile = get-date -uformat '%m-%d-%Y-%H%M%S'

$filename = "C:\Snaps" + $datefile + ".htm"

 

 

# Get list of VMs with snapshots

# Note:  It may take some time for the  Get-VM cmdlet to enumerate VMs in larger environments

$ss = Get-vm | Get-Snapshot

Write-Host "   Complete" -ForegroundColor Green

Write-Host "Generating VM snapshot report"

#$ss | Select-Object vm, name, description, powerstate | ConvertTo-HTML -head $a -body "<H2>VM Snapshot Report</H2>"| Out-File $filename

$ss | Select-Object vm, name, description | ConvertTo-HTML -head $a -body "<H2>VM Snapshot Report</H2>"| Out-File $filename

Write-Host "   Complete" -ForegroundColor Green

Write-Host "Your snapshot report has been saved to:" $filename

 

Other script:

# Load PowerCLI Module

 

  if ( !(Get-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) ) {

 

  . “C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1”

 

  }

 

function Get-SnapshotSummary {

 

  param(

 

  $InputObject = $null

 

  )

 

    PROCESS {

 

  if ($InputObject -and $_) {

 

  throw 'ParameterBinderStrings\AmbiguousParameterSet'

 

  break

 

  } elseif ($InputObject) {

 

 

  $InputObject

 

  } elseif ($_) {

 

  $mySnaps = @()

 

  foreach ($snap in $_){

 

  $SnapshotInfo = Get-SnapshotExtra $snap

 

  $mySnaps += $SnapshotInfo

 

  }

 

  $mySnaps | Select VM, @{N="SnapName";E={[System.Web.HttpUtility]::UrlDecode($_.Name)}}, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, Creator, @{N="SizeGB";E={$_.SizeGB -as [int]}}, Created, Description -ErrorAction SilentlyContinue | Sort DaysOld

 

  } else {

 

  throw 'ParameterBinderStrings\InputObjectNotBound'

 

  }

 

  }

 

}

 

function Get-SnapshotTree{

 

  param($tree, $target)

 

  $found = $null

 

  foreach($elem in $tree){

 

  if($elem.Snapshot.Value -eq $target.Value){

 

  $found = $elem

 

  continue

 

  }

Invoke-VMScript. Pass variable in BASH

$
0
0

Hi LUCD, hi all!

Small script to change IP in CentoS

 

 

$IPguest = Read-Host -Prompt 'Enter IP Guest'
$script = "sed -i 's:^IPADDR=.*$:IPADDR=$IPguest:g' /etc/sysconfig/network-scripts/ifcfg-ens160"
Invoke-VMScript -VM CentOS-7 -ScriptType bash -ScriptText $script -GuestUser root -GuestPassword P@ssw0rd

 

Error:sed: -e expression #1, char 13: unterminated `s' command

The problem here: $:IPADDR=$IPguest.

How can I pass variable in this case?

shutdown-vmguest and set cpu and mem

$
0
0

will this work?

have not had a chance to test

 

$vms = get-vm -name (get-content vms.txt)

foreach ($vm in $vms) {

get-VM -name $vm | Shutdown-VMGuest -Confirm:$false

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

   Write-Host "Shutting Down" $VMName

   Shutdown-VMGuest -VM $VM

   #Wait for Shutdown to complete

   do {

      #Wait 5 seconds

      Start-Sleep -s 5

      $status = $VM.PowerState

   }until($status -eq "PoweredOff")

}

$vm | Set-VM –MemoryGB 8 –NumCpu 2 –Confirm:$False

$vm  | Start-VM

}

Script to automatically remove VM's older than 14 days.

$
0
0

Hi guys,

 

A while back Mr. LucD helped me with a script that automatically deletes any VM that has been powered off longer than 14 days. The script does work as intended but I wanted to see if someone could help me by modifying it so that instead of me having to update the script manually to exclude a VM from being deleted, we could simply make it so that if a virtual machine or multiple virtual machines are inside a folder, these would not get deleted. In other words, if we manually move a VM to a folder, the script will NOT remove any of the virtual machines inside it.

 

Below is the script I am using.

 

##Load all VMware related snap-ins

#Add-PSSnapin VMware.VimAutomation.Core

Get-Module -ListAvailable VM* | Import-Module

 

 

##vCenter connection information

$vcenter = 'vcenter instances'

$vcenteruser = 'vadmin'

$vcenterpw = ''

 

 

##Connects to all vCenter instances

Connect-VIServer $vcenter -User $vcenteruser -Password $vcenterpw

 

 

#Here's where you can exclude any virtual machines from being removed by the script. You will need to un-comment this line.

#You will also need to comment the $excludedVM = @{} line in order to honor this line.

#$excludedVM = 'Some VM' -----> This is where a folder would be a lot safer to use.

 

 

#Here's where you can ignore the exclusions. If you un-comment this line, all virtual machines that meet the 7 day criteria will be removed.

#If you comment this line, then you will need to un-comment the #$excludedVM = 'VM Name Line' in order to honor this line.

$excludedVM = @{}

 

 

#Here you're defining the any VM variable

$vms = @{}

 

 

#This piece will get all powered off VMs and exclude the ones from the list that were defined in the $excludedVM variable

Get-VM | where {$_.PowerState -eq "PoweredOff" -and $excludedVM -notcontains $_.Name} | % {$vms.Add($_.Name, $_)}

#Get-VM | where {$_.PowerState -eq "PoweredOff"} | % {$vms.Add($_.Name, $_)}

 

 

#Exclude any virtual machine that was powered off before the last 7 days

Get-VIEvent -Start (Get-Date).AddDays(-7) -Entity $vms.Values -MaxSamples ([int]::MaxValue) | where {$_ -is [VMware.Vim.VmPoweredOffEvent]} | Sort-Object -Property CreatedTime -Unique | % {$vms.Remove($_.VM.Name)}

 

 

#Remove the remaining VMs

#Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false -WhatIf

Remove-VM -VM $vms.Values -DeletePermanently -Confirm:$false

resourcepool does not take two words as inputc

$
0
0

Hi,

 

The resourcepool parameter does not take inputs such as  Business Critical, see my simple code below and error.

 

New-VM -Name ibgkbapp01 -Template rhel5u5-64-v7 -Datastore vmfs_duprb1_ns960_0650_20 -ResourcePool Business Critical

 

 

The Error :

 

 

New-VM : 11/8/2011 10:13:10 AM    New-VM        The specified parameter 'ResourcePool' expects a single value, but your name criteria 'Business Critical' corresponds to multiple
values.   
At C:\Documents and Settings\gajulg\Local Settings\Temp\911c0993-9ebb-4433-971a-1040b2f0468d.ps1:2 char:7
+ New-VM <<<<  -Name ibgkbapp01 -Template rhel5u5-64-v7 -Datastore vmfs_duprb1_ns960_0650_20 -ResourcePool 'Business Critical'
    + CategoryInfo          : InvalidResult: (System.Collecti...dObjectInterop]:List`1) [New-VM], VimException
    + FullyQualifiedErrorId : Core_ObnSelector_SelectObjectByNameCore_MoreResultsThanExpected,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM
New-VM : 11/8/2011 10:13:10 AM    New-VM        VIContainer parameter: Could not find any of the objects specified by name.   
At C:\Documents and Settings\gajulg\Local Settings\Temp\911c0993-9ebb-4433-971a-1040b2f0468d.ps1:2 char:7
+ New-VM <<<<  -Name ibgkbapp01 -Template rhel5u5-64-v7 -Datastore vmfs_duprb1_ns960_0650_20 -ResourcePool 'Business Critical'
    + CategoryInfo          : ObjectNotFound: (VMware.VimAutom...er ResourcePool:RuntimePropertyInfo) [New-VM], ObnRecordProcessingFailedException
    + FullyQualifiedErrorId : Core_ObnSelector_SetNewParameterValue_ObjectNotFoundCritical,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM

mount an existing NFS datastores to a new host

$
0
0

Hello, I want to perform this without using the "new-datastore" command, I want to perform it as we do from the vSphere webclint, just by rightclicking the datastore and select "Mount ao another host", so I want to do it like this in PowerCLi. is it doable?

Invoke-VMScript - An error occurred while sending the request

$
0
0

Hi,

I am writing a script that use invoke-vmscript and Copy-VMGuestFile but they throw an error when I run them again the vcenter server.

 

Here one example:

 

Invoke-VMScript -ScriptText $NetworkSettings -VM $VMName -GuestCredential $credential

 

Invoke-VMScript : 01/04/2019 10:56:52   Invoke-VMScript         An error occurred while sending the request.

At C:\Users\user\Documents\vscodeProjects\SupportTeam\Vmware-Automation\Actions\CONFIGNET\ActionCONFIGNET.psm1:43 char:5

+     Invoke-VMScript -ScriptText $NetworkSettings -VM $VMName -GuestCr ...

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

    + CategoryInfo          : NotSpecified: (:) [Invoke-VMScript], ViError

    + FullyQualifiedErrorId : Client20_VmGuestServiceImpl_DownloadFileFromGuest_DownloadError,VMware.VimAutomation.ViCore.Cmdlets.Commands.InvokeVmScript

 

 

To notice that I connected correctly to the vcenter before run the Invoke-Script and that the script contained in $NetworkSettings has been run correctly on the guest VM. The only problem seems to happen when the Invoke-VMScript try to read the result. If I run the Invoke-VMScript again the physical host instead the VCenter everything is working.

Vcenter, physical host and the machine who the invoke-vmscript are in the same network.

Same problem if I use the Copy-VMGuestFile

 

Any ideas?

Error running Invoke-Vmscript - An error occurred while sending the request. FullyQualifiedErrorId : Client20_VmGuestServiceImpl_DownloadFileFromGuest_DownloadError,VMware.VimAutomation.ViCore.Cmdlets.Commands.InvokeVmScript

$
0
0

(EDIT: Same issue already reported here: Invoke-VMScript - An error occurred while sending the request )

 

Hello folks,

 

 

I used to run Invoke-Vmscript againts our Environment to automate Template Creation.
Recently it stopped working, not sure when exactly.  Targeted VM's OS is "Server 2016".

 

For example when I'm running the following PoSh:

 

Invoke-VMScript -ScriptText "get-service" -VM $VM -GuestCredential (get-credential)

 

I'm getting the following Error:

 

Invoke-VMScript : 02.04.2019 11:54:59   Invoke-VMScript         An error occurred while sending the request.

At line:1 char:1

+ Invoke-VMScript -ScriptText "get-service" -VM $VM -GuestUser Administ ...

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

    + CategoryInfo          : NotSpecified: (:) [Invoke-VMScript], ViError

    + FullyQualifiedErrorId : Client20_VmGuestServiceImpl_DownloadFileFromGuest_DownloadError,VMware.VimAutomation.ViC

   ore.Cmdlets.Commands.InvokeVmScript

 


Credentials are correct, I'm seeing a confirmation in the VM Eventlog that the user was sucessfully authenticated. (Eventsource: VGauth, EventID: 1000, Message: vmtoolsd: Username and password successfully validated for 'Administrator')
I also see a brief appearance of a cmd.exe in Taskmanager on the VM.
No other related Events in Eventlog.

Also tried different Clients to run the script, and different target VMs too.
I also ensured that the Client running the script is able to access the ESX Host via Port 443 and (because I read it somewhere: 902 works also)

 

No more ideas... anyone else? Thanks for any help!

Script to get who created VM Clone copy

$
0
0

Hi All,

i found various script on creating VM Clone.

 

But is anyone have script which can give details like who created VM Clone, date, time, user id, Clone Disk size.

 

 

 

Thanks in Advance.

Fetch certification details assigned to client by CA server

$
0
0

Gents,

Please help to loop this query to correct group if not relevant in this community. My query is as below....

 

I have a CA server and multiple clients to whom certification is assigned by this CA server. I need to fetch details of certificates assigned to client, when assigned, what is  expiry date etc and export all in excel sheet. please suggest.

New-VM in 11.2 requires a portgroup

$
0
0

PowerCLI 11.2 appears to require a portgroup for New-VM:

 

PS C:\> New-VM -Name testvm -ResourcePool testpool -Datastore testds

New-VM : 4/2/2019 8:19:17 AM New-VM Value cannot be null.

Parameter name: source

At line:1 char:1

+ New-VM -Name testvm -ResourcePool testpool -Datastore testds ...

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

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

    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.V

   iCore.Cmdlets.Commands.NewVM

 

 

PS C:\> New-VM -Name testvm -ResourcePool testpool -Datastore testds -Portgroup testpg

 

Name                 PowerState Num CPUs MemoryGB      

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

testvm              PoweredOff 1        0.250         

 

 

 

This was not true in 10.0; haven't tested 11.1.  In any case, I believe this is the wrong behavior.

Move-VM bug

$
0
0

I have two datacenters and am running PowerCLI 11.2.0 and vSphere 6.7u1.

 

When I try moving a VM to a different folder in the same datacenter, this happens:

 

try {

    Move-VM -VM $vm -InventoryLocation $folder -ErrorAction Stop

} catch {

    $_

    $_.Exception.ExpectedDatacenter

    $_.Exception.InvalidArgumentInternal

}

 

 

Move-VM : 4/2/2019 8:10:28 AM Move-VM The operation for the entity "test-vm"

failed with the following message: "The input arguments had entities that did not

belong to the same datacenter."

At line:2 char:5

+     Move-VM -VM (Get-VM "test-vm") `

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

    + CategoryInfo          : NotSpecified: (:) [Move-VM], DatacenterMismatch

    + FullyQualifiedErrorId : Client20_TaskServiceImpl_CheckServerSideTaskUpdates

   _OperationFailed,VMware.VimAutomation.ViCore.Cmdlets.Commands.MoveVM

Datacenter-datacenter-34666

Entity                       InputDatacenter         LinkedView
------                       ---------------         ----------
HostSystem-host-145951       Datacenter-datacenter-2          
Folder-group-v49412          Datacenter-datacenter-2          
ResourcePool-resgroup-436820 Datacenter-datacenter-2   

Get list of plugins and versions installed from vCenter?

$
0
0

Hi all,

 

Does anyone know how to use PowerCLI to get a list of plugins installed in vCenter, their versions and any other information associated with those plugins?  I found Get-vCenterPlugin, per http://www.jonathanmedd.net/2012/02/managing-vcenter-plugins-with-powercli.html, but that doesn't seem to work for me in PowerCLI 6.0 Release 1.  Anybody know what I can use instead?  Or am I missing something with Get-vCenterPlugin?

Export CSV - Multiple VMs hard disks information

$
0
0

All

I started a powercli below to extract harddisk information and generate a csv file.

The problem here is that information being exported is only for one vm, and not all vms included in  GetVMList.txt are being exported.

Anyone can give me solution, I appreciate any comments.

 

 

$VMs = Get-content E:\vmw\GetVMList.txt

Write-Host "Collecting Vm hard disks information..." -ForegroundColor Yellow

Foreach ($vm in $VMs){

  Get-vm $vm | get-harddisk | select Parent,StorageFormat,DiskType,Filename,CapacityGB,Persistence,Name | Export-Csv e:\vmw\output\VM_disks.csv –NoTypeInformation

}

Write-Host "Done." -foreground Green

Unable to get folder, datastore, templates,vm hosts details

$
0
0

Hi,

 

I am unable to get the folder, datastore, templates,vm hosts details from my datacenter level.

 

I am just seeing datacenter name rest all are blank

 

Please help

 

get-datacenter | select Name,

get-vmhost | Select Name,

get-folder | Select Name,

Get-Datastore | Select Name,

get-template | Select Name | Export-Csv D:\inventory.csv -NoTypeInformation

PowerCli 11.2.0 and Microsoft System Center Orchestrator CU 5 problem

$
0
0

Hello,

We have some workflows work on  Microsoft System Center Orchestrator CU 5. We face some trouble  when we upgrade Vitrual Center to 6.7 U1 While we try to access from powershell to Virtual Center there is no problem to log in but when we try to log in from orchestrator workflow with same code; we cant log in to vitrual center. We face above the error message:

The term 'Connect-VIServer' 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.

Also we relized that issue related to ssl and tls usage when we add tls registery key into the registry; Wmware integration pack started to work but some workflows still does not work which are use powershell scipts.

 

 

Regards

 

 

 

get-ovfconfigurationa and multiple networkmappings

$
0
0

Hi all,

 

I am trying to import multiple OVA's in to a VMC on AWS environment.  These OVA.s sometimes have multiple vNIC's connected.  with the get-ovfconfigueration cmdlet

 

I can see all the old networkmappings. 

PS C:\Windows\system32> $ovfPath = "\my.ova"

PS C:\Windows\system32> $ovfConfig = Get-OvfConfiguration -Ovf $ovfPath

PS C:\Windows\system32> $ovfconfig

 

 

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

OvfConfiguration: my.ova

 

 

   Properties:

   -----------

   NetworkMapping

 

 

 

 

 

 

PS C:\Windows\system32> $ovfconfig.NetworkMapping

 

 

Portgroup1 Portgroup2

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

 

 

 

 

Is there an easy way to change all the networkmappings (I do not know the content of the networkmapping upfront )  to a same (NSX-T) portgroup?

 

thanks

Viewing all 9071 articles
Browse latest View live


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