<#
.SYNOPSIS
    Move Virtual Machines to the correct folder based on the AppName tag
.DESCRIPTION
    Move Virtual Machines to the correct folder based on the AppName tag
.NOTES
    
.LINK
    
.EXAMPLE
    Move-ITDVMwareVMToAppNameFolder -VMName itdservername.nd.gov
#>

function Move-ITDVMwareVMToAppNameFolder {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $VMName
    )
    
    begin {
    }
    
    process {
        Write-Verbose -Message "Gathering Virtual Machine information"
        $VMs = Get-VM -Name $VMName | Select-Object Name, PowerState, Folder, @{n = 'VIServer'; e = { $_.Uid.split('@')[1].split(':')[0] } }, @{n = 'AppName'; e = { (Get-TagAssignment -Category AppName -Entity $_).Tag.Name } }, @{n = 'Datacenter'; e = { ($_ | Get-Datacenter).Name } } | Sort-Object Name
        
        ForEach ($VM in $VMs) {
            Write-Verbose -Message ("Start " + $VM.Name)

            $NewFolder = $null
            $Owner = $VM.AppName.split('-')[0]

            Write-Verbose ($VM.Name + ": current folder is  " + $VM.Folder.Name)
            Write-Verbose ($VM.Name + ": current appname is " + $VM.AppName)
                
            If ($VM.Folder.Name -ne $VM.AppName) {
                If ($VM.AppName) {
                    Write-Verbose ($VM.Name + ": Folder and AppName are different!!! moving VM to folder " + $VM.AppName)    
                    If (!(Get-Datacenter $VM.Datacenter | Get-Folder -Name $VM.AppName -Server $VM.VIServer -ErrorAction SilentlyContinue)) {
                        New-Folder -Name $VM.AppName -Location (Get-Datacenter $VM.Datacenter | Get-Folder -Type VM -Name $Owner -Server $VM.VIServer)
                    }
                    
                    $NewFolder = Get-Datacenter $VM.Datacenter | Get-Folder $VM.AppName -Server $VM.VIServer
                    Move-VM -VM $VM.Name -InventoryLocation $NewFolder -Destination (Get-VM $VM.Name -Server $VM.VIServer).VMHost
                }
                Else {

                }
            }    
        }
        
    }
    
    end {
    }
}
