Ultimate Cross vCenter Script

Last year i attend the Dutch VMUG (NLVMUG) i followed session from

Michael Wilmsen that was: Migrate your datacenter without downtime.

I must also move al lot of VM’s from different datacenters to other datacenters.
I use the script from Michael Wilmsen to move the VM’s. But along the way I counter some problems with this script. So I begon tweaking and tweaking and tweaking this script to create for me the ultimate Cross vCenter PowerCLI Script.

Coolfeatures:
– Info through Whattsapp (Default not enabled)
– Dryrun (Test Run)
– Logging
– Selection through GUI
– Multiple Nic support maximum of 4.
– Datastore en Host selection based on Free space en Free Memory
– Check of Destination Host or Datastore in Maintance
– Destination Store exist in Destination Cluster

MoveVM.ps1:
#Filename: MoveVM.ps1
#Author: M. Wilmsen / W. Vissers
#Source: http://virtual-hike.com/nlvmug-2018/
#Version: 2.0
#Date: 21-10-2018
#ChangeLog:
# V0.9 – M. Wilmsen First Version
# V1.0 – Fixed Multiple Nics to maximium of 4 nics
#      – Logfile name VM name
# V1.1 – Destination Cluster not the first Host
# V1.2 – Selected Destination host based on memory used
# V1.3 – Fixed folder location and VirtualPortGroup
# V1.4 – Fixed Datastore in Maintance
# V1.5 – Using Get-VICredentialStoreItem + Logpath Fixt
# V1.6 – Fixed Log in Hours in 24 uurs
# V1.7 – Fixed Using DatastoreCluster name based on Cluster name!
# V1.8 – Check if Destination has the same datastore
#          – Ask know for input
#          – VM selection with VMhost
#          – Fixed Ping Check
# v1.9 – Added Destination Store exist in Destination Cluster
# v2.0 – Fixed Destination Store exist in Destination Cluster
<#
.SYNOPSIS
Script to migrate a virtual machine
.DESCRIPTION
Script to migrate compute and storage from cluster to cluster. Log will be in current dir [VM]-[-timestamp].log

.EXAMPLE
MoveVM.ps1
#>
################################## INIT #################################################
#Set WebOperation timeout
# set-PowerCLIConfiguration -WebOperationTimeoutSeconds 3600
#Define Global variables
$location = “D:\xmovewhattsapp”
$LogPath = “.\”
$DataStoreClusterPrefix = “SAN-“
$SourceVC = Read-Host “Give Source vCenter”
$DestinationVC = Read-Host “Give Destination vCenter”
$DRSRecommendation = $true
$Dryrun = $false
$SendWhatsApp = $false
$WhatsAppNumbers = “0123456789”
$WhatsAppGroup = “Namehireyourwhattsgroup”
$instanceId = “23” #chang this line
$clientId = “demo@demo.nl” #change this line
$clientSecret = “Puthiersecretid” #change this line
################################## PASSWORD STORE ##############################################
#Username
# Check if credentials exist in credential store if not ask for credentials and put them in credential store

If ((Get-VICredentialStoreItem).host -notcontains $SourceVC) {New-VICredentialStoreItem -Host $SourceVC -User $env:USERNAME -Password ((get-credential).GetNetworkCredential().Password)}
If ((Get-VICredentialStoreItem).host -notcontains $DestinationVC) {New-VICredentialStoreItem -Host $DestinationVC -User $env:USERNAME -Password ((get-credential).GetNetworkCredential().Password)}

# Remove-VICredentialStoreItem * -Confirm:$false

################################## END INIT #################################################
################################## FUNCTIONS #################################################
#Define log function
Function LogWrite
{
    Param ([string]$logstring)
    #Add logtime to entry
    $LogTime = Get-Date -Format “MM-dd-yyyy_HH-mm-ss”
    $logstring = $LogTime + ” : ” + $logstring
    #Write logstring
    Add-content $LogFile -value $logstring
    Write-Host $logstring
}
#Define SendWhatsApp function
Function SendWhatsApp
{
   Param ([string] $message)
  
   if ( $SendWhatsApp ) {
     $LogTime = Get-Date -Format “MM-dd-yyyy_hh-mm-ss”
     $message = $logtime + ” : ” + $message
    
     foreach ( $number in $WhatsAppNumbers )
     {
        $jsonObj = @{‘group_admin’=$number;
                     ‘group_name’=$WhatsAppGroup;
                     ‘message’=$message;}
       Try {
         $res = Invoke-WebRequest -Uri “http://api.whatsmate.net/v2/whatsapp/group/message/$instanceId” `
                           -Method Post   `
                           -Headers @{“X-WM-CLIENT-ID”=$clientId; “X-WM-CLIENT-SECRET”=$clientSecret;} `
                           -Body (ConvertTo-Json $jsonObj)
         LogWrite “WhatsMate Status Code: ”  $res.StatusCode
         LogWrite $res.Content
       }
       Catch {
         $result = $_.Exception.Response.GetResponseStream()
         $reader = New-Object System.IO.StreamReader($result)
         $reader.BaseStream.Position = 0
         $reader.DiscardBufferedData()
         $responseBody = $reader.ReadToEnd();

        Write-host “Status Code: ” $_.Exception.Response.StatusCode
         Write-host $message
         }
     }
   }
}

function Get-VmSize($vm)
{
     #Initialize variables
     $VmDirs =@()
     $VmSize = 0
     $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
     $searchSpec.details = New-Object VMware.Vim.FileQueryFlags
     $searchSpec.details.fileSize = $TRUE
     Get-View -VIObject $vm | % {
         #Create an array with the vm’s directories
         $VmDirs += $_.Config.Files.VmPathName.split(“/”)[0]
         $VmDirs += $_.Config.Files.SnapshotDirectory.split(“/”)[0]
         $VmDirs += $_.Config.Files.SuspendDirectory.split(“/”)[0]
         $VmDirs += $_.Config.Files.LogDirectory.split(“/”)[0]
         #Add directories of the vm’s virtual disk files
         foreach ($disk in $_.Layout.Disk) {
             foreach ($diskfile in $disk.diskfile){
                 $VmDirs += $diskfile.split(“/”)[0]
             }
         }
         #Only take unique array items
         $VmDirs = $VmDirs | Sort | Get-Unique
         foreach ($dir in $VmDirs){
             $ds = Get-Datastore ($dir.split(“[“)[1]).split(“]”)[0]
             $dsb = Get-View (($ds | get-view).Browser)
             $taskMoRef  = $dsb.SearchDatastoreSubFolders_Task($dir,$searchSpec)
             $task = Get-View $taskMoRef
             while($task.Info.State -eq “running” -or $task.Info.State -eq “queued”){$task = Get-View $taskMoRef }
             foreach ($result in $task.Info.Result){
                 foreach ($file in $result.File){
                     $VmSize += $file.FileSize
                 }
             }
         }
     }
     return $VmSize
}
################################## END FUNCTIONS #################################################
#Login to vCenter servers
if (($global:DefaultVIServers).Name -notcontains $SourceVC -or $DestinationVC) {

#SourceVC
$ConnectVC = Connect-VIServer $SourceVC
$Message = “Connecting to ” + $ConnectVC  + ” as ” + $env:USERNAME
#Logwrite $Message
#DestionationVC
$ConnectVC = Connect-VIServer $DestinationVC
$Message = “Connecting ” + $ConnectVC + ” as ” + $env:USERNAME
#Logwrite $Message

# Disconnect-VIServer * -Confirm:$false

}
Set-Location $location

$cluster=Get-Cluster -Server $SourceVC  | Out-GridView -OutputMode Single -Title “Select Source Cluster”
$vmtomigrate =Get-Cluster $cluster -Server $SourceVC | Get-VM | Out-GridView -OutputMode Single -Title “Select VM”
$DestinationCluster = Get-Cluster -Server $DestinationVC | Out-GridView -OutputMode Single -Title “Select Destination Cluster”
$vmfolder=Get-folder -Server $DestinationVC | Out-GridView -OutputMode Single -Title “Select Folder”

#Main Script

    #Set $MigError to false befor migration
     $MigError = $false
     #Get VM variables
     $vm = get-vm $vmtomigrate
    
     #Define LogFile with time stamp
     $LogTime = Get-Date -Format “MM-dd-yyyy_hh-mm-ss”
    
     if([IO.Directory]::Exists($LogPath))
     {
     #Do Nothing!!
     }
     else
     {
     New-Item -ItemType directory -Path $LogPath
     }
     $LogFile = $LogPath+$VM+”-“+$LogTime+”.log”
    
     # LogWrite Gebruiker
    
     Logwrite $env:USERNAME

    # Get-VM Info   
    
     $VMHDDSize = Get-VmSize($vm)
     $VMHDDSize = [Math]::Round(($VMHDDSize / 1GB),2)

    Logwrite “Start Virtual Machine Move”
     #If WhatsApp make notice
     if ( $SendWhatsApp ) { LogWrite “Notifications will be send using WhatsApp to WhatsApp Group: $WhatsAppGroup” }
     #If DryRun make Notice
     if ( $Dryrun ) {
     Logwrite “Start move virtual machines $vm Disksize $VMHDDSize GB (DryRun)”
     SendWhatsApp “Start move virtual machines $vm Disksize $VMHDDSize GB(DryRun)”
     }
     else {
     Logwrite “Start move virtual machines $vm Disksize $VMHDDSize GB”
     SendWhatsApp “Start move virtual machines $vm Disksize $VMHDDSize GB”
     }
     $SourceCluster = get-vm $vm | Get-Cluster | select name
     $vmip = $vm  | Select @{N=”IP Address”;E={@($_.guest.IPAddress[0])}}
     $vmip = $vmip.”ip address”
     $VMHDDSize = Get-VmSize($vm)
     $VMHDDSize = [Math]::Round(($VMHDDSize / 1GB),2)
     $NetworkAdapter = Get-NetworkAdapter -VM $vm -Server $SourceVC
     $SourceVMPortGroup = Get-NetworkAdapter -vm $vm | Select NetworkName
     $switchname = $DestinationCluster
    

     $Datastore = Get-VM $vm | Get-DataStore -Server $sourceVC | Select @{N=”Name”;E={@($_.Name)}}
     $Datastore = $Datastore.Name
     $DatastoreExistinOthervCenter = Get-Cluster $DestinationCluster | Get-DataStore -Server $DestinationVC | ? {$_.Name -like “*$Datastore*”}

     if ($DatastoreExistinOthervCenter )
      {
      LogWrite  “Datastore exsist $DestinationCluster in  destination vCenter $DestinationVC “
      $destinationDatastore = $DatastoreExistinOthervCenter }
      Else
      {
      LogWrite  “Datastore does not exsist in $DestinationCluster destination vCenter $DestinationVC”
      # Select DataStore with the most free space and not in maintance
      $DatastoreCluster = “$DataStoreClusterPrefix”+”$DestinationCluster”
      $destinationDatastore = Get-DatastoreCluster $DatastoreCluster | Get-Datastore | Where {$_.State -ne “Maintenance”} | Sort-Object -Property FreeSpaceGB -Descending | Select-Object -First 1
      }

     $destinationDatastoreFreeSpace = $destinationDatastore | Select Name,@{N=”FreeSpace”;E={$_.ExtensionData.Summary.FreeSpace}}
      $destinationDatastoreFreeSpace = [Math]::Round(($destinationDatastoreFreeSpace.”FreeSpace” / 1GB),2)

    # Select the host with the less used memory
   
     $DestinationHost = Get-Cluster –Name $DestinationCluster –Server $DestinationVC | Get-VMhost -State Connected | Sort-Object -Property MemoryUsageGB | Select-Object -First 1
            
     # Change Here if you have a vm with multiple Network Cards (Remove the # for the multiple nics)
    
     if ($NetworkAdapter.Count-eq 1) {
         $DestinationVMPortgroup =@()
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic1”
      }
     elseif ($NetworkAdapter.Count-eq 2) {
         $DestinationVMPortgroup =@()
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic1”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic2”
     }
     elseif ($NetworkAdapter.Count-eq 3) {
         $DestinationVMPortgroup =@()
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic1”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic2”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic3”
     }
     elseif ($NetworkAdapter.Count-eq 4) {
         $DestinationVMPortgroup =@()
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic1”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic2”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic3”
         $DestinationVMPortgroup += Get-VirtualPortGroup -Server $DestinationVC -Vmhost $DestinationHost | Out-GridView -OutputMode Single -Title “Select Nic4”
     }

    LogWrite “Start move: $vm”
     Logwrite “VM IP: $vmip”
     Logwrite “VM Disk Used (GB): $VMHDDSize”
     Logwrite “VM Folder: $vmfolder”
     Logwrite “Source vCenter: $SourceVC”
     Logwrite “VM Source Cluster: $SourceCluster”
     Logwrite “Destination vCenter: $DestinationVC”
     Logwrite “VM Destination Cluster: $DestinationCluster”
     Logwrite “Destination host: $DestinationHost”
     LogWrite “VM Source PortGroup: $SourceVMPortGroup”
     LogWrite “VM Destination Portgroup: $DestinationVMPortgroup”
     Logwrite “VM Destination Datastore: $destinationDatastore”
     LogWrite “Destination Datastore FreeSpace GB: $destinationDatastoreFreeSpace “
     if ( $Dryrun ) {
       $FreespaceAfterMigration = $destinationDatastoreFreeSpace – $VMHDDSize
       if ( $FreespaceAfterMigration -lt 0 ) { Logwrite “ERROR: Datastore $destinationDatastore does not have sufficient freespace! Virtual Machine needs $VMHDDSize. Only $destinationDatastoreFreeSpace available.” }
       else { Logwrite “Virtual Machine will fit on datastore $destinationDatastore. Freespace after migration is: $FreespaceAfterMigration GB” }
     }
    #Test if VM responsed to ping
    if ($vmip -eq $null) {
     LogWrite “Virtual Machine ip address not known”
     Logwrite “No ping check will be performed after moving the Virtual Machine”
     }
    else {
         Test-Connection -comp $vmip -quiet
         LogWrite “Virtual Machine $vm response to ping before being moved. Virtual machine will be checked after being moved”
         $PingVM = $true
     }
      
     #if ( $VMHDDSize -eq
     if ( -NOT $Dryrun) {
       #Migrate VM to cluster
       LogWrite “Move $vm to vCenter $DestinationVC and datastore $DestinationDatastore”
       Try {
         $Result = Move-VM -VM $vm `
                            -Destination $DestinationHost `
                            -Datastore $DestinationDatastore `
                            -NetworkAdapter $NetworkAdapter `
                            -PortGroup $DestinationVMPortgroup `
                            -ErrorAction Stop
           }
       Catch {
         $ErrorMessage = $_.Exception.Message
         LogWrite “ERROR: Move of $vm to cluster $DestinationHost failed!!!”
         Logwrite “ERROR: Move Status Code:  $ErrorMessage”
         SendWhatsApp “ERROR: Move of $vm failed!!! $ErrorMessage”
         $MigError = $true   
       }
       #Migrate VM to folder
       LogWrite “Move $vm to vCenter $vmfolder”
       Try {
         $VMtemp = get-vm $vm
         $Result = Move-VM -VM $vmtemp -InventoryLocation $vmfolder -ErrorAction Stop
           }
       Catch {
         $ErrorMessage = $_.Exception.Message
         LogWrite “ERROR: Move of $vm to folder $vmfolder failed!!!”
         Logwrite “ERROR: Move Status Code:  $ErrorMessage”
         SendWhatsApp “ERROR: Move of $vm failed!!! $ErrorMessage”
         $MigError = $true   
         }
       }
    
     $MigError = $false
     #Test if VM is running on destination cluster
     if ( -NOT $MigError -AND -NOT $Dryrun ) {
       LogWrite “Check $vm is registered in $DestinationVC”
       try {
         $CheckVM = get-vm -name $vm -server $DestinationVC -ErrorAction Stop
 
         if ( $CheckVM ) {
           Logwrite “$vm registered in $DestinationVC”
         }
         else {
           Logwrite “ERROR: $vm not found in $DestinationVC”
         }
       }
       catch {
         $ErrorMessage = $_.Exception.Message
         Logwrite “ERROR: $vm not found in $DestinationVC”
         Logwrite “ERROR: $ErrorMessage”
         SendWhatsApp “ERROR move: $vm not found in $DestinationVC”
       }
     }
     #Test is VM response to ping, if $PingVM = $True
     if ($PingVM) {
       if (Test-Connection -comp $vmip -quiet) {
         LogWrite “Virtual Machine $vm response to ping after move”
         SendWhatsApp “Virtual Machine $vm response to ping after move”
       } 
     }
     sleep 1
     SendWhatsApp “Finished move action: $vm from $SourceVC to $DestinationVC”
     Logwrite “Finished move action: $vm from $SourceVC to $DestinationVC”

if ($DRSRecommendation)
  {
   Get-DrsRecommendation -Cluster $DestinationCluster -Server $DestinationVC | Apply-DrsRecommendation
   Logwrite “DRS Recommendatation applyed”
  }
Else
  {
  Logwrite “No DRS Recommendatation applyed”
  Write-Host “No DRS Recommendatation applyed”
  }  
 

#Disconnect from vCenter servers
Logwrite “Disconnect from vCenter servers $SourceVC $DestinationVC”
Disconnect-viserver $SourceVC -Confirm:$false
Disconnect-viserver $DestinationVC -Confirm:$false
Logwrite “Finished moving virtual machines, exiting…..”
SendWhatsApp “Finished moving virtual machines, exiting…..”

PowerCLI Move All VM’s to other Host

################### Config ##################################

$SourceVC = “vcenter.wardvissers.nl

################## PASSWORD STORE #########################

#Username

# Check if credentials exist in credential store if not ask for credentials and put them in credential store

 

If ((Get-VICredentialStoreItem).host -notcontains $SourceVC) {New-VICredentialStoreItem -Host $SourceVC -User $env:USERNAME -Password ((get-credential).GetNetworkCredential().Password)}

 

# Remove-VICredentialStoreItem * -Confirm:$false

 

#################### END INIT ####################################

 

#Login to vCenter servers

if (($global:DefaultVIServers).Name -notcontains $SourceVC) {

 

#SourceVC

$ConnectVC = Connect-VIServer $SourceVC

 

# Get-Cluster –Name $DestinationCluster –Server $DestinationVC | Get-VMhost -State Connected | Sort-Object -Property MemoryUsageGB | Select-Object -First 1

 

$ESXiHostSrc = “esx01.wardvissers.nl”

$ESXiHostDst = “esx02.wardvissers.nl”

$vmList = Get-VMHost $ESXiHostSrc | Get-VM

$vmList | move-vm -destination (get-vmhost $ESXiHostDst)

}

Deploy Multi VM’s based on Windows Template

I love powershell. I created a little script to deploy multi VM based on a Windows Template throug CSV file.

It’s create a computer account at the specfified ou. He greates also a Domain Local Group for management. (It used in the customization not specified here)

TempVMlist.csv

server,cpu,memory,DestinationCluster,OSCustomizationSpec,VMtemplate,adgroup

WARDTEST01,2,8,CLUSTER01,W2012R2_Demo,TPL_W2012R2_STD,ServerAdmin

MultiVM.ps1

#Filename: MultiVM.ps1

#Author: W. Vissers

#Source:

#Version: 1.1

#Date: 08-05-2018

#ChangeLog:

# V1.0 – Module Active Directory

#      – Module VMware PowerCli

#      – Active Directory Computer Account, Group

#      – Host Selected from Cluster with Least Memory

#      – Storage selection based on volume with most free space

# V1.1 – Added Harddisk 1&2

#      – Changed porte group other vlan

#

<#

.SYNOPSIS

Script to create a virtual machine from template

.DESCRIPTION

Script to create a virtual machine from template

.EXAMPLE

MultiVM.ps1

#>

################################## INIT #################################################

# LoadModule Active Directory

if (!(Get-Module “activedirectory”)) {Import-module activedirectory}

Else {Write-Host “Module Active Directory is al ready loaded”}

# LoadModule VMware PowerCLI

# if (!(Get-Module “VMware.PowerCLI”)) {

#    Find-Module VMware.PowerCLI

#    Install-Module -Name VMware.PowerCLI -Scope CurrentUser

#}

#Else

# {

# Write-Host “Module PowerCLI is al ready loaded”

# }

#Config

$ouservers=”OU=Servers,DC=wardvissers.nl,DC=nl”

$ougroup=”OU=GroepObjecten,DC=wardvissers,DC=nl”

$folder=”Applicatie Servers”

$DestinationVC =”vcenter01.wardvissers.nl

#Username

if (!$username ) { $username = Read-Host “Give vCenter username ‘wardvissers\admin'”}

#Password

if ( -NOT $Password ) {

$PasswordSec = Read-Host “Give vCenter password” -AsSecureString

$Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($PasswordSec))

}

#Connect vCenter

$ConnectVC = Connect-VIServer $DestinationVC -Username $Username -Password $Password -AllLinked

$AllVMs = @()

$AllVMs = Import-Csv “D:\TempVMlist.csv”

foreach ($vm in $AllVMs) {

#Haal De Gegevens op

$server=$($vm.server)

$memory=$($vm.memory)

$cpu=$($vm.cpu)

$DestinationCluster=$($vm.DestinationCluster)

$OSSpec=”$($vm.OSCustomizationSpec)”

$VMtemplate=$($vm.VMtemplate)

$group=$($vm.adgroup)

$harddisk1=$($vm.harddisk1)

$harddisk2=$($vm.harddisk2)

Write-Host “$server heeft $memory GB memory en $cpu cpu(‘s)”

if ($server.length -gt 15) {

Write-Output “Hostname cannot contain more than 15 characters.”

$server = Read-Host “Re-enter hostname for host $server”}

Else

{

Write-Host “Server is umc server”

#Maak AD Groep aan en Computer Account

New-ADComputer -Name $server -Path $ouservers -Enabled $true

New-ADGroup -Name “DLG.$server” -SamAccountName “DLG.$server” -GroupCategory Security -GroupScope DomainLocal -DisplayName “DLG.$server” -Path $ougroup

Add-ADGroupMember -Identity “DLG.$server” -Members $group

}

# Rol server uit van Template

# Select the host with the less used memory

$DestinationHost = Get-Cluster –Name $DestinationCluster –Server $DestinationVC | Get-VMhost -State Connected | Sort-Object -Property MemoryUsageGB | Select-Object -First1

# Select DataStore with the most free space and not in maintance

$destinationDatastore = Get-Cluster $DestinationCluster | Get-Datastore | Where {$_.State -ne “Maintenance”} | Sort-Object -Property FreeSpaceGB -Descending | Select-Object -First 1

# Finally, I deploy my VM with the New-VM cmdlet using my template and OS specs. I place the VM on the ESXi host and store the VM on the datastore.

New-VM -Name $server -Template $VMTemplate -OSCustomizationSpec $OSSpec -VMHost $DestinationHOST -Datastore $DestinationDatastore -Location $folder

Get-VM $server | Set-VM -NumCpu $cpu -MemoryGB $memory -Confirm:$false

if ($harddisk1 -gt 60){Get-HardDisk -vm $server | Where {$_.Name -eq “Hard disk 1”} | Set-HardDisk -CapacityGB $harddisk1 -Confirm:$false}

if ($harddisk2 -gt 20) {Get-HardDisk -vm $server | Where {$_.Name -eq “Hard disk 2”} | Set-HardDisk -CapacityGB $harddisk2 -Confirm:$false}

Get-VM $server | Start-VM -Confirm:$false

Get-VM $Server | Get-NetworkAdapter | Set-NetworkAdapter -Connected $true -Confirm:$false

}

VMware Disk to Windows Disk Script

vCenter01

Credentials

ClusterNode

virtuelemachine

DiskInfo

Script: VMwareDisktoWindows.ps1

# VMware to Windows Disk Script                                    
#                                                                                                   
# Author     : Ward Vissers                                                                                
# created on : 08-11-2017                                                                                  
# version    : V1.0                                                                                         
# Source     : http://www.enterprisedaddy.com/2016/07/powercli-match-windows-disk-to-vmware-harddisk/  
#
# V0.1 Testing
# V0.2 Line 33 $vm to $vm.name(Bug Found)
# V0.3 Graphical Version Select VM
# V0.4 Add Select VM from Cluster
# V1.0 Add Selection of multiple vCenter                                                                                                      
#
# $VCServerList is a comma-separated list of vCenter servers
$VCServerList = “vCenter01.wardvissers.nl”
# Select vCenter
$VCServer = $VCServerList | Out-GridView -Title “Select vCenter Server” -OutputMode Single
# write-host $VCServer
$Cred = Get-Credential
# Write-Host $Cred
 
# Set Default Server Mode to Multiple
Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Confirm:$false | Out-Null
# Connect to vCenter Server(s)
Connect-VIServer -Server “$VCServer” | Out-Null
$DiskInfo= @()
# Select Cluster
$Cluster = Get-Cluster | Out-GridView -Title “Select Target Cluster Node” -OutputMode Single
# write-host $Cluster
# Select VM From Cluster
$Vm = Get-Cluster $Cluster | Get-VM | Out-GridView -Title “Select Virtuele Machine” -OutputMode Single
# write-host $vm

if (($VmView = Get-View -ViewType VirtualMachine -Filter @{“Name” = $Vm.Name})) {
  $WinDisks = Get-WmiObject -Class Win32_DiskDrive -Credential $Cred -ComputerName $VmView.Name
  foreach ($VirtualSCSIController in ($VMView.Config.Hardware.Device | where {$_.DeviceInfo.Label -match “SCSI Controller”})) {
foreach ($VirtualDiskDevice in ($VMView.Config.Hardware.Device | where {$_.ControllerKey -eq $VirtualSCSIController.Key})) {
  $VirtualDisk = “” | Select SCSIController, DiskName, SCSI_Id, DiskFile, DiskSize, WindowsDisk
  $VirtualDisk.SCSIController = $VirtualSCSIController.DeviceInfo.Label
  $VirtualDisk.DiskName = $VirtualDiskDevice.DeviceInfo.Label
  $VirtualDisk.SCSI_Id = “$($VirtualSCSIController.BusNumber) : $($VirtualDiskDevice.UnitNumber)”
$VirtualDisk.DiskFile = $VirtualDiskDevice.Backing.FileName
  $VirtualDisk.DiskSize = $VirtualDiskDevice.CapacityInKB * 1KB / 1GB
  # Match disks based on SCSI ID
  $DiskMatch = $WinDisks | ?{($_.SCSIPort – 2) -eq $VirtualSCSIController.BusNumber -and $_.SCSITargetID -eq $VirtualDiskDevice.UnitNumber}
  if ($DiskMatch){
  $VirtualDisk.WindowsDisk = “Disk $($DiskMatch.Index)”
}
else {Write-Host “No matching Windows disk found for SCSI id $($VirtualDisk.SCSI_Id)”}
  $DiskInfo += $VirtualDisk
  }
  }
  $DiskInfo | Out-GridView
  }
  else {Write-Host “Virtual Machine $Vm Not Found”}

Disconnect-VIServer * -Confirm:$false

CleanUp Old Active Sync Devices

Overview older than 30 Days:
Get-MobileDevice | Get-MobileDeviceStatistics | where {$_.LastSyncAttemptTime -lt (get-date).adddays(-30)} | out-gridview

Delete active sync devices older then 30 days

Get-MobileDevice | Get-MobileDeviceStatistics | where {$_.LastSyncAttemptTime -lt (get-date).adddays(-30)} |  Remove-MobileDevice -Confirm:$false

Server 2016 and ADFS Error 364 0d00-0080000000e1 EnableIdPInitiatedSignonPage False

image

On ADFS page you get error: 00000000-0000-0000-0d00-0080000000e1

Event viewer: Event 364 Microsoft.IdentityServer.Web.IdPInitiatedSignonPageDisabledException: MSIS7012: An error occurred while processing the request.

image

image

Get-AdfsProperties | select EnableIdPInitiatedSignonPage

Set-AdfsProperties -EnableIdPInitiatedSignonPage $true

adfs-server-2016-issue-testing

Translate »