Monday, October 3, 2016

PART 4.1 : MICROSOFT AZURE POWERSHELL CREATING AND ADMINISTRATING LOCAL NETWORK GATEWAY

Recently I have started writing on Microsoft Azure blogs, It is to be complete by this week, so do stay tuned on my new website http://vcloud-lab.com.



PART 1 : MICROSOFT AZURE CREATION AND CONFIGURATION OF VPN TUNNEL SERIES
PART 2 : MICROSOFT AZURE CREATING RESOURCE GROUP 
PART 3 : MICROSOFT AZURE CREATING AND ADMINISTERING VIRTUAL NETWORK (VNET)
PART 3.1 : MICROSOFT AZURE POWERSHELL CREATING AND ADMINISTERING VIRTUAL NETWORK (VNET)
PART 4 : MICROSOFT AZURE CREATING AND ADMINISTRATING LOCAL NETWORK GATEWAY VPN
PART 4.1 : MICROSOFT AZURE POWERSHELL CREATING AND ADMINISTRATING LOCAL NETWORK GATEWAY





New-AzureRmLocalNetworkGateway -Name Poc-VPN_localGateway -ResourceGroupName POC-VPN -Location 'East US 2' -GatewayIpAddress '203.1.1.10' -AddressPrefix @('172.21.101.0/24', '172.21.1.0/24')
Parameters break down as below.
-Name: Name for new local network gateway
-ResourceGroupName: Name of the existing Resource Group in my case is POC-VPN
-Location: This is region where gateway is location, mine is same as existing resource group (East US 2)
-GatewayIPAddress: This is my in-house public internet IP
-AddressPrefix: This is again my inhouse private IPs, I have my servers and desktops in this IP series.

Friday, May 6, 2016

Top vBlog 2016 - Time to Choose the Top Blogs.

Last year I registered my blog for top vblog, Again Top vBlog 2016 voting on vSphere-Land has been opened . Please vote me for keep bloggers motivated. 


If you appreciate my work and blogs please do vote me. LINK TO VOTE

Below is the paragraph Copying from Eric's post, what should you look for while voting.
  • Longevity – Anyone can start a blog but it requires dedication, time & effort to keep it going. Some bloggers start a blog only to have it fall to the wayside several months later. Things always come up in life but the good bloggers keep going regardless of what is happening in their life.
  • Length – It’s easy to make a quick blog post without much content, nothing wrong with this as long as you have good content in the post that people will enjoy. But some bloggers post pretty long detailed posts which takes a lot of time and effort to produce. The tip of the hat goes to these guys that burn the midnight oil trying to get you some great detailed information.
  • Frequency – Some bloggers post several times a week which provides readers with lots of content. This requires a lot of effort as bloggers have to come up with more content ideas to write about. Frequency ties into length, some do high frequency/low length, some do low frequency/high length, some do both. They’re all good and require a lot of time and effort on the bloggers part.
  • Quality – It all comes down to whats in the blog post regardless of how often or how long the blog posts are. After reading a blog post if you come away with learning something that you did not previously know and it benefits you in some way then you know you are reading a quality post. Good quality is usually the result of original content, its easy to re-hash something previously published elsewhere, the good bloggers come up with unique content or put their own unique spin on popular topics.

Friday, March 25, 2016

Find CDP or LLDP information on Windows Servers

The Cisco Discovery Protocol (CDP) is a proprietary Data Link Layer protocol developed by Cisco Systems. It is used to share information about other directly connected Cisco equipment, such as the operating system version and IP address. 

The Link Layer Discovery Protocol (LLDP) is a vendor-neutral link layer protocol in the Internet Protocol Suite used by network devices for advertising their identity, capabilities, and neighbors on an IEEE 802 local area network, principally wired Ethernet.

From Systems perspective You can view on which Switch and Switchport your Server or desktop NIC/Network cards are connected.
Finding CDP or LLDP information from ESXi very easy as VMware has provisioned separate interface for the same. As in the below screenshot click esxi server, then go to configuration tab, select Networking from Hardware, now as shown click on the CDP button after the Physical Network Card, and you will see CISCO Discovery Protocol, Now you can see I know which switch port I am connected, with this information I can connect to my networking team for any further troubleshooting issue or any changes if I required.
As I wanted to design HyperV/SCVMM solution, I was working on the same from networking part. and while architecturing Network solution for HyperV and I needed some Network side inventory like where my Windows Server HyperV Nic ports are connected on Physical switches for further designing, I don't see any separate interface or console where I can find such Information (if anyone know feel free to point out). So to find that information you can use Microsoft's tool Microsoft Network Monitor 3.4. It can capture network traffic and then you can filter the information you required. This topic is not only limited to Windows Server you can also use your own desktop to test this.
Here I will be using my favorite tool WiresharkWireshark is a network protocol analyzer for Unix and Windows, and it has many great features, I have download and installed it on my Windows Server., Here my server has got two physical ethernet cards and I want to know where both cards are connected on physical Switch. 
Search for wireshare and open it
Once Wireshark is running, you will detect all Network cards you have in your server, It matches the earlier screenshot I posted, Now You need to select one network card at a time, first NIC card I select is Team01, It will capture traffic on Team01 Nic.
Once you click on the network card it will start analyzing traffic in and out from the Nic. and you will see tons and tons of information. Now you will need to filter this captured information to find required CDP information. Type CDP and it will drop down the list of protocols from that list select CDP, incase you need LLDP information you can filter for LLDP.
Here I have got what I wanted. Very specific useful information regarding Switch name and Switch port number. 
Now I have collected information for one of the NIC card, I will be capturing data for another NIC card. from the capture menu press Stop to halt the capturing packets and go on selecting another Ethernet Card in the Options which is currently grayed out.
Now in the same Capture menu Options will be active once you stop capturing and we can click it to select another NIC.
You will again see 2 Nics in the list as we have already collected and captured information for one of the NIC in my scenario I had team01 and now will collect information for Management NIC card and click on start.
Now here is the info for another NIC card. As long as you keep wireshare capture starting and running, It will keep fetching the CDP data after some interval, Again you can capture LLDP information also with this tool. 
I found some of other tools exist which only CDP from tallsoft CDP monitor which is also handy, and there is windump.exe commandline utility which is available on the wireshark only.

My earlier useful script for collecting CDP and LLDP from VMWare ESXi environment.

Save complete virtual PortGroup information Settings - Powercli

Powercli Pull CDP and LLDP information in single nice table format - Part 2

Wednesday, March 23, 2016

Error resolved: Hyperv cannot be installed: A Hyperviser is already running.

From my earlier Post Powershell Rocks - Creating virtual Nic cards for testing (Standalone HyperV), While installing HyperV role I got error through Server Manager GUI I was receiving error, HyperV cannot be installed: A Hyperviser is already running. After many repetitive attempts through server manager GUI it was failing, I also used Powershell command Install-WindowsFeature Hyper-V but result was same. In the last I stumble upon Microsoft blog .
And I got to know about new command for installing optional roles. 
Enable-WindowsOptionalFeature –Online -FeatureName Microsoft-Hyper-V –All 
This resolved my error and after reboot I was able to use hyperV.

Old useful Posts
Configuring HyperV on windows 2008 R2 and configuring Failover clustering 

Powershell Rocks - Creating virtual Nic cards for testing (Standalone HyperV)

Today I had to setup some demo lab environment for my friend for tutoring purpose. He had couple of old desktop and Laptop with low configurations and one manageable old switch and router, I intended to install Windows server 2012 R2 on them and wanted to show standalone HyperV Demo. I installed and setup server everything was working fine but I wanted to show him HyperV Microsoft Failover Clustering but unable to simulate it, why because all those couple of desktops and laptop had only one NIC card and I required another Network Card for heartbeat purpose. but we didn't want to invest anything on the old. so here Powershell came to our rescue.
In windows server 2012 R2 when installed Hyperv Role and Powershell module, there is a feature you can create multiple virtual ethernet card, and all the traffic flows through single physical network card. Here I wanted to achieve my physical and virtual network card configuration like below diagram, HyperV role must be installed is requirement and Switch port where physical Nic is connected must be trunk if you want to use different subnets. 
Here are the Powershell commands with there parameters I used to setup and configure virtual network cards. First rule open Powershell as administrator.
Note: Running second command in the line can cause server disconnection. hence advised to not use remote desktop instead use ILO, DRAC or make sure you are in the front of server.
##*************************************************************************
Get-NetAdapter
New-NetLbfoTeam -Name "SwTeam" -TeamMembers PhysicalNic -TeamingMode Static -Confirm:$false
New-VMSwitch "VirtualSwitch" -MinimumBandwidthMode weight -NetAdapterName "SwTeam" -AllowManagement $false
Add-VMNetworkAdapter -ManagementOS -Name "Management" -SwitchName "VirtualSwitch"
Set-VMNetworkAdapter -ManagementOS -Name "Management" -MinimumBandwidthWeight 33
Add-VMNetworkAdapter -ManagementOS -Name "HeartBeat" -SwitchName "VirtualSwitch"
Set-VMNetworkAdapter -ManagementOS -Name "HeartBeat" -MinimumBandwidthWeight 33
Add-VMNetworkAdapter -ManagementOS -Name "Storage" -SwitchName "VirtualSwitch"
Set-VMNetworkAdapter -ManagementOS -Name "Storage" -MinimumBandwidthWeight 33
Get-VMNetworkAdapter -All -Name *
Get-NetAdapter
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "Management" -Access -VlanID 5
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "HeartBeat" -Access -VlanID 10
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "Storage" -Access -VlanID 20
Get-VMNetworkAdapterVlan -ManagementOS
##*************************************************************************

Now I will be running one command at a time and whatever I will be setting parameters based on results. First I will be running Get-Netadapter which shows all the Ethernet cards on the my system. As you can see from below screenshot I got only one Physical NIC and it is named as "PhysicalNic", Which I will be require in my next cmdlets.
Now I know, What is my Physical Nic name is, which I am going to use it in next command
Note: Running this command can cause server disconnection. hence advised to not use remote desktop instead use ILO, DRAC, or make sure you are in the front of server.
New-NetLbfoTeam -Name "SwTeam" -TeamMembers PhysicalNic -TeamingMode Static -Confirm:$false
It has created new software switch "SwTeam" and PhysicalNic is part of the Team, Static is the Teaming mode I am using here.
Tip: Incase you have installed HyperV but you are not able to find above command or next command I am going to run below command to install hyperv feature before starting command. HyperV role must be installed before running above commands. 
Install-WindowsFeature Hyper-V-PowerShell
New-VMSwitch "VirtualSwitch" -MinimumBandwidthMode weight -NetAdapterName "SwTeam" -AllowManagement $false
New-VMSwitch cmdlet creates a new virtual switch on one or more virtual machine hosts, Parameter minimumbandwidthMode is weight (weight is a unit (1 to 100) which i will be using in next command.)
Next I will be adding Virtual Network card and to the Host. and it will be using 33 % bandwidth weight of Physical nic. ManagementOS is your main operating system.
Add-VMNetworkAdapter -ManagementOS -Name "Management" -SwitchName "VirtualSwitch"
Set-VMNetworkAdapter -ManagementOS -Name "Management" -MinimumBandwidthWeight 33
Here is next screenshot after creating all the virtual nic cards. 
Next command to verify again what we have deployed. 
Get-VMNetworkAdapter -All -Name *
Get-NetAdapter
The last command is setting Vlan. and verify what settings has been configured. You can change below parameters as per your requirements. 
Tip: Incase you don't have trunk port(I mean your computers are connected to normal switches), do not run below commands, just assign IP directly.
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "Management" -Access -VlanID 5
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "HeartBeat" -Access -VlanID 10
Set-VMNetworkAdapterVlan -ManagementOS -VMNetworkAdapterName "Storage" -Access -VlanID 20
Get-VMNetworkAdapterVlan -ManagementOS
Now the last step is assign IP to virtual network cards and verify you can connect them over network, here I will assign IP on Management Network and just will check whether I am able to do RDP to the server. And I am Successful.


Sunday, March 6, 2016

Resolved: The trust relationship between this workstation and the primary domain failed

In my earlier post I knew only 2 commands (Netdom and Test-ComputerSecureChannel) to rejoin computer in domain without restart. One of the user Tim Basten commented on my post that there is one more powershell cmdlet can be used to fix broken computer account without restart. so I tried it and yes it works perfectly.

Reset-ComputerMachinePassword -Credential (Get-Credential)
Once you execute it will ask for your domain admin username and password.
It is fairly simple. I guess their might be more commands available to do same tasks, I know there is one more from command prompt nltest but never used it.

Powershell Rocks, Rejoin computers in domain without restart

Saturday, March 5, 2016

Powershell Rocks, Rejoin computers in domain without restart

I received below error many many times when logging to some critical server and I am stuck. (I am very sure you also must have received this error many times)
The trust relationship between this workstation and the primary domain failed.
Due to this error I cannot login into server with my domain credentials. In old days I had to disjoin this server from domain, reboot and rejoin again. This was big headache for Mission Critical servers. If you like using Powershell for system management it is very easy to rejoin computer account to domain without restarting server. You must have at least Powershell version 3 to use this command which is by default there in windows 2012 server version and windows 8. 

Video how to use Test-ComputerSecureChannel
It is obvious that you can use your domain accounts means you have to use your local administrator account to login, and open powershell as administrator.
Once powershell is fired up you have to just run below command to rejoin computer into domain without restart.

Test-ComputerSecureChannel -Repair -Credential (Get-Credential)

It prompts for username password, It should be domain and should have AD rights. 
It will simply repair broken computer account password on your computer. and will give message True. Once this is done and you can logoff and test logging with your Domain account, This trick has saved me many times when there was restriction on rebooting Server, even plenty of time I used it on my own desktop, so I dont have reboot and I can work undisturbed (I found I can no longer access file servers and other things).
there is old trick for old OS you can use Netdom command (I used to use it on Windows 2008 r2 and lower OS, you can find this netdom 2008 os series by default, for older you can download it from its CD/DVD)
netdom resetpwd /Server:DC /UserD:DomainAdmin /PasswordD:Password
In next blog I found one more command to rejoing computer into domain without reboot.

Resolved: The trust relationship between this workstation and the primary domain failed

Wednesday, February 24, 2016

Install missing Powershell ISE on Windows Server 2008 R2

Everytime I login to any of new server in my windows server 2008 r2 with default PSversion powershell v2 I find ISE is missing and it need to install in case if i want to run some script, (Powershell ISE is my favorite powershell script editor which comes with windows 2008 r2 and above), I use ISE lot to edit scripts. 

Here is how when I search for powershell it is missing.
Here is how you can install it using powershell it self, open powershell as an administrator. and you will have run below 2 commands to install ISE.
Import-Module ServerManager
Add-WindowsFeature Powershell-ISE
If you check in the above screenshot you will find powershell can be used from GUI, need to install as a feature from Server Manager and the Feature name is a Windows Powershell Integrated Scripting Engine.

I prefer the powershell way only to install ISE, because I find it quick, no need to touch mouse., and also this way I memorize my essential commands.

Friday, February 19, 2016

vSphere Datastores inventory report powercli - Volume 2

I used to collect datastores inventory using my old script VMware Datastores inventory. It is still very handy when I want to keep it as inventory. This inventory is also good when I want to troubleshoot, but over the period of time I found still I am missing something. Now I have added some more useful information about iSCSI paths. With this information I was able to rectify and implement multiplying best practices correctly. 

Alike my old script this also tells datastore configuration information per host, It starts with first esxi host, pull information about all the datastores configured on it, then second host and all the datastores on it, and so on, Below is list this script pulls information about.
VMhost name
DatastoreName -  You will find it repetitive if same datastore is mounted on another host also
FreeSpaceGB - Free Space in GB
CapacityGB - Capacity in GB
FileSystemVersion - this tells what is the version of VMFS filesystem.
RuntimeName: Handy when you want to check what device datastore is mapped.
CanonicalName: I use this to match my esxi datastore and storage name. (I can ensure I am working on correct lun/datastore)
MultipathPolicy: Self explanatory.
Vendor: Esxi can detect what can be device (vendor) of datastore.
DatastoreDatacenter:  Datacenter this datastore available.
VMsOnDatastore: VMs name on the this datastore but only belongs the esxi host you are fetching information
NumberofPaths: This is really handy and saved my day lots of time.
Paths: IP addresses of Paths (iscsi target storage paths)
State: Where path is active or standby?
Preferred:  What storage path is preferred path?
IsWorkingPath: This somewhat similar to preferred path. but tells is the path active currently.

This is screenshot after running the script on the console. 
here is the script, on how to use u can check my previous articles, 
  #####################################                                                                
  ## http://kunaludapi.blogspot.com                                                                
  ## Version: 2                                                               
  ## Date: 16 Dec 2015                                                              
  ## Script tested on below platform                                                                
  ## 1) Powershell v4                                                               
  ## 2) Powercli v5.5                                                                
  ## 3) Vsphere 5.5                                                               
  ####################################                                                               
  #Add-PSSnapin vmware.vimautomation.core                                                               
  #Connect-Viserver #vcenterserver                                                                
                                                               
 function Get-DatastoreInventory {                                                               
   $HostDatastoreInfo = Get-VMHost | Get-ScsiLun -LunType disk                                                                
   $DatastoreInfo = Get-Datastore                                                               
   foreach ($Hostdatastore in $HostDatastoreInfo) {                                                                
    $Datastore = $DatastoreInfo | Where-Object {$_.extensiondata.info.vmfs.extent.Diskname -match $Hostdatastore.CanonicalName}                                                               
    $LunPath = $Hostdatastore | Get-ScsiLunPath                                                              
    if ($Datastore.ExtensionData.vm) {                                                               
     $VMsOnDatastore = $(Get-view $Datastore.ExtensionData.vm).name -join ","                                                               
    } #if                                                               
    else {$VMsOnDatastore = "No VMs"}                                                               
                                                                 
   #Work on not assigned Luns error at silentlyContinue                                                               
    if ($Datastore.Name -eq $null) {                                                              
     $DatastoreName = "Not mapped"                                                              
     $FileSystemVersion = "Not mapped"                                                              
    }                                                              
    else {                                                              
     $DatastoreName = $Datastore.Name -join ","                                                              
     $FileSystemVersion = $Datastore[0].FileSystemVersion                                                               
    }                                                              
                                                                   
    $DatastoreFreeSpace = $Datastore.FreeSpaceGB -join ", "                                                               
    $DatastoreCapacityGB = $Datastore.CapacityGB -join ", "                                                               
    $DatastoreDatacenter = $Datastore.Datacenter -join ", "                                                               
                                                               
    $State = $LunPath.State -join ", "                                                              
    $Preferred = $LunPath.Preferred -join ", "                                                              
    $Paths = ($LunPath.ExtensionData.Transport | foreach {($_.Address -split ":")[0]}) -Join ", "                                                              
    $IsWorkingPath = $LunPath.ExtensionData.IsWorkingPath -Join ", "                                                              
                                                                  
    $Obj = New-Object PSObject                                                               
    $Obj | Add-Member -Name VMhost -MemberType NoteProperty -Value $hostdatastore.VMHost                                                               
    $Obj | Add-Member -Name DatastoreName -MemberType NoteProperty -Value $DatastoreName                                                                
    $Obj | Add-Member -Name FreeSpaceGB -MemberType NoteProperty -Value $DatastoreFreeSpace                                                               
    $Obj | Add-Member -Name CapacityGB -MemberType NoteProperty -Value $DatastoreCapacityGB                                                               
    $Obj | Add-Member -Name FileSystemVersion -MemberType NoteProperty -Value $FileSystemVersion                                                               
    $Obj | Add-Member -Name RuntimeName -MemberType NoteProperty -Value $hostdatastore.RuntimeName                                                               
    $Obj | Add-Member -Name CanonicalName -MemberType NoteProperty -Value $hostdatastore.CanonicalName                                                               
    $Obj | Add-Member -Name MultipathPolicy -MemberType NoteProperty -Value $hostdatastore.MultipathPolicy                                                               
    $Obj | Add-Member -Name Vendor -MemberType NoteProperty -Value $hostdatastore.Vendor                                                               
    $Obj | Add-Member -Name DatastoreDatacenter -MemberType NoteProperty -Value $DatastoreDatacenter                                                               
    $Obj | Add-Member -Name VMsOnDataStore -MemberType NoteProperty -Value $VMsOnDatastore                                                               
    $Obj | Add-Member -Name NumberOfPaths -MemberType NoteProperty -Value $LunPath.Count                                                              
    $Obj | Add-Member -Name Paths -MemberType NoteProperty -Value $Paths                                                              
    $Obj | Add-Member -Name State -MemberType NoteProperty -Value $State                                                              
    $Obj | Add-Member -Name Preferred -MemberType NoteProperty -Value $Preferred                                                              
    $Obj | Add-Member -Name IsWorkingPath -MemberType NoteProperty -Value $IsWorkingPath                                                              
    $Obj                                                               
   }                                                               
  }                                                               
  Get-DatastoreInventory | Export-Csv -NoTypeInformation c:\temp\DatastoreInfoHostwise.csv                                                              
I exported report to csv and file looks like this., Csv file can be opened in excel, this CSV can be used as inventory later, My favorite use is capacity management, I kept collecting data for 1 year, and after 1 year i know how datastore is getting filled gradually. 

Monday, February 15, 2016

import vCenter roles (privileges) - Powercli.

From my first article Export vcenter roles (privileges) I exported all the roles and privileges successfully now it was task to migrate Roles on another vCenter. I already had grabbed roles in files so they where completely portable, I extracted zip file of my roles in the same c:\temp folder as I was going to use it.

Other very useful script for vCenter migration.

Exporting virtual machine annotation (Attributes) and notes to CSV file - Powercli

Move/Migrate VMs to folder Path on another vCenter - Powercli

Get vCenter VM folder Path from VMs and Templates- Powercli

Importing VM annotation (Attributes) and notes from CSV file into vCenter - Powercli

Import vCenter roles (privileges) - Powercli

Export vcenter roles (privileges)


this is screenshot from my previous post it contains all the roles.
Here is the script. I hope I am keeping all simple.

 <#   
  .Synopsis   
   Imports roles into vsphere roles..   
  .Description   
   This script imports roles into vspheres from .role file/   
  .Example   
   Import-vSphereRoles -Path c:\temp  
   Import Roles to the folder.   
  .Notes  
   NAME: Import-vSphereRoles   
   AUTHOR: Kunal Udapi   
   LASTEDIT: 15th February 2016  
   KEYWORDS: Import Roles   
  .Link   
   #Check Online version: http://kunaludapi.blogspot.com    
   #Requires -Version 3.0   
  #>   
  #requires -Version 3    
 [CmdletBinding(SupportsShouldProcess)]   
  Param(   
   [Parameter(Mandatory=$true, Position=1,   
    ValueFromPipeline=$true)]   
   [AllowNull()]   
   [alias("LiteralPath")]   
   [string]$Path = "c:\temp"    
  ) #Param   
 Begin {  
   $roleFiles = Get-ChildItem -Path $Path -Filter *.role  
 }  
 Process {  
   foreach ($role in $roleFiles) {  
     $VIRoleName = $role.BaseName   
     $RolesContent = Get-Content -Path $role.FullName  
     New-Virole -Name $VIRoleName | Out-Null  
     Write-Host "Created Role `"$VIRoleName`"" -BackgroundColor DarkGreen  
     foreach ($Privilege in $RolesContent) {  
       if (-not($privilege -eq $null -or $privilage -eq "")) {  
         Write-Host "Setting Permissions `"$Privilege`" on Role `"$VIRoleName`"" -ForegroundColor Yellow  
         Set-VIRole -Role $VIRoleName -AddPrivilege (Get-VIPrivilege -ID $privilege) | Out-Null  
       } #if (-not($privilege -eq $null -or $privilage -eq ""))  
     } #foreach ($Privilege in $RolesContent)  
   } #foreach ($role in $roleFiles)  
 }  
Once you keep it in .ps1 and run it  (check my earlier post for Export vcenter roles (privileges) how i have collected information and running script), you will see powercli console some thing like below screenshot.
I will be sharing next script for Exporting and Importing roles permissions stay tuned. If you like this article please share knowledge. 

Export vcenter roles (privileges) - Powercli.

This post I am continuing from another posts, Migration from one vcenter to another.

Exporting virtual machine annotation (Attributes) and notes to CSV file - Powercli

Move/Migrate VMs to folder Path on another vCenter - Powercli

Get vCenter VM folder Path from VMs and Templates- Powercli

Importing VM annotation (Attributes) and notes from CSV file into vCenter - Powercli

Import vCenter roles (privileges) - Powercli

Export vcenter roles (privileges)


In this post I will be showing how to export roles. and can be imported to another vCenter. This is completely dedicated to exporting roles only, they are exported to specified folder with .role extension. As you can see I have multiple roles created, some are by default created roles, my script skip those roles and only backup User created roles.
When you edit one of the role you will see information some thing like this, these are called roles privileges. Each privilege has some meaning ful name, ie inside alarms there is acknowledge alarm rights.
Here is my script that can pull all this information and keeps in .role file. Copy paste this script and keep it in ps1 file.
  <#   
  .Synopsis   
   Exports vsphere roles to text file extension roles.   
  .Description   
   This script exports only the custom created roles by users   
  .Example   
   Export-vSphereRoles -Path c:\temp  
   Exports Roles to the folder.   
  .Notes  
   NAME: Export-vSphereRoles   
   AUTHOR: Kunal Udapi   
   LASTEDIT: 12th February 2016  
   KEYWORDS: Export Roles   
  .Link   
   #Check Online version: http://kunaludapi.blogspot.com    
   #Requires -Version 3.0   
  #>   
  #requires -Version 3    
 [CmdletBinding(SupportsShouldProcess)]   
  Param(   
   [Parameter(Mandatory=$true, Position=1,   
    ValueFromPipeline=$true)]   
   [AllowNull()]   
   [alias("LiteralPath")]   
   [string]$Path = "c:\temp"    
  ) #Param   
 Begin {  
   $DefaultRoles = "NoAccess", "Anonymous", "View", "ReadOnly", "Admin", "VirtualMachinePowerUser", "VirtualMachineUser", "ResourcePoolAdministrator", "VMwareConsolidatedBackupUser", "DatastoreConsumer", "NetworkConsumer"  
   $DefaultRolescount = $defaultRoles.Count  
   $CustomRoles = @()  
 } #Begin  
   
 Process {  
   $AllVIRoles = Get-VIRole  
   
   0..($DefaultRolescount) | ForEach-Object {  
     if ($(Get-Variable "role$_" -ErrorAction SilentlyContinue)) {  
       Remove-Variable "role$_" -Force -Confirm:$false  
     } #if ($(Get-Variable "role$_" -ErrorAction SilentlyContinue))  
   } #0..($DefaultRolescount) | Foreach-Object  
   
   0..$DefaultRolescount | ForEach-Object {  
     $DefaultRolesnumber = $DefaultRoles[$_]  
     if ($_ -eq 0) {  
       New-Variable "role$_" -Option AllScope -Value ($AllVIRoles | Where-Object {$_.Name -ne $DefaultRolesnumber})  
     } #if ($_ -eq 0)  
     else {  
       $vartxt = $_ - 1  
       $lastrole = 'role'+"$vartxt"  
       #Get-Variable $lastrole  
       New-Variable "role$_" -Option AllScope -Value (Get-Variable "$lastrole" | select -ExpandProperty value | Where-Object {$_.Name -ne $DefaultRolesnumber})  
     } #else ($_ -eq 0)  
   } #0..$DefaultRolescount | ForEach-Object  
   $filteredRoles = Get-Variable "role$($DefaultRolescount-1)" | select -ExpandProperty value  
 } #Process  
 End {  
   $filteredRoles | ForEach-Object {  
     $completePath = Join-Path -Path $Path -ChildPath "$_.role"  
     Write-Host "Exporting Role `"$($_.Name)`" to `"$completePath`"" -ForegroundColor Yellow  
     $_ | Get-VIPrivilege | select-object -ExpandProperty Id | Out-File -FilePath $completePath  
   } #$filteredRoles | ForEach-Object  
 } #End  
   
Open vmwere vsphere powercli,  Make sure your execution policy is set to remote singed or something that can execute script. Mine is unrestricted, I only run script created by me only.
Connect to old vcenter server using Connect-VIServer command.
Once you are connected. time to execute command, I have saved my script under c:\script. and this is how I run that script with dot sourcing. Once you run ps1 file you can see on the screen what is happening in yellow.
All the roles file are stored on the c:\temp, now you can copy paste these roles in zip file and ready to be used on other vcenter for importing.
You can open role file in notepad and the view is as below. This is how exported vcenter role file looks like, in my next blog i am going to use same file and export privileges to another vCenter.