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

VM Creation Script Failing

$
0
0

I have a script that reads info from a csv file to build a VM which has always worked in the past but....

The script still builds the VM as it is supposed to without problem, but running set-vm and start-vm commands fail after with these errors. In this case I built a VM named PRDV2N3.

 

Any ideas???

 

 

Get-VM : 3/7/2019 11:49:04 AM   Get-VM          VM with name 'PRDV2N3 ' was not found using the specified filter(s).   

At C:\temp\keep.ps1:24 char:1

+ Get-VM -Name $($line.name) | Set-VM -memoryGB $($line.memory) -NumCpu ...

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

    + CategoryInfo          : ObjectNotFound: (:) [Get-VM], VimException

    + FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

 

 

start-vm : 3/7/2019 11:49:04 AM Start-VM                Could not find VirtualMachine with name 'PRDV2N3 '.

At C:\temp\keep.ps1:26 char:1

+ start-vm -vm $($line.name) -confirm:$false

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

    + CategoryInfo          : ObjectNotFound: (PRDV2N3 :String) [Start-VM], VimException

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

   ts.Commands.StartVM

 

 

start-vm : 3/7/2019 11:49:04 AM Start-VM                Value cannot be found for the mandatory parameter VM

At C:\temp\keep.ps1:26 char:1

+ start-vm -vm $($line.name) -confirm:$false

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

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

    + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM

 

VM Build Script

 

$ScriptRoot = Split-Path $MyInvocation.MyCommand.Path

$csvfile = "$ScriptRoot\vmbuilder.csv"

$vms2deploy = Import-Csv -Path $csvfile

#For every line in the csv variable do something:

foreach ($line in $vms2deploy) {

Get-OSCustomizationSpec -Name $($line.oscust) | New-OSCustomizationSpec -name "$($line.oscust)_$($line.name)"

Get-OSCustomizationSpec "$($line.oscust)_$($line.name)"| Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $($line.ip) -SubnetMask $($line.mask) -DefaultGateway $($line.gw) -Dns $($line.dns1),$($line.dns2)

 

$vmhost = get-cluster $($line.cluster) | get-vmhost -state connected | Get-Random

 

new-vm -name $($line.name) -template $($line.template) -vmhost $vmhost -oscustomizationspec "$($line.oscust)_$($line.name)" -datastore $($line.datastore) -location $($line.folder) -DiskStorageFormat thin

 

Get-VM -Name $($line.name) | Set-VM -memoryGB $($line.memory) -NumCpu $($line.cpu) -confirm:$false

start-vm -vm $($line.name) -confirm:$false

Remove-OSCustomizationSpec "$($line.oscust)_$($line.name)" -confirm:$false

}


Change output of a script to include the VM name?........maybe?

$
0
0

So I'm running this script found here: VMX Raiders Revisited - LucD notes

 

It runs and does what I need it to do. It outputs the below when finished....

 

PS C:\Users\user> C:\Users\user\Desktop\ImportVMsFromDatastore.ps1

 

Name                           State      % Complete Start Time   Finish Time

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

RegisterVM_Task                Running             0 01:26:59 PM             

RegisterVM_Task                Running             0 01:26:59 PM             

RegisterVM_Task                Running             0 01:27:00 PM             

RegisterVM_Task                Running             0 01:27:00 PM             

 

 

My question is, how do you make it output the actual VM name instead of "RegisterVM_Task "?

Or is that just the step the script is at for that specific VM in the list?

 

Also, how about stamping the finish time as well? Not important but just for completeness for my OCD.......lol

 

Thanks

PowerCLI - Get SDRS datastore recommendation to deploy VM via Scorch

$
0
0

In absence of vRA, I'm trying to work on some deployment runbooks for VMs in System Center Orchestrator (Scorch) that can be published in Service Manager. It appears that Scorch does not support datastore clusters/SDRS in the Clone Windows VM activity.

 

Any ideas using PowerCLI?  Is there a way via PowerCLI to get a recommended datastore name that I can then use/pass along to the Clone Windows VM activity?

 

Thanks.

drs

$
0
0

Hi Luc,

not a powercli question but if yu could sugesst something.

can you suggest something on the following  hosts memory utilization in cluster .its been there for last two days .one of the hosts is statying at 92 percent .

i changed settings to aggressive to see any improvement happens .canyou suggest any other way of handling this if possible from our end .

 

 

Get-CIVM -vApp -name | Open-VMConsoleWindow Current version of VMRC only supports vSphere VMs

$
0
0

I am using following script to open the console of a vcloud vm

 

Get-Module –ListAvailable VM* | Import-Module

$VM_Server = <servername>

$VM_ServerUname = <username>

$VM_ServerPwd = <password>

$VM_Name = <vmname>

$VAPP_Name =<vapp name>

$VM_Org = <org>

Connect-CIServer -Server $VM_Server -User $VM_ServerUname -Password $VM_ServerPwd -Org $VM_Org

Get-CIVM -VApp $VAPP_Name -name $VM_Name | Open-VMConsoleWindow

 

It is working fine till Connect-CIServer and I can even get vm details using following command:

Get-CIVM -VApp $VAPP_Name -name $VM_Name

 

But getting following error while executing Get-CIVM -VApp $VAPP_Name -name $VM_Name | Open-VMConsoleWindow :

Open-VMConsoleWindow Current version of VMRC only supports vSphere VMs

 

Complete output:

Open-VMConsoleWindow : 3/7/2019 3:11:14 PM    Open-VMConsoleWindow

Current version of VMRC only supports vSphere VMs

At line:1 char:71

+ Get-CIVM -VApp "Encryption-vApp-Automation" -name "enc-win7x64-rme" |

Open-VMCon ...

+

~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Open-VMConsoleWindow], Inv

   alidArgument

    + FullyQualifiedErrorId : Core_OpenVMConsoleWindow_OnlyvSphereVMsSupported

   ,VMware.VimAutomation.ViCore.Cmdlets.Commands.OpenVMConsoleWindow

 

Power CLI Version: VMWare PowerCLI 6.5 Release 1 build 4624819

Invoke-vmscript

$
0
0

Hello Lucd/all

 

I would like to reset the AD account password of one VM using invoke-vmscript, but fact is I don't have access however guest local SYSTEM account has previlage, so is there any possibility the run the command using guest Local system account using invoke-vmscript  ?

Powercli Linked clones | Datastore cluster

$
0
0

Hi community,

 

I'm currently working on automating linked clones on a datastore cluster using this powershell function:

 

Function New-VMLinkedClone {

    [CmdletBinding()]

    param (

        [string]$vCenterserver,

        [string]$TargetVM,

        [string]$vCenterUser,

        [String]$vCenterPassword,

        [string]$BaseVM,

        [string]$TargetDatastore,

        [string]$ResourcePool

    )

 

    ### Connect vSphere

    Connect-VIServer -server $vCenterserver -user $vCenterUser -Password $vCenterPassword

 

    ### Check if there is already a linkedclone snapshot for the clone and delete it

    $SnapshotExists = Get-Snapshot -VM $BaseVM

 

    if ($SnapshotExists.Name -eq "Linked-Snapshot-for-$TargetVMs") {

        Write-Host "Linked-Snapshot-for-$TargetVMs already exists" -ForegroundColor red

        Read-Host -Prompt "Press any key to delete the snapshot and continue or CTRL+C to quit"

 

        $ExistingSnapshot = Get-Snapshot -VM $BaseVM -Name "Linked-Snapshot-for-$TargetVMs"

        Remove-Snapshot -Snapshot $ExistingSnapshot -Confirm:$false

        write-host "Old snapshot deleted" -ForegroundColor Green

    }

 

    ### Create Master Snapshot

    $SnapShot = New-Snapshot -VM $BaseVM -Name "Linked-Snapshot-for-$TargetVM" -Description "Snapshot for linked clones for $TargetVM" -Memory -Quiesce

    Write-Host "Snapshot created for $BaseVM" -ForegroundColor Green

 

    ### Create Linked Clone

    $DataStoreCluster = Get-DatastoreCluster -Name "$TargetDatastore"

    $LinkedClone = New-VM -Name $TargetVM -VM $BaseVM -Datastore $DataStoreCluster -ResourcePool $ResourcePool -LinkedClone -ReferenceSnapshot $SnapShot

    write-host "Linked clone $TargetVM created" -ForegroundColor Green

}

 

This function works well for single datastores, but when I specify a datastore cluster, I get this error:

New-VM The operation for the entity "" failed with the following message: "A specified parameter was not correct: CloneBase

 

Does any one have a clue about this error.

 

Thanks in advance.

VMware Horizon 7.7.0 powershell to see if a specific user ID has an active session

$
0
0

I'm currently exploring working within VMware Horizon View powercli and I'm not having much success with trying to create a script to parse a list of users from a text file to see if they have an active session to a Horizon environment. I haven't done much with the Horizon module in powershell and I can't seem to find much documentation for what all of the available cmdlets do. Has anyone tried to do this same type of thing? If so, could I see an example of a script where this was accomplished?

 

Thanks in advance!


Powercli to get "show system storage " output of all NSX Edges

$
0
0

Hi team ,

        i am looking for a script where i can run  "show system storage " command on NSX edges and get the output .  Please let me know if it is possible or not . I know Edges have Vmware tools installed so we can invoke the script . The reason i asked this question is we are using NSX 6.3.2 and Edges disk get full specially /var/log partition . i want to run Script  weekly  and get the output .

 

I am aware that we can get disk capacity and free disk space of a Virtual machine , but it does not help where a Linux Virtual machine have multiple partions on a particalur disk .

Is there any way i can get the partitions inside the Virtual Machine and get their usage .

 

Thanks for help. this is what i am looking for

 

f9rzpcmne001.sushosted.com-0> show system storage

Filesystem      Size  Used Avail Use% Mounted on

/dev/root       444M  355M   66M  85% /

tmpfs           498M  3.5M  495M   1% /run

/dev/sda2        43M  1.1M   40M   3% /var/db

/dev/sda3        27M  413K   25M   2% /var/dumpfiles

/dev/sda4        32M  5.7M   25M  19% /var/log

 

 

 

Tarun Gupta

VMware host firewall rulesetid that contains a space.

$
0
0

Another question on running a PowerCLI script to change the firewall settings on a VMware Host.

When I run the script below and the "rulesetid" does not contain any spaces, it runs just fine.

However, if the rulesetid has a space I get the following error message:

Message: EsxCLI.CLIFault.summary;
InnerText: Invalid Ruleset Id.EsxCLI.CLIFault.summary
At line:1 char:1
+ $ESXcli.network.firewall.ruleset.set.Invoke($arguments1)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], MethodFault
    + FullyQualifiedErrorId : VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.MethodFault

The output for the hash table is:

Name                           Value
----                           -----    
allowedall        False 
rulsetid                       SSH Client

I have also set the $Security.Name variable in quotes ($Security.'Name' and $Security."Name") which resulted in the rulesetid to be in quotes ("SSH Client).

foreach ($Security in $SecurityProfile1) {

    $arguments1 = @{"rulesetid"= $Security.Name
                    "allowedall" = $Security.Allowed}    

$ESXcli.network.firewall.ruleset.set.Invoke($arguments1)
$ESXcli.network.firewall.ruleset.allowedip.add.Invoke($arguments2)
}

Any suggestions, etc. would be greatly appreciated.

Thanks.

drsautomationlevel_powercli

$
0
0

Hi Luc ,

 

can you please suggest why following does not work

get-vm|select name,drsautomationlevel

 

i was expecting name and drsautomationlevel of each vm .drsautomationlevel is direct property of vm .still i m getting names only.

whn i do individually i am getting name and drsautomationlevel.

vCenter Inventory

$
0
0

Hi,

I need a script or command in order to gather the following infos from a list of VM (datacenter name, cluster name, vm name and vm uuid).

 

I have used this command which works fine :

 

Get-Cluster **** | Get-VM | Select @{N=”Datacenter”;E={Get-Datacenter -VM $_}}, @{N="Cluster";E={Get-Cluster -VM $_}},Name, @{N="VMUUID";E={(Get-View $_.Id).config.uuid}} | Export-CSV "C:\DC-$(Get-Date -f ddMMyyyy).csv" -NoTypeInformation

 

Except that now I need to use a list of VM from a text file to retrieve the above infos.

 

Could you please help me out?

Need to know the contents in datastore using powercli or power shell commands

$
0
0

I need to get the contents in a datastore present in our environment , how can i get those using a powershell or powercli commands ?

Export outfile to formated table in list vm with less disk space

$
0
0

HI ,

 

I need to get  the out put this report  to formatted table and send as html

 

Connect-VIServer Server -user "username" -Password "password"

ForEach ($VM in Get-VM | where-object {($_.powerstate -ne "PoweredOff") -and ($_.Extensiondata.Guest.ToolsStatus -Match ".*Ok.*")}){

ForEach ($Drive in $VM.Extensiondata.Guest.Disk) {

$Path = $Drive.DiskPath

#Calculations

$Freespace = [math]::Round($Drive.FreeSpace / 1MB)

$Capacity = [math]::Round($Drive.Capacity/ 1MB)
$SpaceOverview = "$Freespace" + "/" + "$capacity"

$PercentFree = [math]::Round(($FreeSpace)/ ($Capacity) * 100)

if ($PercentFree -lt 10) {    

    $Output = $Output + "VM: " + $VM.Name + "`n"

    $Output = $Output + "Disk: " + $Path + "`n"

    $OutPut = $Output + "Free(MB): " + $Freespace + "`n"

    $Output = $Output + "Free(%): " + $PercentFree + "`n" 

}

}

}

$Output | Out-File \path\report.csv

List of ESXi hosts and uptime (days)

$
0
0

Ok, I know it's possible but need some help on the follow-thru.

 

I am trying to get a list of hosts in a vcenter with the following columns.

 

datacenter |  cluster | hosts name | uptime in Days

 

All I have so far is:

 

Get-VMHost | Get-View | select @{N="Uptime"; E={(Get-Date) - $_.Summary.Runtime.BootTime}}


but that just gives me it in boot time when I need just the number of days.


Also, I need to get this in a .csv.  This is what I am coming up with but something is way off here....I am so new to this still and can't put the pieces together.  Any help is appreciated.


Get-Cluster |

Select Name,

  @{N="Datacenter";E={Get-Datacenter -Cluster $_ | Select -ExpandProperty Name}},

  @{N="Hosts";E={$_.ExtensionData.Host.Count}},

  @{N="Uptime"; E={$_.ExtensionData.Summary.Runtime.BootTime $end).days}},

    Select -ExpandProperty Sum

  }} | Export-Csv c:\report2.csv -NoTypeInformation -UseCulture


Poweroff and Poweron 1000 VMs in Parallel

$
0
0

Hi

 

I've a maintenance is coming up for which I need to shutdown 1000+ VMs and once the Maintenance is complete, Need to start those VMs back on.

 

I've a list of 1000 VMs and I can run in for loop but that will take hours to shutdown these VMs and I only have 2 hours of Maintenance window, Can someone please help ?

 

Here is the script which I got from the community and it works as expected but it runs serially.

 

foreach ($vmlist in (Get-Content -Path C:\vmlist1.txt)){

$vm = Get-VM -Name $vmlist

Start-VM -VM $vm -Confirm:$false -RunAsync

}

 

Thanks & Regards

Count VMs per portgroup

$
0
0

Get-vdportgroup | Get-V< -pipelinevariable VM | Select .....

 

And then what? I need to list portgroup name, along with the count of related VMs.

 

Thank you,

Connect-HVServer fails because VMware.VimAutomation.logging.SoapInterceptor cannot be loaded

$
0
0

Hi!

 

Im trying to get started in automating Horizon View using PowerCLI.

On my Windows 7 box :

 

PS C:\Windows\system32> $PSVersionTable


Name                           Value
----                           -----
PSVersion                      5.1.14409.
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0,
BuildVersion                   10.0.14409
CLRVersion                     4.0.30319.
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3

 

I installed PowerCLI from PSGallery

 

PS C:\Windows\system32> Get-Module Vmware* -ListAvailable    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules




ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     6.7.0.1... VMware.DeployAutomation             {Add-DeployRule, Add-ProxyServer, Add-ScriptBundle, Copy-D...
Script     6.7.0.1... VMware.ImageBuilder                 {Add-EsxSoftwareDepot, Add-EsxSoftwarePackage, Compare-Esx...
Manifest   11.2.0.... VMware.PowerCLI
Script     6.7.0.1... VMware.Vim
Script     11.2.0.... VMware.VimAutomation.Cis.Core       {Connect-CisServer, Disconnect-CisServer, Get-CisService}
Script     11.0.0.... VMware.VimAutomation.Cloud          {Add-CIDatastore, Connect-CIServer, Disconnect-CIServer, G...
Script     11.2.0.... VMware.VimAutomation.Common
Script     11.2.0.... VMware.VimAutomation.Core           {Add-PassthroughDevice, Add-VirtualSwitchPhysicalNetworkAd...
Script     11.2.0.... VMware.VimAutomation.Hcx            {Connect-HCXServer, Disconnect-HCXServer, Get-HCXAppliance...
Script     7.6.0.1... VMware.VimAutomation.HorizonView    {Connect-HVServer, Disconnect-HVServer}
Script     10.0.0.... VMware.VimAutomation.License        Get-LicenseDataManager
Script     11.2.0.... VMware.VimAutomation.Nsxt           {Connect-NsxtServer, Disconnect-NsxtServer, Get-NsxtPolicy...
Script     11.2.0.... VMware.VimAutomation.Sdk            {Get-ErrorReport, Get-InstallPath, Get-PSVersion}
Script     11.0.0.... VMware.VimAutomation.Security       {Get-SecurityInfo, Get-VTpm, Get-VTpmCertificate, Get-VTpm...
Script     11.2.0.... VMware.VimAutomation.Srm            {Connect-SrmServer, Disconnect-SrmServer}
Script     11.2.0.... VMware.VimAutomation.Storage        {Add-KeyManagementServer, Copy-VDisk, Export-SpbmStoragePo...
Script     1.3.0.0    VMware.VimAutomation.StorageUtility Update-VmfsDatastore
Script     11.2.0.... VMware.VimAutomation.Vds            {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, E...
Script     11.2.0.... VMware.VimAutomation.Vmc            {Connect-Vmc, Disconnect-Vmc, Get-VmcSddcNetworkService, G...
Script     10.0.0.... VMware.VimAutomation.vROps          {Connect-OMServer, Disconnect-OMServer, Get-OMAlert, Get-O...
Script     6.5.1.7... VMware.VumAutomation                {Add-EntityBaseline, Copy-Patch, Get-Baseline, Get-Complia...

 

I tried Importing only PowerCLI, VimAutomation.HorizonView and both (trying both modules first). Also tried Installing VimAutomation.Sdk explcititly.

 

But when I try to connect to a HV server, I get (also tried with passing credentials, domain):

PS C:\Windows\system32> Connect-HVServer -server vdi-xxxxx.xxx.de
Connect-HVServer : Die Datei oder Assembly "VMware.VimAutomation.Logging.SoapInterceptor, Version=1.0.0.570,
Culture=neutral, PublicKeyToken=null" oder eine Abh���ngigkeit davon wurde nicht gefunden. Das System kann die
angegebene Datei nicht finden.
At line:1 char:1
+ Connect-HVServer -server vdi-connect01.resource.sonia.de
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-HVServer], FileNotFoundException    + FullyQualifiedErrorId : System.IO.FileNotFoundException,VMware.VimAutomation.HorizonView.Commands.Cmdlets.Connec   tHVServer

 

How can I get this thing working?

 

Kind regards,

David

PowerCLi Script loops

$
0
0

Hello,

I've taken this Script for Datastore Tags:

 

Connect-viserver xxxxxxx -user xxxxxxxx -password xxxxxxxx

 

$CMDBInfo = Import-CSV .\DS-Tag.csv

# Get the header names to use as tag category names

$TagCatNames = $cmdbinfo | Get-Member | Where {$_.MemberType -eq "NoteProperty"} | Select -Expand Name

# Create the Tag Category if it doesnt exist

Foreach ($Name in ($TagCatNames | Where {$_ -ne "Name"})){

    Try{

    $tCat = Get-TagCategory $Name -ErrorAction Stop

    }

    Catch{

    Write-Host "Creating Tag Category $Name"

    $tCat = New-TagCategory -Name $Name

    }

 

    # Create Tags under the Tag Categories

    $UniqueTags = $cmdbinfo | Select -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

    }

   

   

    # Assign the Tags to the VMs/Hosts

    $cmdbinfo | Where {$_.($Name) -eq $Tag} | Foreach {

    Write-Host ".... Assigning $Tag in Category of $Name to $($_.Name)"

    New-TagAssignment -Entity $($_.Name) -Tag $tTag | Out-Null

    }

    }

}

 

The csv File looke like this:

Name,Location,StoragePool,Sync

SYNC_LA2_SVC_INFRATIS_VOL_01,LA2,MIXED,JA

SYNC_ARS_SVC_INFRATIS_VOL_01,ARS,MIXED,JA

ARS_SVC_MS-ONLY_VOL_17,ARS,MIXED,NEIN

LA2_SVC_RELEASEMGMT_VOL_01,LA2,MIXED,NEIN

LA2_SVC_RELEASEMGMT_VOL_02,LA2,MIXED,NEIN

LA2_SVC_RELEASEMGMT_VOL_03,LA2,MIXED,NEIN

LA2_SVC_Releasemgmt_Restore-Test,LA2,MIXED,NEIN

 

The Script generates only the catagory "Location" with the Tags LA2 oder ARS. Then it runs in a loop with no errors. The other catagories and tags are not generated.

 

What's wrong?

 

Thank you

 

Best regards

Andi

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\redacted\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
Viewing all 14549 articles
Browse latest View live


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