The following will add the VM ($vmName) to a specific port mirroring session ($mirrorSessionName) on a distributed switch ($dvSwName).
You can define the traffic direction(s) for which the VM needs to be added with the variables $Ingress and $Egress.
Note that there isn't any error checking in the script.
For example if the mirror session does not exist, the script will fail without an informative messages.
To repeat this script for all VMs in a specific folder should be not too difficult, I assume ?
$dvSwName = 'dvSw1'
$mirrorSessionName = 'Test'
$vmName = 'VM2'
$Ingress = $false
$Egress = $true
$dvSw = Get-VDSwitch -Name $dvSwName
$vm = Get-VM -Name $vmName
$vmNic = $vm.ExtensionData.Config.Hardware.Device |
where{$_.Backing -is [VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo]}
$spec = New-Object VMware.Vim.VMwareDVSConfigSpec
foreach($mirrorSession in $dvSw.ExtensionData.Config.VspanSession){
if($mirrorSession.Name -eq $mirrorSessionName){
$vspan = New-Object VMware.Vim.VMwareDVSVspanConfigSpec
$vspan.Operation = [VMware.Vim.ConfigSpecOperation]::edit
$vmInRc = $mirrorSession.SourcePortReceived | where{$_.PortKey -contains $vmNic.Backing.Port.PortKey}
if($Ingress -and !$vmInRc){
$mirrorSession.SourcePortReceived.PortKey += $vmNic.Backing.Port.PortKey
}
$vmInTx = $mirrorSession.SourcePortTRansmitted | where{$_.PortKey -contains $vmNic.Backing.Port.PortKey}
if($Egress -and !$vmInTx){
$mirrorSession.SourcePortTransmitted.PortKey += $vmNic.Backing.Port.PortKey
}
$vspan.vspanSession = $mirrorSession
$spec.vspanConfigSpec += $vspan
}
}
$spec.ConfigVersion = $dvSw.ExtensionData.Config.ConfigVersion
$dvSw.ExtensionData.ReconfigureDvs($spec)