PowerCLI

 View Only
  • 1.  New-Folder and New-TagAssignment

    Posted Mar 14, 2025 11:34 AM

    I have a much larger VM decom script that I've tested on my home lab and works just fine in 8.0.

    However, running the same exact script at work in an 7.0.3 environment fails throws errors on the following lines.

    if (!(Get-Folder -Name "DECOM" -Location (Get-Folder vm))) { New-Folder -Name "DECOM" -Location (Get-Folder vm) -Server $vCenterServers } - This actually doesn't error. It just doesn't create the folder in a 7.0.3 environment. The hope is it looks for the DECOM folder and if it doesn't exist, creates it. 

    New-TagAssignment -Tag $tagname -Entity $vmobject - This throws the following: The TagCisImpl - 'Excluded' must be managed by the same VC Server that you are using to invoke this operation. This error very much appears to be saying that the tag I'm attempting to assign doesn't actually exist. It does. I'm connecting to about 10 vCenters to run this command and I haven't verified it's in all of them but it's certainly there with the specific vCenter my test VM is located. 

    I cant post the entire thing if need as I know some of these are variables but the script works perfectly in my home environment as previously stated. 



  • 2.  RE: New-Folder and New-TagAssignment

    Posted Mar 14, 2025 06:11 PM

    What exactly is in the variable $vCenterServers ?
    Same for $tagname.

    When you launch a cmdlet against multiple vCenters, the cmdlet will be executed on each of these vCenters.
    If that Tag doesn't exist on one of the vCenters, you will get a similar error message.

    It could be helpful to include the full error message.
    And perhaps try to use the New-TagAssignment in a Try-Catch construct, where you examine what is in $error[0] in the Catch block.



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


    Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference


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



  • 3.  RE: New-Folder and New-TagAssignment

    Posted Mar 17, 2025 11:06 AM

    Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

    $vCenterServers =@("vCenter1","vCenter2","vCenter3","vCenter4","vCenter5","vCenter6")

    Connect-viserver -server $vCenterServers

    $csvpath = "F:\Scripts\Decom-vms\vmnames.csv"

    $vms = Import-csv $csvpath

    $decomDate = (Get-Date).AddDays(30).ToString('yyyy-MM-dd')

    $sam = Get-ADUser ($env:USERNAME)

    $name1 = $sam.Name

    $changeRecord = Read-Host "Enter Change Record"

    $note = "Decom Per $changeRecord -" +  "$name1 -" + " Delete no earlier than $decomDate"

    $tagname = "Excluded"

    # Looks for DECOM folder, if it doesn't exist it will create

    if (!(Get-Folder -Name "DECOM" -Location (Get-Folder vm))) { New-Folder -Name "DECOM" -Location (Get-Folder vm) -Server $vCenterServers }

     foreach ($vm in $vms) {

        $vmObject = Get-VM -Name $vm.Name

    # Assigns new backup tag so you're not backing up a machine that is off

            New-TagAssignment -Tag $tagname -Entity $vmObject

    # Turns the VM off

                Stop-VM -vm $vmObject -Confirm:$false

    # Sets the VM notes with Change Number, your name, and when it can be deleted

            Set-VM -vm $vmObject -Notes $note -Confirm:$false

    # Moves the VM to the DECOM folder

        Move-VM -vm $vmObject -Destination DECOM

    }

    Disconnect-VIServer -Server $vCenterServers




  • 4.  RE: New-Folder and New-TagAssignment

    Posted Mar 18, 2025 10:33 AM
    Edited by ITSavant Mar 18, 2025 10:40 AM

    Anytime you are connected to multiple vCenters simultaneously, you should ALWAYS use the -server "vCentername" on all of your cmdlets. In fact, I always use it just to stay in the habit because I manage an uncommonly large environment. NOTE: in most cases this should be a single vCenter targeting the one managing the specific object you are working on, unless you don't know where it is.

    Get-Folder -Name "DECOM" -Location (Get-Folder vm) -Server "vCenterName"  <-SINGULAR NAME
    New-Folder -Name "DECOM" -Location (Get-Folder vm) -Server $vCenterServers  <- THIS IS WRONG, SHOULD BE 1 vCENTER

    $vmObject = Get-VM -Name $vm.Name -Server "vCenterName"  <-SINGULAR NAME

    New-TagAssignment, Stop-VM, Set-VM, and Move-VM do not require -Server, because the $vmObject contains a reference to it's own vCenter, although for habit and consistency, not a bad idea to provide it anyhow.

    You will save yourself a LOT of potentially unwanted consequences and red errors on screen






  • 5.  RE: New-Folder and New-TagAssignment

    Posted Mar 18, 2025 11:54 AM
    Edited by rgp982 Mar 18, 2025 11:55 AM

    Thanks for the tip.

    I set it up this way because I was hoping many people could use the script without having to update it depending on which vCenter the VM is located. 

    Would that be the cause to both of the issues I'm seeing? It would make sense because my home lab is just a single vCenter whereas I manage several at work. 

    Do you have a suggestion to make this work without someone who may not exactly know what they are doing having to update the script per the vCenter? 




  • 6.  RE: New-Folder and New-TagAssignment

    Posted Mar 18, 2025 01:00 PM

    You could do something like this

    Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
    
    $vCenterServers = @("vCenter1", "vCenter2", "vCenter3", "vCenter4", "vCenter5", "vCenter6")
    Connect-VIServer -Server $vCenterServers
    
    $csvpath = "F:\Scripts\Decom-vms\vmnames.csv"
    $vms = Import-Csv $csvpath
    $decomDate = (Get-Date).AddDays(30).ToString('yyyy-MM-dd')
    $sam = Get-ADUser ($env:USERNAME)
    $name1 = $sam.Name
    $changeRecord = Read-Host "Enter Change Record"
    $note = "Decom Per $changeRecord -" + "$name1 -" + " Delete no earlier than $decomDate"
    $tagname = "Excluded"
    
    # Looks for DECOM folder, if it doesn't exist it will create
    
    if (!(Get-Folder -Name "DECOM" -Location (Get-Folder vm))) { 
        New-Folder -Name "DECOM" -Location (Get-Folder vm) -Server $vCenterServers 
    }
    foreach ($vm in $vms) {
        $vmObjects = Get-VM -Name $vm.Name
    
        # Loop over all VMs, just in case VMs with the same DisplayName exist on multiple vCenters
        foreach ($vmObject in $vmObjects) {
            
            # Find vCenter to which the VM belongs
            $vc = ([System.Uri]$vmObject.ExtensionData.Client.ServiceUrl).Host 
    
            # Assigns new backup tag so you're not backing up a machine that is off
            New-TagAssignment -Tag $tagname -Entity $vmObject -Server $vc
    
            # Turns the VM off
            Stop-VM -VM $vmObject -Confirm:$false -Server $vc
    
            # Sets the VM notes with Change Number, your name, and when it can be deleted
            Set-VM -VM $vmObject -Notes $note -Confirm:$false -Server $vc
    
            # Moves the VM to the DECOM folder
            Move-VM -VM $vmObject -Destination DECOM -Server $vc
        }
    }
    
    Disconnect-VIServer -Server $vCenterServers


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


    Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference


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



  • 7.  RE: New-Folder and New-TagAssignment

    Posted Mar 18, 2025 10:32 PM

    Sadly it still errors on the New-TagAssignment. The tag absolutely exists in the vCenter the server is in. 

    The only other error is one failing to move the VM to the new DECOM folder, but that's because it doesn't exist. No error on creating the new folder, it just isn't created. 

    New-TagAssignment : 3/18/2025 9:21:51 PM  New-TagAssignment       com.vmware.vapi.std.errors.unauthenticated {'messages': [com.vmware.vapi.std.localizable_message {'id':

    com.vmware.vapi.endpoint.method.authentication.required, 'default_message': Authentication required., 'args': [], 'params': , 'localized':}], 'data': , 'error_type':

    UNAUTHENTICATED, 'challenge': Basic realm="VAPI endpoint",SIGN realm=5f7547bb23f16883d4bd23fe9192030b6f7fd0db,service="VAPI

    endpoint",sts="vcenter"}     

    At line:59 char:9

    +         New-TagAssignment -Tag $tagname -Entity $vmObject -Server $vc

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

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

        + FullyQualifiedErrorId : VMware.VimAutomation.ViCore.Impl.V1.Service.Tagging.Cis.TaggingServiceCisImpl.GetTag.Error,VMware.VimAutomation.ViCore.Cmdlets.Commands.Taggin

       g.NewTagAssignment

     

    New-TagAssignment : 3/18/2025 9:21:52 PM  New-TagAssignment       Could not find Tag with name 'Excluded'.  

    At line:59 char:9

    +         New-TagAssignment -Tag $tagname -Entity $vmObject -Server $vc

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

        + CategoryInfo          : ObjectNotFound: (Excluded:String) [New-TagAssignment], VimException

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

     

    New-TagAssignment : 3/18/2025 9:21:52 PM  New-TagAssignment       Value cannot be found for the mandatory parameter Tag 

    At line:59 char:9

    +         New-TagAssignment -Tag $tagname -Entity $vmObject -Server $vc

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

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

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




  • 8.  RE: New-Folder and New-TagAssignment

    Posted Mar 19, 2025 04:21 AM

    Could it be that one or more services on the VCSA where that VM is located is not running or in a funny state?
    If you have the option, a restart of that specific VCSA might help.



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


    Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference


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