Sample send receive Lync / Skype for business messages using powershell

Before you start you need to obtain the Lync SDK package (https://download.microsoft.com/download/0/5/6/056013D5-98F8-4B79-88EF-D221E519C37F/lyncsdk.exe)

I had hard time to have it working with listening what ‘other’ people are writing in the conversation. Thanks to this post(‘John O’ reply) i was able to properly hook the event(to the right participant).
The ‘what*’, was aimed at message: “What is 2+4” or “what is 10*3” for example.
In response you should get the reply with the result.

If you want to test it with ‘somebody’.

cd "C:\Program Files (x86)\Microsoft Office\Office15\lyncsdk\Assemblies\Desktop"
Import-Module .\Microsoft.Lync.Model.dll
$Client = [Microsoft.Lync.Model.LyncClient]::GetClient()
$Conversation = $client.ConversationManager.AddConversation()
$person=$client.ContactManager.GetContactByUri('person@domain.com')
$conversation.AddParticipant($person)


Get-EventSubscriber|Unregister-Event
  # For each participant in the conversation
  $conversation.Participants | Where { !$_.IsSelf } | foreach {
    Register-ObjectEvent -InputObject $_.Modalities[1] -EventName "InstantMessageReceived" -SourceIdentifier "person $i" -action { 
    $global:conv = $event
    $msg = $conv.SourceEventArgs.Text.trim()
    write-host $msg
    switch -Wildcard ($msg) {
     "What*" {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
     "Hello" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Hello human", {}, 0)}
     "stupid robot" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Humanity is overrated", {}, 0)}
    }
    }
    $i++
   }

Or if you don’t have friends and want to test it against yourself (2nd client running).

cd "C:\Program Files (x86)\Microsoft Office\Office15\lyncsdk\Assemblies\Desktop"
Import-Module .\Microsoft.Lync.Model.dll
$Client = [Microsoft.Lync.Model.LyncClient]::GetClient()
$Conversation = $client.ConversationManager.AddConversation()
$conversation.AddParticipant($client.Self.Contact)

Get-EventSubscriber|Unregister-Event
  $conversation.Participants[0]| foreach {
    Register-ObjectEvent -InputObject $_.Modalities[1] -EventName "InstantMessageReceived" -SourceIdentifier "person $i" -action { 
    $global:conv = $event
    $msg = $conv.SourceEventArgs.Text.trim()
    write-host $msg
    #if ($msg -like 'What*') {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
    switch -Wildcard ($msg) {
     "What*" {$Conversation.Modalities['InstantMessage'].BeginSendMessage((Invoke-Expression $msg.split()[-1]), {}, 0)}
     "Hello" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Hello human", {}, 0)}
     "stupid robot" {$Conversation.Modalities['InstantMessage'].BeginSendMessage("Humanity is overrated", {}, 0)}
    }
    }
    $i++
   }

You can send message using the PS session anytime then:
$Conversation.Modalities[‘InstantMessage’].BeginSendMessage(‘text’, {}, 0)}
Some useful links:
https://msdn.microsoft.com/en-us/library/office/jj937273.aspx
https://msdn.microsoft.com/en-us/library/office/hh243705(v=office.14).aspx
https://msdn.microsoft.com/en-us/library/office/jj933215.aspx
https://msdn.microsoft.com/en-us/library/office/jj937298.aspx
https://msdn.microsoft.com/en-us/library/office/jj933248.aspx
https://blogs.technet.microsoft.com/heyscriptingguy/2011/06/16/use-asynchronous-event-handling-in-powershell/

Migrating virtual center to another virtual center

!!! WARNING !!!
this is not finished ! DO NOT RUN THIS ON PRODUCTION SYSTEMS !!! UNLESS YOU HAVE TESTED IT IN DEV !!!

Gents, please do not treat this as a ready-to-go solution, you would have to understand the contents, in order how to apply this. Destroying your production is that last thing i want.
I had to write this to recover a VC after a major bug/failure. I had to create another VirtualCenter in order to fix the issue. The main goal of this script is to move ‘everything’ i had in the old virtual center server to the new one.

PLEASE NOTE !!!
DVS is not supported here at this moment

Before you comment this, yes, i know that there are already some software/script for doing this, but in my opinion they were not doing everything or not in the way i wanted to do it. That’s why i created this.
This is not completed ! I have tested it numerous times on dev platforms, for me it was working. The only part which is not here is the cluster configs and dvs. Script will not configure your virtual center, but just the ‘content’ including, folder (of any kind), dc, clusters, vapps. The placements + permissions. The annotations are written in previous posts as well as roles.
I know it’s messy, yes… Although i think i will not spend more time on this, unless i will have to do so. I just hope that it might help for people that had similar task to do, and they were lacking some features in their clone of virtual center.
I DO NOT GUARANTEE THE RESULTS OF THE SCRIPT. Gents, please test this first in your test/dev environments. I have been running this script at least 600-800 times, until i was happy with the outcome, where it worked for me. Please have in mind it will not take into consideration on DVS setup. I’ve come up with 2 solutions for dvs, but never implemented it in it. I have decided to write this on my own mainly to test myself if i am able to do so. There might be better ways of doing it(100% sure of that 😉 ). I have put some comments in the script so you can know what to expect at which moment, the execution of this script is divided in many parts. It’s because i never got to 100% with this script i left myself spots to understand where it can go wrong.
I am sorry in some way that i did not explain this entirely, but i would have spend serious amount of hours on that…
I will have to check if i have posted the role-cloning script on blog, because this is something that is expected to be in place for this to work.

#READ THIS VARIABLE FIRST!!!
#$ProjectNAme

function traverse-HostView3 
{
param(
[Parameter(Mandatory=$true)]$originVC,
[Parameter(Mandatory=$true)]$root,
[Parameter(Mandatory=$true)]$type,
[Parameter(Mandatory=$true)]$destinationroot,
[Parameter(Mandatory=$true)]$destinationVC,
[Parameter(Mandatory=$true)]$DatabaseFile,
[string]$DestMorefDC
)

$permissionFile = $DatabaseFile+'-Permissions.csv'

#the type can be following :
#HostFolder - For the Host/Clusters view
#

#Datacenter Object does not contain ChildEntity property, it is a point where folders are split on
#VmFolder            
#HostFolder          
#DatastoreFolder     
#NetworkFolder       
#Hence when we encounter the datacenter object, we are switching root obj to become a HostFolder of that root/Datacenter

#"function start:: , passed root is now "+$root.name

"my root moref type is now "+$root.moref
"Child entities inside this root are: "+($root.ChildEntity -join ',')
#"Will start now the IF section"

################
################ WHAT TO DO IN ORDER TO GET THE TOP ROOT FOLDER -D1 , to get his permissions, since iteration starts from children ?!?!
################ Make entry at the verybottom for folder -d1 , and just take all settings from it, as 1 -off
if ($root.moref.type -eq 'Datacenter') 
{ 
$root = get-view -id $root.$type -server $originVC
}
if ($root.moref.type -eq 'ClusterComputeResource')
{
#break
#we are 'cheating' here to get the compliance for the ChildEntity. Since Cluster does not have ChildEntity that would describe all its hosts. We are creating a column with ChildEntity that include all hosts
#This will also make a situation that resourcepools will not be checked, since we redirected already path to Hosts, we can also add to Children resource pools later on.
$root =$root | Select *,@{n='ChildEntity';e={$_.Host}}
}

if ($root.moref.type -eq 'VirtualApp')
{
#we are 'cheating' here to get the compliance for the ChildEntity. Since Cluster does not have ChildEntity that would describe all its hosts. We are creating a column with ChildEntity that include all hosts
#This will also make a situation that resourcepools will not be checked, since we redirected already path to Hosts, we can also add to Children resource pools later on.
$root =$root | Select *,@{n='ChildEntity';e={$_.Vm}}
}

#if ($root.moref.type -eq 'Datastore') {break}

#"If section was finished, now we will be collecting children"

if ($root.ChildEntity)
{
    $children = get-view -id $root.ChildEntity -server $originVC
    foreach ($child in $children)
    {
       "!!!!!"+ $child.name + " :: "+ $child.moref
       # Switch [typ]
       switch ($child.moref.type) 
    { 
        'Datacenter' {
        "We hit Datacenter"
        $CreatedObject = Get-view  (get-view -id ($destinationroot.createdatacenter($child.name)) -server $destinationVC).HostFolder -server $destinationVC
        $CreatedDatacenter = get-view -id $CreatedObject.parent -Server $destinationVC 
        #sourcedatacenter = $child
        #Datacenter reference database
        "showing object"
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$CreatedDatacenter.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        #$SourceDCPermission = g
        
        #$DCobject = get-view -id $child.parent -Server $originvc
        
        if ($child.Permission){ 
        write-host  "I saw permissions inside the DC object" 
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$CreatedDatacenter.Moref.ToString()}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }

        } 
        'Folder' {
        "We hit folder:"
        $CreatedObject = get-view $destinationroot.createfolder($child.name) -server $destinationVC
        #$CreatedObject = get-view (New-Folder -Server $destinationvc -name $child.name -Location ($destinationroot|Get-VIObjectByVIView)).Extensiondata
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile        
        #sourceFolderPermissions
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        } 
        'ClusterComputeResource' {
        "We hit cluster"
        $CreatedObject = get-view $destinationroot.createcluster($child.name,(new-object VMware.Vim.ClusterConfigSpec)) -server $destinationVC
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        #Permissions
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }

        } 
        'VirtualApp' {"We hit VirtualApp"
        #This can only be done, when hosts are attached to cluster.
        #Createvapp is method on default resource pool inside cluster.
        #VMware.Vim.ManagedObjectReference CreateVApp(string name, VMware.Vim.ResourceConfigSpec resSpec, VMware.Vim.VAppConfigSpec configSpec,VMware.Vim.ManagedObjectReference vmFolder)
        $child.vappconfig.EntityConfig | export-clixml -Encoding 'UTF8' -depth 2 -LiteralPath ('c:\'+$child.vappconfig.InstanceUuid+'EntityConfig')
        $child.Config.CpuAllocation | export-clixml -Encoding 'UTF8' -depth 2 -LiteralPath ('c:\'+$child.vappconfig.InstanceUuid+'CpuAllocation')
        $child.Config.MemoryAllocation | export-clixml -Encoding 'UTF8' -depth 2 -LiteralPath ('c:\'+$child.vappconfig.InstanceUuid+'MemoryAllocation')
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$destinationroot.Moref.ToString()}},@{n='Objuuid';e={$child.VAppConfig.InstanceUuid}},@{n='DestMorefDC';e={}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={$child.owner.tostring()}}, @{n='vmmoref';e={}}  | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$child.name}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        }
        'HostSystem' {
        "We hit HostSystem"
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$root.moref.ToString()}},@{n='DestinationObjectMoref';e={$destinationroot.Moref.ToString()}},@{n='Objuuid';e={$child.Hardware.systeminfo.uuid}},@{n='DestMorefDC';e={$DestMorefDC}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$child.Hardware.systeminfo.uuid}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        } 
        'VirtualMachine' {
        #FOR VMS YOU HAVE TO SELECT .config.uuid property into the csv, in order to hit the proper vm. ## TODO !!!!!
        "We hit VirtualMachine"
        $vmtxpath=if ($child.config.template){$child.config.files.VmPathName}
        $vmtxHostRegistered = if ($vmtxpath) { (get-view $child.Runtime.Host -property name -Server $originvc).Name }
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$root.moref.ToString()}},@{n='DestinationObjectMoref';e={$destinationroot.Moref.ToString()}},@{n='Objuuid';e={$child.config.uuid}},@{n='DestMorefDC';e={$DestMorefDC}}, @{n='vmtxpath';e={$vmtxpath}}, @{n='vmtxHost';e={$vmtxHostRegistered}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={$child.moref.toString()}} | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile    
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$child.config.uuid}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        } 
        'Datastore' {"
        We hit Datastore"
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$root.moref.ToString()}},@{n='DestinationObjectMoref';e={$destinationroot.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={$DestMorefDC}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$child.name}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        }
        'StoragePod' {"
        We hit StoragePod"
        $CreatedObject = get-view $destinationroot.createstoragepod($child.name) -server $destinationVC
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        }
        #The ComputeResource if for a single Host inside a folder for example
        #'ComputeResource' {"
        #We hit StoragePod"
        #$CreatedObject = get-view $destinationroot.createstoragepod($child.name) -server $destinationVC
        #'' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$child.moref.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={}} | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        #if ($child.permission){  
        #$child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$CreatedObject.Moref.ToString()}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        #}
        #}
        'Network' {
        "We hit network"
        '' | Select-object @{n='ObjectName';e={$child.name}},@{n='OriginObjectMoref';e={$root.moref.ToString()}},@{n='DestinationObjectMoref';e={$destinationroot.Moref.ToString()}},@{n='Objuuid';e={}},@{n='DestMorefDC';e={$DestMorefDC}},@{n='vmtxpath';e={}}, @{n='vmtxHost';e={}}, @{n='OwnerMoref';e={}}, @{n='vmmoref';e={}}   | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $DatabaseFile
        if ($child.permission){  
        $child.Permission | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$child.name}},@{n='DestMorefDC';e={$DestMorefDC}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $permissionFile
        }
        }  
        default {"The object could not be determined : please check";read-host}
    }
       traverse-HostView3 -root $child -type $type -originVC $originVC -destinationVC $destinationVC -destinationroot $CreatedObject -DatabaseFile 'c:\databasefile.csv' -DestMorefDC $DestMorefDC
       
    }
}

}



$originvc = 'your.original.vc'
$destinationVC = 'your.new.vc'
connect-viserver $originVC -Credential (Get-credential)
connect-viserver $destinationVC -credential (get-credential)
$pscred = Get-Credential

$rootFolder = get-view -id ($global:DefaultVIServers |? {$_.name -eq $originvc}).extensiondata.content.rootfolder -Server $originvc
$destinationroot = get-view -id ($global:DefaultVIServers |? {$_.name -eq $destinationvc}).extensiondata.content.rootfolder -Server $destinationvc

traverse-HostView3 -root $rootFolder -type 'HostFolder' -originVC $originVC -destinationVC $destinationVC -destinationroot $destinationroot -DatabaseFile 'c:\databasefile.csv'



##You start first by running through Host and Clusters View, since you have to recreate the entire main structure for datacenters.
##Remember that after each run , in case you went into trouble to clear the database file, or you different file.
##
##
##Tutaj podajemy root folder w source VC, jako folder do konkretnego DC.networkFolder , tak samo w destination , nakladamy folder dc.networkfolder
#NETWORK FOLDERS:
foreach($dc in (import-csv 'c:\databasefile.csv' -Encoding 'UTF8' |? {$_.OriginObjectMoref -like "Datacenter-*"})  )
{
traverse-HostView3 -root (get-view (get-view $dc.OriginObjectMoref -server $originVC).NetworkFolder -Server $originVC) -type 'NetworkFolder' -originVC $originVC -destinationVC $destinationVC -destinationroot (get-view (get-view $dc.DestinationObjectMoref -server $destinationVC).NetworkFolder -Server $destinationVC) -DatabaseFile 'c:\databasefile.csv' -DestMorefDC ($dc.DestinationObjectMoref) 
}

#VM FOLDERS:


foreach($dc in (import-csv 'c:\databasefile.csv' -Encoding 'UTF8' |? {$_.OriginObjectMoref -like "Datacenter-*"})  )
{
traverse-HostView3 -root (get-view (get-view $dc.OriginObjectMoref -server $originVC).VmFolder -Server $originVC) -type 'VmFolder' -originVC $originVC -destinationVC $destinationVC -destinationroot (get-view (get-view $dc.DestinationObjectMoref -server $destinationVC).VmFolder -Server $destinationVC) -DatabaseFile 'c:\databasefile.csv' -DestMorefDC ($dc.DestinationObjectMoref) 
}

#Storage FOLDERS:
foreach($dc in (import-csv 'c:\databasefile.csv' -Encoding 'UTF8' |? {$_.OriginObjectMoref -like "Datacenter-*"})  )
{
traverse-HostView3 -root (get-view (get-view $dc.OriginObjectMoref -server $originVC).DatastoreFolder -Server $originVC) -type 'DatastoreFolder' -originVC $originVC -destinationVC $destinationVC -destinationroot (get-view (get-view $dc.DestinationObjectMoref -server $destinationVC).DatastoreFolder -Server $destinationVC) -DatabaseFile 'c:\databasefile.csv' -DestMorefDC ($dc.DestinationObjectMoref) 
}

###
###  COPY ROOT VC PERMISSION HERE
### 
### THIS PART IS ONLY IF YOUR LOCAL SSO DOMAIN CHANGES, MODIFY THIS IF IT IS THE SAME
$sourceSSODomain = 'VSPHERE.LOCAL'
$destinationSSODomain = 'TEST.LOCAL'

$tpermissionFile = 'databasefile.csv-Permissions.csv'
$VCSourceRootPermissions = (get-view -id 'Folder-group-d1' -server $originvc).permission |?{$_.Principal -notmatch "vpxd-|vsphere-webclient-"} 
#IF you don't want to change the local sso domain , hash the line below:
$VCSourceRootPermissions|? {$_.principal -match $sourceSSODomain} | %{$_.principal = [regex]::replace($_.Principal,$sourceSSODomain,$destinationSSODomain)}

$VCSourceRootPermissions | select @{n='OriginObjectMoref';e={$_.Entity.ToString()}},@{n='DestinationObjectMoref';e={$_.Entity.ToString()}}, Principal,RoleId,Propagate,Group | Export-Csv -NoTypeInformation -Append -Encoding 'UTF8' -LiteralPath $tpermissionFile


##
## END OF THE COPY OF VC PERMISSION
##



##
##Before replaying permissions you have to be sure that the SSO domain is the same for permissions, therefore we will replace old SSO domain with new SSO domain.
##
$RoleDB = Import-Csv -Encoding UTF8 -LiteralPath 'C:\RoleDB.csv'
$sourceSSODomain = (Get-AdvancedSetting -Entity ($global:DefaultVIServers|?{$_.Name -eq $originvc}) -Name 'config.vpxd.sso.default.admin').value.split('@')[1].ToUpper()
$destinationSSODomain = (Get-AdvancedSetting -Entity ($global:DefaultVIServers|?{$_.Name -eq $destinationvc}) -Name 'config.vpxd.sso.default.admin').value.split('@')[1].ToUpper()
$tpermissionFile = 'c:\databasefile.csv-Permissions.csv'
$permissions = import-csv -Encoding UTF8 -LiteralPath $tpermissionFile 
$permissions |% { $_.principal = [regex]::replace($_.Principal,$sourceSSODomain,$destinationSSODomain)  }
$permissions | export-csv -Encoding UTF8 -LiteralPath $tpermissionFile -NoTypeInformation

##
## REPLAY PERMISSIONS
##
$RoleDB = Import-Csv -Encoding UTF8 -LiteralPath 'C:\RoleDB.csv'
#$rolehash = @{}
#$roleDB | % { $roleHash += @{$_.SourceRoleId = get-virole -id $_.DestinationRoleID -Server $destinationVC}  }
#RoleHash is now [ID_SOURCE_ROLE]  || [ROLE_OBJECT_ON_DESTINATION]
#OriginObjectMoref      : Folder-group-v450
#DestinationObjectMoref : Folder-group-v972
#DestMorefDC            : Datacenter-datacenter-953
#Principal              : VSPHERE.LOCAL\greg
#RoleId                 : -1
#Propagate              : True
## FOLDERS DCs
## FOLDERS Hs
#### We Will need authorizationmanager from the destination VC now. method SetEntityPermissions         Method     void SetEntityPermissions(VMware.Vim.ManagedObjectReference entity, VMware.Vim.Permission[] permission)
##Entity     :
#Principal  :
#Group      : False
#RoleId     : 0
#Propagate  : False
##
##


$DestAM = get-view -id ($global:DefaultVIServers|?{$_.Name -eq $destinationvc}).extensiondata.content.AuthorizationManager -Server $DestinationVC

##
## HOSTS VIEW FOLDERS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "Folder-group-h*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## DATACENTERS NOW
##

Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "Datacenter-datacenter-*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)  
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## CLUSTERS NOW
##

Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "ClusterComputeResource-domain-c*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)  
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## NETWORK VIEW FOLDERS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "Folder-group-n*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## VM VIEW FOLDERS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "Folder-group-v*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## STORAGE FOLDERS VIEW FOLDERS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "Folder-group-s*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}

##
## STORAGE PODS VIEW FOLDERS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "StoragePod-group-p*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
$DestAM.SetEntityPermissions($entity.DestinationObjectMoref, $DestinationObjectPermission)
}


#Adding Hosts to cluster
Foreach ($cluster in ((import-csv -LiteralPath 'c:\databasefile.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "ClusterComputeResource-domain-c*"}) |?{$_.Objuuid} | Group-Object -Property destinationObjectMoref).group) 
{ 
$VMhostsInCluster = $cluster
$Clusterdestination = $VMhostsInCluster[0].DestinationObjectMoref
$location = get-view -id  $Clusterdestination -server $destinationVC| Get-VIObjectByVIView
foreach ($vmhost in $VMhostsInCluster) 
{
 Add-VMHost -Name $vmhost.ObjectName -Location $location -Credential $pscred -Force -Server $destinationVC
 }

}
#make sure that all pwd are the same

##
##Once all hosts are in place in the VC , we attach our templates
##
foreach ($vmtemplate in  (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "Folder-group-v*" -and $_.vmtxpath})){
$location = get-view -id $vmtemplate.DestinationObjectMoref -server $destinationVC | Get-VIObjectByVIView
New-Template -Name $vmtemplate.ObjectName -TemplateFilePath $vmtemplate.vmtxpath -Location $location -vmhost $vmtemplate.vmtxHost
}


##
## VMHOSTS PERMISSIONS
##
Foreach ($entity in (import-csv -LiteralPath 'c:\databasefile.csv-permissions.csv' -Encoding UTF8 | ?{$_.OriginObjectMoref -like "HostSystem-host-*"})){
$DestinationObjectPermission = New-Object VMware.vim.Permission
$DestinationObjectPermission.Principal = $entity.Principal
$DestinationObjectPermission.Group = [System.Convert]::ToBoolean($entity.Group)
$DestinationObjectPermission.RoleId = ($roleDB|?{$_.SourceRoleId -eq ($entity.RoleId)}).DestinationRoleId
$DestinationObjectPermission.Propagate = [System.Convert]::ToBoolean($entity.Propagate)
$DestinationObjectPermission
#Here our destinationObjectMoref is actually vm host uuid value , not moref. We couldn't have moref as it was unknown.
$DestinationVMHost = get-view -ViewType HostSystem -Filter @{'Hardware.SystemInfo.Uuid'=$entity.DestinationObjectMoref} -Property Name -Server $destinationVC
#$destinationVMHost
$DestAM.SetEntityPermissions($DestinationVMHost.moref, $DestinationObjectPermission)
}



##
## Moving object to their correct location
##
##
## NETWORK VIEW ENTITIES
##!!!!!!!!!!!!!!!!!!!!!!!!!! We should move only those which are not located at the datacenter, otherwise , waste of time.
$DCnetworkFolderIDs = @((get-view -id ((import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "Folder-group-n*" -and $_.DestMorefDC -like "Datacenter-datacenter-*"}) |group-object -Property DestMorefDC).Name -Server $destinationVC).NetworkFolder |% {$_.ToString()})
$allNetworksInFolders = (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "Folder-group-n*" -and $_.DestMorefDC -like "Datacenter-datacenter-*"}) | ? {$DCnetworkFolderIDs -notcontains $_.DestinationObjectMoref}
Foreach ($entity in $allNetworksInFolders){
#DestinationObjectMoref : Folder-group-n1575
$dof = get-view -id $entity.DestinationObjectMoref -server $destinationVC
$ntwkmoref = (get-view -server $destinationVC -searchroot $entity.DestMorefDC -viewtype 'Network' -filter @{'name'=$entity.ObjectName}).moref
$dof.MoveIntoFolder($ntwkmoref)
}

## VM VIEW ENTITIES
##!!!!!!!!!!!!!!!!!!!!!!!!!! We should move only those which are not located at the datacenter, otherwise , waste of time.
Foreach ($entity in (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "Folder-group-v*" -and $_.DestMorefDC -like "Datacenter-datacenter-*"})){
#DestinationObjectMoref : Folder-group-n1575
'Object'
$entity

$dof = get-view -id $entity.DestinationObjectMoref -server $destinationVC
'Destination'
$dof.name
$vmmoref = (get-view -server $destinationVC -searchroot $entity.DestMorefDC -viewtype 'Virtualmachine' -filter @{'Config.Uuid'=$entity.Objuuid}).moref
'VM Object'
$vmmoref
$dof.MoveIntoFolder($vmmoref)
}

##
## Creating Vapps, moving VMs into Vapps, Applying Vapp start order
##
Foreach ($entity in (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "VirtualApp-resgroup-v*" -and $_.OwnerMoref})){
#entity is now
#ObjectName             : LABS_Greg
#OriginObjectMoref      : VirtualApp-resgroup-v241
#DestinationObjectMoref : Folder-group-v4284
#Objuuid                : 5038914a-df12-abcc-77aa-2d2991ccaa2e
#DestMorefDC            :
#vmtxpath               :
#vmtxHost               :
#OwnerMoref             : ClusterComputeResource-domain-c7

#First we prepare the configs for our Vapp entity
$EntityMemoryAllocationXML = Import-Clixml -LiteralPath ('C:\'+$entity.Objuuid+'MemoryAllocation')
$EntityCpuAllocationXML = Import-Clixml -LiteralPath ('C:\'+$entity.Objuuid+'CpuAllocation')
$EntityConfig = Import-Clixml -LiteralPath ('C:\'+$entity.Objuuid+'EntityConfig')
$resSpec = New-Object VMware.Vim.ResourceConfigSpec
$resSpec.cpuAllocation = New-Object VMware.Vim.ResourceAllocationInfo
$resSpec.cpuAllocation.reservation = $EntityCpuAllocationXML.Reservation
$resSpec.cpuAllocation.expandableReservation = $EntityCpuAllocationXML.expandableReservation
$resSpec.cpuAllocation.limit = $EntityCpuAllocationXML.limit
$resSpec.cpuAllocation.shares = New-Object VMware.Vim.SharesInfo
$resSpec.cpuAllocation.shares.shares = $EntityCpuAllocationXML.shares.shares
$resSpec.cpuAllocation.shares.level = $EntityCpuAllocationXML.shares.level
$resSpec.memoryAllocation = New-Object VMware.Vim.ResourceAllocationInfo
$resSpec.memoryAllocation.reservation = $EntityMemoryAllocationXML.Reservation
$resSpec.memoryAllocation.expandableReservation = $EntityMemoryAllocationXML.expandableReservation
$resSpec.memoryAllocation.limit = $EntityMemoryAllocationXML.limit
$resSpec.memoryAllocation.shares = New-Object VMware.Vim.SharesInfo
$resSpec.memoryAllocation.shares.shares = $EntityMemoryAllocationXML.shares.shares
$resSpec.memoryAllocation.shares.level = $EntityMemoryAllocationXML.shares.level

$configSpec = New-Object VMware.Vim.VAppConfigSpec
$configSpec.InstanceUuid = $entity.Objuuid
$vmFolder = $Entity.DestinationObjectMoref


#(import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $data.OwnerMoref -and !$_.Objuuid})
#$ClusterResourcePool = (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $data.Objuuid -and !$_.Objuuid}).DestinationObjectMoref

$ClusterResourcePool = get-view -id (get-view -id (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $entity.OwnerMoref -and !$_.Objuuid}).DestinationObjectMoref -server $destinationVC).ResourcePool -Server $destinationVC

$CreatedVapp = get-view -id  $ClusterResourcePool.CreateVApp($entity.ObjectName, $resSpec, $configSpec, $vmFolder) -Server $destinationVC

if ( $CreatedVapp.vappconfig.InstanceUuid -ne $entity.Objuuid ) { Write-Error "We have failed to created vapp with the same uuid"}

#Moving vms into the vAPP
$VMsOldMorefs = $EntityConfig.Key|%{$_.toString()}
$OldVMs = import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? { $VMsOldMorefs -contains $_.vmmoref }
$newVMs = $oldVMs.Objuuid | % {get-view -viewtype virtualmachine -Filter @{'config.uuid'=$_} -Server $destinationVC}
$createdvapp.MoveIntoResourcePool($newVMs.moref)
#Let's make proper order in vapp

foreach ($entry in $EntityConfig)
{
$oldkey = (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.vmmoref -eq $entry.Key.ToString() }).Objuuid
$newkey = (get-view -viewtype virtualmachine -Filter @{'config.uuid'=$oldkey} -Server $destinationVC).moref
$entry.key=$newkey

}

$newconfig = new-object VMware.Vim.VAppConfigSpec
foreach ($entry in $EntityConfig)
{

$newEntityconfig =  new-object VMware.Vim.VAppEntityConfigInfo
$newEntityconfig.Key = $entry.key
$newEntityconfig.Tag = $entry.tag
$newEntityconfig.StartOrder = $entry.StartOrder
$newEntityconfig.StartDelay = $entry.StartDelay
$newEntityconfig.WaitingForGuest = $entry.WaitingForGuest
$newEntityconfig.StartAction = $entry.StartAction
$newEntityconfig.StopDelay = $entry.StopDelay
$newEntityconfig.StopAction = $entry.StopAction
$newEntityconfig.DestroyWithParent = $entry.DestroyWithParent

$newConfig.EntityConfig += $newEntityconfig

}

$CreatedVapp.UpdateVAppConfig($newConfig)
}
#we have now updated entityconfig

For the vapps part :

Foreach ($entity in (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.OriginObjectMoref -like "VirtualApp-resgroup-v*" -and $_.OwnerMoref})){
#entity is now
#ObjectName             : LABS_Greg
#OriginObjectMoref      : VirtualApp-resgroup-v241
#DestinationObjectMoref : Folder-group-v4284
#Objuuid                : 5038914a-df12-abcc-77aa-2d2991ccaa2e
#DestMorefDC            :
#vmtxpath               :
#vmtxHost               :
#OwnerMoref             : ClusterComputeResource-domain-c7

#First we prepare the configs for our Vapp entity
$EntityMemoryAllocationXML = Import-Clixml -LiteralPath ('C:\'+$data.Objuuid+'MemoryAllocation')
$EntityCpuAllocationXML = Import-Clixml -LiteralPath ('C:\'+$data.Objuuid+'CpuAllocation')
$EntityConfig = Import-Clixml -LiteralPath ('C:\'+$data.Objuuid+'EntityConfig')
$resSpec = New-Object VMware.Vim.ResourceConfigSpec
$resSpec.cpuAllocation = New-Object VMware.Vim.ResourceAllocationInfo
$resSpec.cpuAllocation.reservation = $EntityCpuAllocationXML.Reservation
$resSpec.cpuAllocation.expandableReservation = $EntityCpuAllocationXML.expandableReservation
$resSpec.cpuAllocation.limit = $EntityCpuAllocationXML.limit
$resSpec.cpuAllocation.shares = New-Object VMware.Vim.SharesInfo
$resSpec.cpuAllocation.shares.shares = $EntityCpuAllocationXML.shares.shares
$resSpec.cpuAllocation.shares.level = $EntityCpuAllocationXML.shares.level
$resSpec.memoryAllocation = New-Object VMware.Vim.ResourceAllocationInfo
$resSpec.memoryAllocation.reservation = $EntityMemoryAllocationXML.Reservation
$resSpec.memoryAllocation.expandableReservation = $EntityMemoryAllocationXML.expandableReservation
$resSpec.memoryAllocation.limit = $EntityMemoryAllocationXML.limit
$resSpec.memoryAllocation.shares = New-Object VMware.Vim.SharesInfo
$resSpec.memoryAllocation.shares.shares = $EntityMemoryAllocationXML.shares.shares
$resSpec.memoryAllocation.shares.level = $EntityMemoryAllocationXML.shares.level

$configSpec = New-Object VMware.Vim.VAppConfigSpec
$configSpec.InstanceUuid = $entity.Objuuid
$vmFolder = $Entity.DestinationObjectMoref


#(import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $data.OwnerMoref -and !$_.Objuuid})
#$ClusterResourcePool = (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $data.Objuuid -and !$_.Objuuid}).DestinationObjectMoref

$ClusterResourcePool = get-view -id (get-view -id (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8| ?{$_.OriginObjectMoref -eq $data.OwnerMoref -and !$_.Objuuid}).DestinationObjectMoref -server $destinationVC).ResourcePool -Server $destinationVC

$CreatedVapp = get-view -id  $ClusterResourcePool.CreateVApp($data.ObjectName, $resSpec, $configSpec, $vmFolder) -Server $destinationVC

if ( $CreatedVapp.vappconfig.InstanceUuid -ne $entity.Objuuid ) { Write-Error "We have failed to created vapp with the same uuid"}

#Moving vms into the vAPP
$VMsOldMorefs = $EntityConfig.Key|%{$_.toString()}
$OldVMs = import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? { $VMsOldMorefs -contains $_.vmmoref }
$newVMs = $oldVMs.Objuuid | % {get-view -viewtype virtualmachine -Filter @{'config.uuid'=$_} -Server $destinationVC}
$createdvapp.MoveIntoResourcePool($newVMs.moref)
#Let's make proper order in vapp

foreach ($entry in $EntityConfig)
{
$oldkey = (import-csv -LiteralPath C:\databasefile.csv -Encoding UTF8 | ? {$_.vmmoref -eq $entry.Key.ToString() }).Objuuid
$newkey = (get-view -viewtype virtualmachine -Filter @{'config.uuid'=$oldkey} -Server $destinationVC).moref
$entry.key=$newkey

}

$newconfig = new-object VMware.Vim.VAppConfigSpec
foreach ($entry in $EntityConfig)
{

$newEntityconfig =  new-object VMware.Vim.VAppEntityConfigInfo
$newEntityconfig.Key = $entry.key
$newEntityconfig.Tag = $entry.tag
$newEntityconfig.StartOrder = $entry.StartOrder
$newEntityconfig.StartDelay = $entry.StartDelay
$newEntityconfig.WaitingForGuest = $entry.WaitingForGuest
$newEntityconfig.StartAction = $entry.StartAction
$newEntityconfig.StopDelay = $entry.StopDelay
$newEntityconfig.StopAction = $entry.StopAction
$newEntityconfig.DestroyWithParent = $entry.DestroyWithParent

$newConfig.EntityConfig += $newEntityconfig

}

$CreatedVapp.UpdateVAppConfig($newConfig)
}
#we have now updated entityconfig

readd-permission

This is only usefull if you get into problems with VC, if everything is ok then powercli cmdlet is more than enough for managing permissions. I could not do it via powercli cmdlet because i was receving error (user already exists, which is sort of true, but that due to the ‘issue’ i had).
Kudos to William Lam LINK He was describing accessing other methods, really helpful article for what i had to do.
Via powershell you will be calling methods in the same way as you would do it via mob(via your web browser)
The way i did this particular one is that , first you would have to login to VC, then get permissions in some variable so , $perms=get-vipermission
Then you would call it readd-permission -permission $perms[4]
for example. if would transform the [domain]\username to [full.domain.name]\username and later on will add the permission on exactly the same object, in the same way as the permission you are sending was built. I also left 1 parameter if you want to edit on the fly the username , so with: -user ‘shortdomain\username’ you will be replacing the current user on the permission you sent to the function.
I don’t want to go too deep with the issue i had but, all in all i had issues with not being able to search entities (any kind, vm, network, datastore,host).

function readd-permission{
[CmdletBinding()]
param(
[parameter(Mandatory=$true)]
[VMware.VimAutomation.Types.PermissionManagement.Permission]
$permission,
$user,
$vcenter=$global:DefaultVIServer.name
)
$entity=$permission.EntityId
$principal=$permission.Principal
$isgroup=$permission.isgroup
if($user){$principal=$user}
$udomain=$principal.Split('\')[0]
$domain = (((([ADSI]"LDAP://$udomain").DistinguishedName).Split('DC=')).replace(',','') |?{$_}) -join '.'
$properusername=$principal.Split('\')[1]+'@'+$domain
$principal=[uri]::EscapeDataString($properusername)
[uri]::EscapeUriString($properusername)
$propagate=$permission.Propagate
$roleid=$permission.ExtensionData.RoleId
[regex]$pattern = '-'
$goodentity = [uri]::EscapeDataString($pattern.replace($entity,':',1))
$mob_url = "https://$vcenter/invsvc/mob3/?moid=authorizationService&method=AuthorizationService.AddAccessControlList"
$sessionnonce = (Invoke-WebRequest -Uri $mob_url -SessionVariable vmware -Credential $cred -Method GET).inputfields[0].value
$iuuid = $global:DefaultVIServer.InstanceUuid
$body = @"
vmware-session-nonce=$sessionnonce&docUri=urn%3Avmomi%3A$goodentity%3A$iuuid&permissions=%3Cpermissions%3E%0D%0A+++%3Cprincipal%3E%0D%0A++++++%3Cname%3E$principal%3C%2Fname%3E%0D%0A++++++%3Cgroup%3E$isgroup%3C%2Fgroup%3E%0D%0A+++%3C%2Fprincipal%3E%0D%0A+++%3Croles%3E$roleid%3C%2Froles%3E%0D%0A+++%3Cpropagate%3E$propagate%3C%2Fpropagate%3E%0D%0A+++%3Cversion%3E42%3C%2Fversion%3E%0D%0A%3C%2Fpermissions%3E
"@ 
Invoke-WebRequest -Uri $mob_url -WebSession $vmware -Method POST -Body $body
$body
$result = (get-view -id $entity).permission
return $result
}

before running this , you would already need the $cred variable prepared + ignore ssl issue

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    
    public class IDontCarePolicy : ICertificatePolicy {
        public IDontCarePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate cert,
            WebRequest wRequest, int certProb) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy 
$cred = get-credential

Clone-CustomAttributes using PowerCLI

There is nothing to explain i guess in this function. Just copies the definitions of custom attributes between 2 virtual center servers. It expects that you are connected to both virtual centers.

Function Clone-CustomAttributes 
{
<#
    .SYNOPSIS
        Copies custrom attributes used for annotations , just the definitions.
  
    .DESCRIPTION
        Copies custrom attributes used for annotations , just the definitions.
  
    .PARAMETER  sourceVC
        Specify the Virtual Center from which it will download the custom attributes.

    .PARAMETER  destinationVC
        Specify the Virtual Center to which it will apply the custom attribues.
          
    .PARAMETER  TargeType
        Specify for which kind of attributes this list will be generated: VirtualMachine,ResourcePool, 
        Folder,VMHost,Cluster,Datacenter. Global is not included in this version.

    .EXAMPLE
        PS C:\> Clone-CustomAttributes -sourceVC 'VC01.biz' -destinationVC 'vc02.biz' -TargetType 'VirtualMachine'
        Will create the custom attribute definitions for type VirtualMachine which belong to VC01 on VC02.

    .NOTES
        NAME:  Export-CustomAttributes
          
        AUTHOR: Grzegorz Kulikowski
          
        NOT WORKING ? #powercli @ irc.freenode.net 
          
    .LINK
  
https://psvmware.wordpress.com
  
#>
param(
[Parameter(Mandatory=$true)]$sourceVC, 
[Parameter(Mandatory=$true)]$destinationVC, 
[Parameter(Mandatory=$true)][VMware.VimAutomation.ViCore.Types.V1.AnnotationManagement.CustomAttributeTargetType]$targetType

) 
    $SourceCustomAttr = @{}
    #I have special filter not to much some names, as i do not wan't them on my new VC Instance.
    Get-CustomAttribute -Server $sourceVC -TargetType $targetType  | ? {$_.Name -notmatch "PnC|vrm|FA.|Xd"} | % { $SourceCustomAttr+=@{$_.Key=$_.Name}}
    Foreach ($CustomAttribute in $SourceCustomAttr.GetEnumerator()) 
    {
        New-CustomAttribute -Name $CustomAttribute.Value -TargetType $targetType -Server $destinationVC
    }
}

Export-CustomAttributes using PowerCLI

Ok , exporting values of custom attributes , in other words our custom annotations for vms.
When running with specific -Attribute parameter :

When running without the -Attribute parameter it will grab all annotations for the specific target type (VirtualMachine,ResourcePool, Folder,VMHost,Cluster,Datacenter).

I have not implemented the ‘global’ target type here. Might be the case that i will do it later on.
The idea behind is to save the report to a file , and then with the import function , apply to vms that were imported to the new VC.

Function Export-CustomAttributes
{
<#
    .SYNOPSIS
        Returns VM report with custom attributes for vms that have currently custom attributes applied.
  
    .DESCRIPTION
        Returns VM report with custom attributes for vms that have currently custom attributes applied.
        Can be ran with the -Attribute parameter to specify which exactly attributes should be recorded.
        Cmdlet expects that we are already connected to a specified virtual center system. The sourceVC
        parameter is needed to distinguish between VC if you are connected to more than 1 VC. It also 
        used as the identificator of VC connection if you are connected to a single VC instance.
  
    .PARAMETER  sourceVC
        Specify the Virtual Center from which it will download the report.
          
    .PARAMETER  TargeType
        Specify for which kind of attributes this list will be generated: VirtualMachine,ResourcePool, 
        Folder,VMHost,Cluster,Datacenter. Global is not included in this version.

    .PARAMETER  Attribute
        Specify for which attributes this list will be generated, you can check which one you have by 
        running get-customattributes cmdlet. Attributes inside the specific TargetType only.
 
    .EXAMPLE
        PS C:\> $CA = Export-CustomAttributes -sourceVC 'VC004.domain.biz' -targetType 'virtualmachine' -Attribute 'ApplicationOwner','Function'
        Will get 2 custom attribute for all virtualmachine that have currently customattributes

    .EXAMPLE
        PS C:\> $CA = Export-CustomAttributes -sourceVC 'VC004.domain.biz' -targetType 'virtualmachine'
        Will get all custom attributes from virtualmachine type for all virtualmachine that have currently customattributes
         

    .NOTES
        NAME:  Export-CustomAttributes
          
        AUTHOR: Grzegorz Kulikowski
          
        NOT WORKING ? #powercli @ irc.freenode.net 
          
    .LINK
  
https://psvmware.wordpress.com
  
#>
param(
[Parameter(Mandatory=$true)][string]$sourceVC, 
[Parameter(Mandatory=$true)][VMware.VimAutomation.ViCore.Types.V1.AnnotationManagement.CustomAttributeTargetType]$targetType, 
[string[]]$Attribute
)
#▅▇█▓▒░Don't forget to implement the global option as per :http://pubs.vmware.com/vsphere-60/index.jsp#com.vmware.wssdk.apiref.doc/vim.CustomFieldsManager.FieldDef.html
#▅▇█▓▒░Right now the $targetType can't be null, so we can't take 'globals' , globals are the ones which are empty.
    
    $SourceCustomAttr = @{}
    if ($Attribute) 
    {
        Get-CustomAttribute -Server $sourceVC -TargetType $targetType -Name $Attribute | % { $SourceCustomAttr+=@{$_.Key=$_.Name}}
    } else 
        {
            #This is custom to the environment, depending on which plugins you were installing to your VC, you might have different special attributes, which might not be needed on the other side.
            Get-CustomAttribute -Server $sourceVC -TargetType $targetType  | ? {$_.Name -notmatch "PnC|vrm|FA.|Xd"} | % { $SourceCustomAttr+=@{$_.Key=$_.Name}}
        }
    #get only those that have custom attributes     
    $SourceVms = Get-View -ViewType virtualmachine -Property 'CustomValue','Name' -Server $sourceVC | ?{$_.customvalue}
    $ReportSourceVms = $SourceVms | Select Moref,Name,CustomValue
    
    Foreach ($VM in $ReportSourceVms) 
    {
        foreach ($CustomAttribute in $SourceCustomAttr.GetEnumerator()) 
        {
            Add-Member -InputObject $VM -MemberType NoteProperty -Name $CustomAttribute.Value -Value ($VM.CustomValue|?{$_.Key -eq $CustomAttribute.Name}).value
        }
    }
    return $ReportSourceVms | Select-Object * -ExcludeProperty CustomValue
} 

Get-ESXiMemoryDimms

I had to get some info about host memory dimms layout, so i wrote this one.
It is utilizing CIM_PhysicalMemory. Not sure if i haven’t written it before, but i couldn’t find it on my disk so…
Here it is.

Function Get-ESXiMemoryDimms {
<#
    .SYNOPSIS
        Returns memory dimms configuration for esxi
  
    .DESCRIPTION
        This function utilizes wsman / cim in order to download configuration of memory dims in ESXi.
  
    .PARAMETER  esxi
        Specify esxi host for which you want to get the report
          
    .PARAMETER  rootpw
        Password for user root inside esxi
 
    .EXAMPLE
        PS C:\> Get-ESXiMemoryDimms -Esxi 'Esxi048.domain.local' -rootpw 'password.123' | ft *
        BankLabel               Manufacturer Description SizeGB MemoryType MemoryDef
        ---------               ------------ ----------- ------ ---------- ---------
        P0_Node0_Channel0_Dimm0 Samsung      P1-DIMMA1       16 24         DDR3
        P0_Node0_Channel0_Dimm1 Samsung      P1-DIMMA2       16 24         DDR3
        P0_Node0_Channel1_Dimm0 Samsung      P1-DIMMB1       16 24         DDR3
        P0_Node0_Channel1_Dimm1 Samsung      P1-DIMMB2       16 24         DDR3
        P0_Node0_Channel2_Dimm0 Samsung      P1-DIMMC1       16 24         DDR3
        P1_Node1_Channel2_Dimm0 Samsung      P2-DIMMG1       16 24         DDR3
        P1_Node1_Channel2_Dimm1 Samsung      P2-DIMMG2       16 24         DDR3
        P1_Node1_Channel3_Dimm0 Samsung      P2-DIMMH1       16 24         DDR3
        P1_Node1_Channel3_Dimm1 Samsung      P2-DIMMH2       16 24         DDR3
                                Winbond                  ...625 11         Flash
         

    .NOTES
        NAME:  Get-ESXiMemoryDimms
          
        AUTHOR: Grzegorz Kulikowski
          
        NOT WORKING ? #powercli @ irc.freenode.net 
          
    .LINK
  
https://psvmware.wordpress.com
  
#>
param([String]$Esxi,[string]$rootpw)

#MemoryTypes from: https://msdn.microsoft.com/en-us/library/aa394347(v=vs.85).aspx
$MemHash = @{
'0'='Unknown';
'1'='Other';
'2'='DRAM';
'3'='Synchronous DRAM';
'4'='Cache DRAM';
'5'='EDO';
'6'='EDRAM';
'7'='VRAM';
'8'='SRAM';
'9'='RAM';
'10'='ROM';
'11'='Flash';
'12'='EEPROM';
'13'='FEPROM';
'14'='EPROM';
'15'='CDRAM';
'16'='3DRAM';
'17'='SDRAM';
'18'='SGRAM';
'19'='RDRAM';
'20'='DDR';
'21'='DDR2';
'22'='DDR2 FB-DIMM';
'23'='DDR2 FB-DIMM';
'24'='DDR3';
'25'='FBD2'
}
$pwd = ConvertTo-SecureString $rootpw -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential (“root”, $pwd)
$CIMOpt = New-CimSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck -Encoding Utf8 –UseSsl
$Session = New-CimSession -Authentication Basic -Credential $cred -ComputerName $esxi -port 443 -SessionOption $CIMOpt
Get-CimInstance -CimSession $Session CIM_PhysicalMemory | select BankLabel, Manufacturer, Description , @{n='SizeGB';e={$_.Capacity/1GB}}, MemoryType, @{n='MemoryDef';e={$MemHash[$_.MemoryType]}}
}