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

vsphere_client_installation_powershell

$
0
0

hi Luc,

 

could yu sggest on following.i am trying to installvsphere client on on one windows vm.file is on desktop as shown and run following start-process command .

it went through fine with normal installtionprocesss .

 

 

but failed with followingerror

 


Unable to get the VLanID and VMHostname from VM running with Distributed vSwitch?

$
0
0

Hi All,

 

I'm running vSphere v6.7U1 and using Distributed vSwitch in all of my ESXi servers. I need to get some information in the .CSV file with the below column:

 

VM Name, IPv4, MAC Address, NetworkName, VLanID, NicType, VMHostname

 

However, the VLanID and the VMHostname is not listed properly or it is still empty with the below script:

 

Get-VM|Where-Object {($_.Name-like"PRD-SQL*")} |

 

    ForEach-Object {

    $vm= $_

    $NIC=$vm|Get-NetworkAdapter

    $portGrp=$vm|Get-VirtualPortGroup

    $vm.Guest.Nics|

        ForEach-Object {

        $mac= $_.MacAddress

        $netName= $_.NetworkName

        # Port group treatment depends on the switch type used (distributed etc.)

        $portGrp|Where-Object { $_.Name-eq$netName } |

            ForEach-Object {

            if ($_ -is [VMware.VimAutomation.ViCore.Impl.V1.Host.Networking.DistributedPortGroupImpl]) {

                if ($_.ExtensionData.Config.DefaultPortConfig.Vlan-is [VMware.Vim.VmwareDistributedVirtualSwitchPvlanSpec]) {

                    $_.ExtensionData.Config.DefaultPortConfig.Vlan.PvlanId

                }

                elseif ($_.ExtensionData.Config.DefaultPortConfig.Vlan-is [VMware.Vim.VmwareDistributedVirtualSwitchVlanSpec]) {

                    if ($_.ExtensionData.Config.DefaultPortConfig.Vlan.VlanId-is [VMware.Vim.NumericRange[]]) {

                        [string]::Join(',', ($_.ExtensionData.Config.DefaultPortConfig.Vlan.VlanId|ForEach-Object {"$($_.Start)-$($_.End)"}))

                    }

                    else {

                        $_.ExtensionData.Config.DefaultPortConfig.Vlan.VlanId

                    }

                }

            }

            else {

                $_.VlanId

            }

        } |Set-Variable VLanID

        [PSCustomObject] @{

            Name        =$vm.Name

            IP          = $_.IPAddress-join','

            MAC         =$mac

            NetworkName=$netName

            VLanID      =$VLanID

            NicType     =$NIC     |Where-Object { $_.MacAddress-eq$mac } |Select-Object-Expand Type      

            VMHostName  = $_.VMHostName 

        }

    }

} |Export-CSV C:\VM-Results.csv -NoType

 

This is my PowerCLI configuration:

PowerCLI Version

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

   VMware PowerCLI 11.0.0 build 10380590

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

Component Versions

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

   VMware Cis Core PowerCLI Component PowerCLI Component 11.0 build 10335701

   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 11.0 build 10336080

   VMware VimAutomation Vds Commands PowerCLI Component PowerCLI Component 11.0 build 10336077

   VMware VimAutomation Cloud PowerCLI Component PowerCLI Component 11.0 build 10379994

 

Any help would be greatly appreciated.

 

Thanks in advance.

Adding Syslog logging level possible?

$
0
0

Hi All,

 

Thanks in advance for any help you can provide, I already have a cool bit of PowerCLI that will configure the host Syslog servers in my environment.  I was however wondering if anyone is aware of how I can add to this and also tweak amend the logging level effectively editing the config.xml (which is required from my understanding ...

 

VMware vSphere 6.5 Documentation Library

 

The script I have been using to add add a specific syslog server ...

 

write-Host "Loading Automation Tools"

 

Add-PSSnapin VMware.VimAutomation.Core

 

 

 

# Establish Connection

 

 

Connect-VIServer -Server SecretServer.co.uk -User Luke@SecretDomain -Password TopSecretIWouldHaveToKillYouIfYouSawMe

 

 

Foreach ($vmhost in (get-vmhost))

{

$esxcli = Get-EsxCli -vmhost $vmhost

$esxcli.system.syslog.config.get()

}

 

 

Foreach ($vmhost in (get-vmhost))

{

$esxcli = Get-EsxCli -vmhost $vmhost

$esxcli.system.syslog.config.set($null, $null , $null, $null, $null, $null, $null, $null, “udp://Blah:514,udp://Blah:514,udp://svr0123:514”, $null, $null);

$esxcli.network.firewall.ruleset.set($null, $true, “syslog”)

$esxcli.system.syslog.reload()

}

Why difference result between input line by line and .ps1 script

$
0
0

Hi,

 

I wrote a complete script (.ps1) with all my commands.

If I copy/paste all these command in a powershell window it works fast and fine.

But if I want to execute all these at once via a script I get strange results + it is much slower?

 

For example I have a loop to Add and move Hosts in vcenter.

If I copy/paste that part my result is fine and quick.

 

If I run the same lines from within my script I get strange warnings, other output and slow result.

 

 

######################################################
# Adding hosts to the Datacenter and move to the 
# correct cluster
# + assign license
######################################################
Write-Host "Add hosts to Datacenter and move them into correct cluster" -ForegroundColor Green
foreach ($esx in $hosts) {    Write-Host "Adding ESX Host $esx to" $datacenter.Name -ForegroundColor green    $hostadded = Add-VMHost -Name $esx -Location “MerelbekeHQ” -Force -Credential $UserNames.host    Switch ($esx) {        { "hp1-esx3.atsgroep.be",          "hp1-esx4.atsgroep.be",          "hp1-esx5.atsgroep.be",           "hp2-esx3.atsgroep.be",          "hp2-esx4.atsgroep.be",          "hp2-esx5.atsgroep.be" -contains $_ }         {             Write-Host "Moving ESX Host $esx to cluster Servers" -ForegroundColor Cyan         Move-VMHost -VMHost $hostadded -Destination (Get-Cluster "Servers")            break        }        { "hp1-esx9.atsgroep.be",          "hp2-esx9.atsgroep.be" -contains $_ }         {            Write-Host "Moving ESX Host $esx to cluster AX Production" -ForegroundColor Cyan            Move-VMHost -VMHost $hostadded -Destination (Get-Cluster "AX Production")                   break        }        { "hp1-esx1.atsgroep.be",          "hp2-esx1.atsgroep.be" -contains $_ }         {            Write-Host "Moving ESX Host $esx to cluster AX Staging" -ForegroundColor Cyan         Move-VMHost -VMHost $hostadded -Destination (Get-Cluster "AX Staging")            break        }        { "hp1-esx9.atsgroep.be",          "hp1-esx10.atsgroep.be",          "hp1-esx11.atsgroep.be",           "hp2-esx9.atsgroep.be",          "hp2-esx10.atsgroep.be",          "hp2-esx11.atsgroep.be" -contains $_ }         {            Write-Host "Moving ESX Host $esx to cluster Software Development" -ForegroundColor Cyan         Move-VMHost -VMHost $hostadded -Destination (Get-Cluster "Software Development")            break        }
 }    Write-Host "Assigning license for ESX Host $esx" -ForegroundColor Cyan    Set-VMHost -VMHost $hostadded -LicenseKey $hostsLicTable[$esx]
}

 

If I run the script I get errors like (see below):

I don't get these If I copy/paste the same code in a powershell????
Where does these WARNINGS come from???? I don't use these property's

 

Adding ESX Host hp2-esx5.atsgroep.be to MerelbekeHQ
Moving ESX Host hp2-esx5.atsgroep.be to cluster Servers
WARNING: The 'State' property of VMHost type is deprecated. Use the 'ConnectionState' property instead.
WARNING: PowerCLI scripts should not use the 'DatastoreIdList' property of VMHost type. The property will be removed in a future release.

State                 : Maintenance
ConnectionState       : Maintenance
PowerState            : PoweredOn
VMSwapfileDatastoreId :
VMSwapfilePolicy      : Inherit
ParentId              : ClusterComputeResource-domain-c11
IsStandalone          : False
Manufacturer          : HP
Model                 : ProLiant BL460c Gen9
NumCpu                : 24
CpuTotalMhz           : 62304
CpuUsageMhz           : 0
LicenseKey            : ….
MemoryTotalMB         : 393086,0390625
MemoryTotalGB         : 383,87308502197265625
MemoryUsageMB         : 0
MemoryUsageGB         : 0
ProcessorType         : Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60GHz
HyperthreadingActive  : True
TimeZone              : UTC
Version               : 6.7.0
Build                 : 10302608
Parent                : Servers
VMSwapfileDatastore   :
StorageInfo           : HostStorageSystem-storageSystem-18
NetworkInfo           : hp2-esx5:
DiagnosticPartition   :
FirewallDefaultPolicy : VMHostFirewallDefaultPolicy:HostSystem-host-18
ApiVersion            : 6.7.1
MaxEVCMode            : intel-haswell
Name                  : hp2-esx5.atsgroep.be
CustomFields          : {[AutoDeploy.MachineIdentity, ]}
ExtensionData         : VMware.Vim.HostSystem
Id                    : HostSystem-host-18
Uid                   : /VIServer=vsphere.local\administrator@vcenter2.atsgroep.be:443/VMHost=HostSystem-host-18/
DatastoreIdList       : {Datastore-datastore-19, Datastore-datastore-20, Datastore-datastore-21, Datastore-datastore-22...}

What would cause a VM to get deleted?

$
0
0

Hello,

 

I wrote a script that performs some database updates on a VM. It does so by attaching disks to the VM, uploading some files and running a script inside the VM.

The only CmdLets am calling are Invoke-VMScript, Copy-VMGuestFile, Get-HardDisk, Remove-HardDisk, New-HardDisk

 

Twice so far, the script would fail and I would discover that the VM does not exist in vcenter anymore! Looking in the logs I find that the VM got powered off, during my script run, and got unregistered:

 

2019-02-04T03:58:07.571560-05:00 esxsrv-c5.cua.edu Hostd:  info hostd[12C43B70] [Originator@6876 sub=Vimsvc.ha-eventmgr] Event 96380 : Guest operation List Processes performed on Virtual machine CSDBORAUAT01-C.

2019-02-04T03:58:07.581340-05:00 vcenter vpxd[48551]  Event [2838593] [1-1] [2019-02-04T08:58:07.578664Z] [vim.event.EventEx] [info] [CUA\VEEAM-SERVICE] [Leahy-DR] [2838593] [Guest operation List Processes performed on Virtual machine CSDBORAUAT01-C.]

2019-02-04T03:58:10.968975-05:00 vcenter vpxd[48551]  Event [2838598] [1-1] [2019-02-04T08:58:10.966512Z] [vim.event.VmStoppingEvent] [info] [CUA\VEEAM-SERVICE] [Leahy-DR] [2838597] [CSDBORAUAT01-C on  esxsrv-c5.cua.edu in Leahy-DR is stopping]

2019-02-04T03:58:10.977536-05:00 esxsrv-c5.cua.edu Hostd:  info hostd[13985B70] [Originator@6876 sub=Vimsvc.ha-eventmgr opID=490e4cf4-83-0207 user=vpxuser:CUA\VEEAM-SERVICE] Event 96382 : CSDBORAUAT01-C on  esxsrv-c5.cua.edu in ha-datacenter is stopping

2019-02-04T03:58:35.159218-05:00 esxsrv-c5.cua.edu Hostd:  info hostd[13985B70] [Originator@6876 sub=Vimsvc.ha-eventmgr] Event 96383 : CSDBORAUAT01-C on  esxsrv-c5.cua.edu in ha-datacenter is powered off

2019-02-04T03:58:42.365016-05:00 vcenter vpxd[48551]  Event [2838617] [1-1] [2019-02-04T08:58:42.363276Z] [vim.event.AlarmStatusChangedEvent] [info] [] [Leahy-DR] [2838617] [Alarm 'Virtual machine CPU usage' on CSDBORAUAT01-C changed from Green to Gray]

2019-02-04T03:58:42.368607-05:00 vcenter vpxd[48551]  Event [2838618] [1-1] [2019-02-04T08:58:42.366874Z] [vim.event.VmPoweredOffEvent] [info] [CUA\VEEAM-SERVICE] [Leahy-DR] [2838597] [CSDBORAUAT01-C on  esxsrv-c5.cua.edu in Leahy-DR is powered off]

2019-02-04T03:58:42.391214-05:00 vcenter vpxd[48551]  Event [2838619] [1-1] [2019-02-04T08:58:42.389822Z] [vim.event.AlarmStatusChangedEvent] [info] [] [Leahy-DR] [2838619] [Alarm 'Virtual machine memory usage' on CSDBORAUAT01-C changed from Green to Gray]

2019-02-04T03:58:44.215799-05:00 vcenter vpxd[48551]  Event [2838623] [1-1] [2019-02-04T08:58:44.213694Z] [vim.event.VmRemovedEvent] [info] [CUA\VEEAM-SERVICE] [Leahy-DR] [2838620] [Removed CSDBORAUAT01-C on esxsrv-c5.cua.edu from Leahy-DR]

2019-02-04T03:58:44.223485-05:00 esxsrv-c5.cua.edu Hostd:  info hostd[13985B70] [Originator@6876 sub=Vimsvc.ha-eventmgr opID=178aafac-1e-035a user=vpxuser:CUA\VEEAM-SERVICE] Event 96384 : Removed CSDBORAUAT01-C on esxsrv-c5.cua.edu from ha-datacenter

Is there any way my script would actually have requested that the VM be powered off and un-registered, even though I don't seem to have any call to such commands ?

Update-VmfsDatastore powercli don´t work

$
0
0

Morning. I am updating my datastore with powercli towards Update-VmfsDatastore -Datastore $Source -TemporaryDatastore $Temp -TargetVmfsVersion "6" -server $Server and suddenly ask for New item and is not able to find the right path.. any help will be welcome.. Thx in advance.

 

Buenos días, estoy intentando actualizar mis datastore de la versión 5.82 a la versión 6 a través de Powercli con el procedimiento recomendado por Vmware.

 

El comando que lanzo es Update-VmfsDatastore -Datastore $Source -TemporaryDatastore $Temp -TargetVmfsVersion "6" -server $Server

 

Y me lanza una especie de error como que no encuentra los logs.. he abierto incidencia con Vmware y cómo es Powercli, pues no entra en el soporte básico. Alguién le ha pasado?

 

New-Item : No se encuentra la unidad. No existe ninguna unidad con el nombre 'log_folder_virtual.cpd.xx.es_A8-HUS130'.

En C:\Program Files\WindowsPowerShell\Modules\VMware.VimAutomation.StorageUtility\1.3.0.0\StorageUtility.psm1: 929

Carácter: 7

+ New-Item -ItemType directory -Path $variableFolder | Out-Null

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

+ CategoryInfo : ObjectNotFound: (log_folder_virtual.cpd.xx.es_A8-HUS130:String) [New-Item], DriveNotFou

ndException

+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemCommand

 

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

Fernando Tamariz

Specialist/Staff

UVA

Valladolid

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

How can I optimize this command for finding VM's with multiple tags?

$
0
0

I'm looking for a way to find all VM's that have multiple tags assigned. For the sake of the question let's assume the tags are Alpha and Beta. The command that I've come up with works but it's very slow.

 

get-vm -tag alpha | Where{$_.PowerState -eq 'PoweredOn' and (Get-TagAssignment -Entity $_ ).Tag -match 'Beta'}

 

If I run the following, it's faster but I get VM's with either or.

 

get-vm -tag alpha,beta

 

It's only when I add the additional filter (Get-TagAssignment) to only show the second tag where it slows down. Is there a way to specify both tags in the quicker command but only return when both are found?

Tag Migrations

$
0
0

I am trying to migrate VMs from one vcenter to another and I have a CSV of the source VMs and want to make sure I know how to import them to the destination vCenter.

 

$tagNames=Get-TagCategory|%{$_.Name}

 

Get-VM|where{$_.Notes -notmatch'This is a test VM'} |ForEach-Object-Process {

    $obj=[ordered]@{

        Name =$_.Name

        Notes =$_.Notes

    }

    $tagNames|%{

        $obj.Add($_,'')

    }

    Get-TagAssignment-Entity$_|%{

        $obj.Item($_.Tag.Category.Name) =$_.Tag.Name

    }

    New-ObjectPSObject-Property$obj

} |Export-Csv "\Tags-Assignemnts.csv"-NoTypeInformation-UseCulture


powershell vm cli not running as a CGI

$
0
0

I am running pwsh (PowerShell v6.1.0-preview.2) on Ubuntu 16.04.

   VMware PowerCLI 10.1.0 build 8346946

   VMware Cis Core PowerCLI Component PowerCLI Component 10.1 build 8377811

   VMware VimAutomation VICore Commands PowerCLI Component PowerCLI Component 10.1 build 8344055

 

 

 

When I run my powerCLI script from a shell it runs perfectly, but when I run it as a CGI the vmware module aborts.

 

apache2/error.log says:

 

AH01215: Connect-VIServer : The type initializer for 'VMware.VimAutomation.ViCore.Util10.SettingsManager' threw an exception.: /var/www/html/vm.ps1

AH01215: At /var/www/html/vm.ps1:62 char:7: /var/www/html/vm.ps1

AH01215: + if(Connect-VIServer -Server $vmSphere -user $vmSphereUser -passwor ...: /var/www/html/vm.ps1

AH01215: +       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~: /var/www/html/vm.ps1

AH01215: + CategoryInfo          : NotSpecified: (:) [Connect-VIServer], TypeInitializationException: /var/www/html/vm.ps1

AH01215: + FullyQualifiedErrorId : System.TypeInitializationException,VMware.VimAutomation.ViCore.Cmdlets.Commands.ConnectVIServer: /var/www/html/vm.ps1

AH01215:  : /var/www/html/vm.ps1

 

 

 

syslog contains the errors in the attached errors.txt file.

PowerCLI Error

$
0
0

Hi All,

 

We are using vCenter & ESXi with 6.7 version.

 

PowerCLI Version:
----------------
   VMware PowerCLI 6.5 Release 1 build 4624819
---------------
Component Versions
---------------
   VMware Cis Core PowerCLI Component 6.5 build 4624453
   VMware VimAutomation Core PowerCLI Component 6.5 build 4624450
   VMWare ImageBuilder PowerCLI Component 6.5 build 4561891
   VMWare AutoDeploy PowerCLI Component 6.5 build 4561891
   VMware Vds PowerCLI Component 6.5 build 4624695
   VMware Cloud PowerCLI Component 6.5 build 4624821
   VMware HA PowerCLI Component 6.0 build 4525225
   VMware HorizonView PowerCLI Component 7.0.2 build 4596620
   VMware Licensing PowerCLI Component 6.5 build 4624822
   VMware PCloud PowerCLI Component 6.5 build 4624825
   VMware Storage PowerCLI Component 6.5 build 4624820
   VMware vROps PowerCLI Component 6.5 build 4624824
   VMware vSphere Update Manager PowerCLI 6.5 build 4540462

 

Data is incorporated in a CSV file.

While trying to change the portgroup for a VM. I am getting below error.

Even manually specifying the VM name & the port group also possess same error.

 

command executed:

Get-VM $c.name | Get-NetworkAdapter | ?{$_.Name -eq "Network adapter 1"} | Set-NetworkAdapter -NetworkName $c.portgroup  -Connected:$true -Confirm:$false

 

Error:

Set-NetworkAdapter : 2/6/2019 9:28:42 AM        Set-NetworkAdapter

Could not obtain

the result of task

'/VIServer=domain\adminaccount@vCenter:443/Task=Task-task-1457/'. Task

name is 'ReconfigVM_Task'. The following error occured: Exception has been

thrown by the target of an invocation.

At line:1 char:76

+ ... apter 1"} | Set-NetworkAdapter -NetworkName $c.portgroup  -Connected: ...

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

    + CategoryInfo          : NotSpecified: (:) [Set-NetworkAdapter], VimExcep

   tion

    + FullyQualifiedErrorId : ViCore_TaskCoreService_ConvertTaskResult_Failed,

   VMware.VimAutomation.ViCore.Cmdlets.Commands.VirtualDevice.SetNetworkAdapt

  er

Get Number of VM CPU and Cores

$
0
0

Hi

 

I've tried the following but cannot get the number of VM CPU and Cores. What am I doing wrong?

 

 

 

 

Unable to execute program on remote VMs

$
0
0

Hi,

 

I am unable to execute the local program on remote VMs as I am getting the below error

 

The term 'C:\Program Files\JAM Software\TreeSize\TreeSize.exe' 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.

    + CategoryInfo          : ObjectNotFound: (C:\Program File...ze\TreeSize.exe:String) [], CommandNotFoundException

    + FullyQualifiedErrorId : CommandNotFoundException

    + PSComputerName        : app1

 

Script

Connect-viserver 10.10.10.10

$servs = get-content .\vms.txt

ForEach ($serv in $servs)

{

$WPassword = "password"

$pass = ConvertTo-SecureString -AsPlainText $WPassword -Force

$Creds1 = New-Object System.Management.Automation.PSCredential ("admin", $pass)

$output = Invoke-Command -ComputerName $serv -Credential $Creds1 -ScriptBlock {&'C:\Program Files\JAM Software\TreeSize\TreeSize.exe' /DATE /EXPAND 1 /EXCEL "D:\$serv_Export.xlsx" /EXPANDABLEREPORT /EXTENSIONSLIST /TOPFILESLIST /PIECHART /TREEMAP /AGEOFFILES /EXTENSIONSPIECHART "D:\"}

}

How to exclude the IPV6 address from a list

$
0
0

Hi,

 

I'm using the current script from LucD, I found in another discussion :

 

Get-VM-PipelineVariablevm|where{$_.Guest.Nics.IpAddress} |Get-NetworkAdapter|


@{N='VM';E={$vm.Name}},Name, @{N='VMHost';E={$vm.VMHost.Name}}, @{N=”IP Address”;E={$nic=$_; ($vm.Guest.Nics |where{$_.Device.Name -eq$nic.Name}).IPAddress -join'|'}},MacAddress|Format-table-Autosize

 

 

It works fine, but it shows the IPV6 address I would like to exclude :

 

VM                   Name                   VMHost                   IP Address                                       MacAddress      

 

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

 

test-vm         Network adapter 1 esx03.domain.local fe80::b0fe:ab09:6b6:10f9|192.168.1.1 00:50:56:80:58:21

 

Is it something possible ?

 

Thanks in advance for the help.

 

Regards

Patrick

 

 

Importing Tags using PowerCLI on vCenter 6.7 fails to assign tags to VMs

$
0
0

I've been trying to use the code in the original thread I started a few months ago. It's been exceptionally helpful in demonstrating tag performance issues with our TAM and GSS case. As we move towards 6.7 I want to replicate the same tests and assign a huge batch of tags and categories to our test environment to verify we're going to be safe rolling out tags into production. However it seems like something in script is broken when interacting with 6.7. It works find (same script, same powerCLI/powershell, etc) when run against 6.0

Testing in vCenter 6.0 and succeeded in running this script: https://code.vmware.com/forums/2530#598690|4398020

Copied below to save a click (sorry about formatting - how do YOU make your code look good here?)

$CMDBInfo = Import-CSV .\cmdbinfo.csv
# Get the header names to use as tag category names
$TagCatNames = $cmdbinfo | Get-Member | Where-Object {$_.MemberType -eq "NoteProperty"} | Select-Object -Expand Name
# Create the Tag Category if it doesnt exist
Foreach ($Name in ($TagCatNames | Where-Object {$_ -ne "Name"})) {
  Try {
   $tCat = Get-TagCategory $Name -ErrorAction Stop
  }
  Catch {

   Write-Host "Creating Tag Category $Name"
   $tCat = New-TagCategory -Name $Name # -Description "$Name from CMDB"
  }
  # Create Tags under the Tag Categories
  $UniqueTags = $cmdbinfo | Select-Object -expand $Name | Get-Unique
  Foreach ($Tag in $UniqueTags) {
   Try {
   $tTag = Get-Tag $Tag -Category $tCat -ErrorAction Stop
   }
   Catch {
   Write-Host "..Creating Tag under $Name of $Tag"
   $tTag = New-Tag -Name $Tag -Category $tCat # -Description "$Tag from CMDB"
   }

   # Assign the Tags to the VMs/Hosts
   $cmdbinfo | Where-Object {$_.($Name) -eq $Tag} | Foreach-Object {
   Write-Host ".... Assigning $Tag in Category of $Name to $($_.Name)"
   New-TagAssignment -Entity $($_.Name) -Tag $tTag | Out-Null
   } 
  }
}

I went back and verified in our test lab vCenter 6.0 (latest update) that this script worked flawless. 

However in vCenter 6.7 the script fails to actually assign the tag to the VM. It is able to populate tags and categories without issue but when it comes time to assign a tag to the VM, 

New-TagAssignment : 2/6/2019 10:16:42 AM        New-TagAssignment              Value cannot be null.
Parameter name: collection
At C:\Users\redacted\Desktop\Tagging Project\Import_tag.ps1:37 char:5
+     New-TagAssignment -Entity $($_.Name) -Tag $Tag
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-TagAssignment], VimException
 
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Tagging.NewTagAssignment


If I nuke the categories and tags in 6.7, and manually set them up:

PS C:\Users\redacted\Desktop\Tagging Project> New-TagCategory Application -Cardinality multiple

 

Name                                     Cardinality Description

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

Application                              Multiple

 

PS C:\Users\redacted\Desktop\Tagging Project> New-tag TestApp1 -category Application

 

Name                           Category                       Description

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

TestApp1                       Application

 

PS C:\Users\redacted\Desktop\Tagging Project> New-TagAssignment -entity TagTestVM_00 -Tag TestApp1

New-TagAssignment : 2/6/2019 11:17:20 AM        New-TagAssignment              Value cannot be null.

Parameter name: collection

At line:1 char:1

+ New-TagAssignment -entity TagTestVM_00 -Tag TestApp1

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

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

 

    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Tagging.NewTagAssignment

 

Even just breaking it out further: 

PS C:\Users\redacted\Desktop\Tagging Project> New-TagAssignment -Tag TestApp1 -Entity TagTestVM_00

New-TagAssignment : 2/6/2019 11:21:34 AM        New-TagAssignment              Value cannot be null.

Parameter name: collection

At line:1 char:1

+ New-TagAssignment -Tag TestApp1 -Entity TagTestVM_00

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

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

 

    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Tagging.NewTagAssignment

 

And finally from the basic command: 

PS C:\Users\j129244_su\Desktop\Tagging Project> New-TagAssignment

cmdlet New-TagAssignment at command pipeline position 1

Supply values for the following parameters:

Tag: TestApp1

 

Cannot convert the "TestApp1" value of type "System.String" to type "VMware.VimAutomation.ViCore.Types.V1.Tagging.Tag".

 

New-TagAssignment : 2/6/2019 10:16:42 AM        New-TagAssignment              Value cannot be null.
Parameter name: collection
At C:\Users\j129244_su\Desktop\Tagging Project\Import_tag.ps1:37 char:5
+     New-TagAssignment -Entity $($_.Name) -Tag $Tag
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-TagAssignment], VimException
    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Tagging.NewTagAssignment

Powercli script question for exporting Data

$
0
0

I am trying to export data from my 6.5 vcenter with the embedded database. I keep getting an error. This works in my 6.0 vcenter with no issues. Script is below the error messages

 

Any assistance would be very much appreciated.

 

ERRORS

 

Cannot find an overload for
"Round" and the argument count: "2".

At
C:\Users\wkieca\Desktop\Docs\2019-Trueup\Scripts\Inventory-spvcenter11.ps1:40
char:5

+   
$VMInfo.DatastoreFree = [Math]::Round($ds.FreeSpaceGB,2)

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

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

    +
FullyQualifiedErrorId : MethodCountCouldNotFindBest

 

Method invocation failed because
[System.Object[]] does not contain a method named 'op_Subtraction'.

At
C:\Users\wkieca\Desktop\Docs\2019-Trueup\Scripts\Inventory-spvcenter11.ps1:41
char:5

+   
$VMInfo.DatastoreUsed = [Math]::Round($ds.CapacityGb - $ds.FreeSp ...

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

    +
CategoryInfo          :
InvalidOperation: (op_Subtraction:String) [], RuntimeException

    +
FullyQualifiedErrorId : MethodNotFound

 

Cannot find an overload for
"Round" and the argument count: "2".

At C:\Users\wkieca\Desktop\Docs\2019-Trueup\Scripts\Inventory-spvcenter11.ps1:40
char:5

+   
$VMInfo.DatastoreFree = [Math]::Round($ds.FreeSpaceGB,2)

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

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

    +
FullyQualifiedErrorId : MethodCountCouldNotFindBest

 

Method invocation failed because
[System.Object[]] does not contain a method named 'op_Subtraction'.

At
C:\Users\wkieca\Desktop\Docs\2019-Trueup\Scripts\Inventory-spvcenter11.ps1:41
char:5

+   
$VMInfo.DatastoreUsed = [Math]::Round($ds.CapacityGb - $ds.FreeSp ...

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

    +
CategoryInfo          :
InvalidOperation: (op_Subtraction:String) [], RuntimeException

    + FullyQualifiedErrorId
: MethodNotFound

 

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

 

filterGet-FolderPath
{

    $_|Get-View|% {

      
$row=""|selectName,Path

      
$row.Name
=$_.Name

      
$current=
Get-View$_.Parent

      
# $path = $_.Name # Uncomment out this line if
you do want the VM Name to appear at the end of the path

      
$path=""

      
do {

          
$parent=
$current

          
if($parent.Name -ne"vm"){$path
=$parent.Name +"\"+
$path}

          
$current=
Get-View$current.Parent

      
} while ($current.Parent -ne$null)

      
$row.Path
=$path

      
$row

    }

}

 

$VCServerName=
"spvcenter11.reyesholdings.com"

$VC=
Connect-VIServer$VCServerName
-userRH\x-bkieca
-password

$VMFolder=
"RFS"

$ExportFilePath=
"C:\Users\wkieca\Desktop\Docs\2019-Trueup\Export-spvcenter11.csv"

$Report=
@()

$VMs=
Get-VM

$Datastores=
Get-Datastore

$VMHosts=
Get-VMHost|
selectName,Parent

ForEach ($VM
in$VMs)
{

    $VMView=$VM|Get-View

    $ds=$Datastores|where {$_.ID -match ($vmview.Datastore
|Select-First1).Value}

    $VMInfo= {} |SelectVMName,Powerstate,OS,Folder,IPAddress,ToolsStatus,ToolsVersion,Host,Cluster,Datastore,DatastoreFree,DatastoreUsed,NumCPU,MemMb,DiskGb,DiskFree,DiskUsed,BusinessUnit

    $VMInfo.VMName =$vm.name

    $VMInfo.Powerstate
=$vm.Powerstate

    $VMInfo.OS =$vm.Guest.OSFullName

    $VMInfo.Folder = ($vm|Get-Folderpath).Path

    $VMInfo.IPAddress
=$vm.Guest.IPAddress[0]

    $VMInfo.ToolsStatus
=$VMView.Guest.ToolsStatus

    $VMInfo.ToolsVersion
=$VMView.Guest.ToolsVersion

    $VMInfo.Host =$vm.VMHost.Name

    $VMInfo.Cluster
=$vm.VMhost.Parent.Name

    $VMInfo.Datastore
=$ds.Name

    $VMInfo.DatastoreFree
=[Math]::Round($ds.FreeSpaceGB,2)

    $VMInfo.DatastoreUsed
=[Math]::Round($ds.CapacityGb -$ds.FreeSpaceGB,2)

    $VMInfo.NumCPU =$vm.NumCPU

    $VMInfo.MemMb =[Math]::Round(($vm.MemoryMB),2)

    $VMInfo.DiskGb =[Math]::Round((($vm.Guest.Disks |Measure-Object-Property
CapacityGB-Sum).Sum),2)

    $VMInfo.DiskFree
=[Math]::Round((($vm.Guest.Disks |Measure-Object-Property
FreeSpaceGB-Sum).Sum),2)

    $VMInfo.DiskUsed
=$VMInfo.DiskGb -$VMInfo.DiskFree

    $VMInfo.BusinessUnit
=$vm.CustomFields.Item("Business Unit")

    $Report+=$VMInfo

}

$Report=
$Report|
Sort-ObjectVMName

IF ($Report
-ne"")
{

    $report|Export-Csv$ExportFilePath
-NoTypeInformation

}

$VC=
Disconnect-VIServer-Confirm:$False

 


Clone a VM with a script

$
0
0

Hello friends

 

 

You could help me with example script to clone a VM on a certain date and that it runs automatically on an ESXI host

PowerCLi Script to fetch file details like FullName, LastWriteTime, Length stored on the datastores

$
0
0

With the help of below command, i can able to fetch the details of files with FullName, LastWriteTime, Length only from one datastore, I am looking for the modified script to get this details from all the datastores present in the VC.

 

dir vmstore:\Datacenter\localssd | Get-ChildItem | select-object FullName, LastWriteTime, Length

Ping VM on Host Scrip

$
0
0

I have the following script where it checks if I have ping to an IP of a VM, if it has ping it simply shows me a message that the VM has connection otherwise it deactivates the network interface of the VM aora the inconvenience is that it only validates once the ping, how can I make it validate the ping all the time until it tells me that it lost connection and sends the statement that disconnects the interface of the VM

 

Thank you for you help

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

 

##Variables

$vcenter_server ="172.16.6.10"

$vcenter_user ="administrator@taurus.local"

$vcenter_pwd ="T4urus.2018.v1Center"

$VMIP= "172.16.6.100"

 

 

##Connect to vCenter

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

 

 

 

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

if ($results.StatusCode -eq 0) {

Write-Host "$VMIP hostname is pingable"

}

else {

##Desconectar vNIC de la VM origen

Get-VM -Name AD-LAB | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$false -Confirm:$false

##

}

Clone VM with MAC addres of VM origen

$
0
0

I have the following code to clone a machine, can you help me to be able to clone with the same MAC as the source VM?

 

Regards

 

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

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

Export and Import of Resource Pools using PowerCLI

$
0
0

I'm faced with a task of rebuilding a fresh vCentre server and bringing across all the ESXi hosts and VMs.

I've got scripts in place to export virtual machine notes and annotations, folders, permissions etc. However, I'm struggling to finding something to handle the nested resource pools.

 

Problem seems to be the export of the resource pools doesn't show the whole 'path', so when I try and import these back into the vCentre I get a lot of failures due to the resource pool already existing, and everything is created at the top level.

 

eg.

 

Client A

     Gold

     Silver

     Bronze

 

Client B

     Gold

     Silver

     Bronze

 

etc.

 

so the script I have actually create 5 resource pools - Client A, Client B, Gold, Silver, Bronze - all created at the top level.   Consequently, I get errors when it tries to create Gold, Silver and Bronze for the second time.

 

Is this something I'm going to be able to get working, or is it a manual task I'm faced with?

Viewing all 14549 articles
Browse latest View live


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