profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Thursday, November 30, 2017

Automating adding of vlans to UCS

I often wonder why am I doing automation because it is boring. Doing stuff manually is time consuming, inefficient but gives a sense of 'hey i am doing something'. Lol... anyway we had a VxBlock and my colleague needed to add 500+ vlans on UCS and we needed to map them to fabric-A and fabric B.
System Requirements:
Powershell 4+
Cisco Powertool Suite 2.x
The purpose of this post is to make the reader understand that how easy it is to come up with your own automation and it is easier than resisting sugar in your diet.
So let us look at the command first which does the adding of vlan

Get-UcsLanCloud | Add-UcsVlan -DefaultNet no -Id $vlan -Name $vlanID

It is simple as a pimple on a dimple on my niece cheek. Okay enough of showing off of my poetic (oh i know i suck at it...) let us move on shall we!
The above command is something you can find from UCS documentation or search online. Yes, why do stuff when it is already done. Build on it not rebuild it.
$vlan here is the name of the vlan, an alphanumeric.
$vlanID is the vlan ID, an integer.

If you have seen any of my previous scripts or even seen my powershell tutorials then you will know that I like csv files to take inputs. They are simple and easy to work with. When the user runs our script we want the script to open a csv file with proper headers .

1st part of the script will display a message on the terminal and tells the user on what to do.

Write-Host "
A CSV file will be opened (open in excel/spreadsheet)
populate the values,
save & close the file,
Hit Enter to proceed
" -ForegroundColor Blue -BackgroundColor White

After this we want to define the path where the csv file will be created and it's name.

$csv = "$PSScriptRoot/ucsAddVlan.csv"

I always love to $PSScriptRoot as the path since it means that wherever the script is currently located that is the our path. So it sets the current working directory as your path. the gnu/linux shell equivalent of cwd. After that I have given the name of the file with .csv as the extension. Since we have the path and the file we now need to add headers to the file.


get-process | Select-Object vlan,vlanID | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation

Do not get confused with why I am using get-process here. It is just my street smart way of adding headers (headings) to the csv file. The above  '-Encoding ASCII -NoTypeInformation' is important since that enables you to open it with an excel.


# this line opens the csv file
Start-Process $csv
# the below line waits for the user to save the csv file and hit enter
Read-Host "Hit Enter/Return to proceed"

Okay the start-process opens up the file but we want to wait for the user to enter the data and wait. So we will Add a Read-host command below since it pauses the script till the user enters something, in this case, just hit enter once the user is done entering the data, save the file.


$csv = Import-Csv $csv
foreach ($line in $csv) {
  $vlan = $($line.vlan)
  $vlanID  = $($line.vlanID)
}

Processing a csv file is damn easy. the 1st line is importing the data from the $csv file and storing all that in the $variable $csv.
2nd line is going through each line of the $csv file and creating a variable. $vlan = $($line.vlan) here means that go in the line $line where the heading or column name is vlan, take the value from that cell and store it in the variable named $vlan. The same thing is true with $vlanID. Now once we have the variables for the 1st line we want to do something with that right? so let us do it.


foreach ($line in $csv) {
  $vlan = $($line.vlan)
  $vlanID  = $($line.vlanID)
  
    write-host -ForeGroundColor yellow  "Add Vlan $vlan $vlanID" 
    Get-UcsLanCloud | Add-UcsVlan -DefaultNet no -Id $vlan -Name $vlanID
  }

So once I created the variables I am using those variables to create a vlan with a vlan ID in the last line. Above that I have another line which is just to tell the user what it is doing.
Combine all the above and now you have the script to add vlans with vlan IDs to the UCS. Yes, I leave that combining part to you. Anything where you have not put some effort of your own you won't find it interesting and struggle learn to something or do something, even if it is trivial will always make you know it than just remember it.

Python 3.6 OOP Regular, Class and static methods


files here

https://github.com/MrAmbiG/LearningPython

Sunday, November 26, 2017

My PyCharm Setup

So these are my notes to get back my pycharm setup in case if i have reset it or lose it for whatever reason.

  1. PyCharm community edition ( i am poor, can't afford professional edition )
  2. Atom file icons IDEA
  3. CodeGlance
  4. Material Theme UI
  5. replace the default ctrl+shift+f10 to run the code with ctr+comma (this seems to be the only ctrl+ combo available, rest are all taken by others)

Wednesday, November 22, 2017

Python 3.6 GUI with tkinter

There is no fun in using an application which does not have a graphical user interface. When you are trying to make a game or a program and if it is for those who are not coders then tkinter is here for the rescue.
Get your notebook here.


import tkinter as tk

# create a window
window = tk.Tk()

# start the GUI
window.mainloop()

tkinter is a built in GUI module. Here we are importing it. Creating a window. We can run just this code but the window will disappear too fast. saying window.mainloop() will make it stay till we close it.
I urge you to always do the following when you are exploring a module.


dir(tkinter)
help(tkinter)

Once you are done exploring the module then let us improvise on our previous work.
  1. create a Label for our window
  2. Give it a label
  3. define a size for the window
import tkinter as tk
from tkinter import ttk # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") 

# start the GUI
window.mainloop()

What is the use of this justice league window without it's members? The house is empty. Let us bring in our heroes.


import tkinter as tk
from tkinter import * # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") # 

# Let us add our members to the window
T = tk.Text(window)
T.pack()
T.insert(tk.END, "Batman \nSuperman \nFlash \nAquaman \nWonder woman \nCyborg")

# Start the GUI event loop
window.mainloop()

You can easily make out that we are now adding text to the window. This is how you add text in tkinter so I will not try to pour any logic here. You just have to remember it or do it so many times to that you won't forget.
If you run it now, you will have the text displayed. Why stop there? Let us add a button, give it a name and when you click on it, it will display the true identity of the members of the justice league.


import tkinter as tk
from tkinter import ttk # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") 

# Let us add our members to the window
T = Text(window, height=10, width=30) # define the area of text
T.pack()
T.insert(END, "Batman \nSuperman \nFlash \nAquaman \nWonder woman \nCyborg")

# member's real identity
def RevealId():
    print("Batman is Bruce Wayne \nSuperman is Clark Kent \nFlash is Barry Allen \
    \nAquaman is Arthur Curry \nWonder woman is Diana Prince \nCyborg is Victor Stone")

# add a button to do some stuff
b = Button(text="Reveal their identity", command=RevealId)
b.pack()

# Start the GUI event loop so that it won't close
window.mainloop()

go on. explore more.

Monday, November 20, 2017

Python 3.6 Handling errors and exceptions

Error handling one of the great feature of python and it offers a lot of versatility. Let us first build up the need for this feature of python.

if 1<2:
    print('Hello world'
File "<ipython-input-1-83ff31806b18>", line 2
    print('Hello world'
                       ^
SyntaxError: unexpected EOF while parsing

You will notice that the missing parenthesis causes the above error. Correcting the above just works fine.


if 1<2:
    print('Hello world')
Hello world

Let us take another example.

x = int(input("Please enter a number: "))
Please enter a number: hey
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-553ece37be8b> in <module>()
----> 1 x = int(input("Please enter a number: "))

ValueError: invalid literal for int() with base 10: 'hey'

Here x was expecting an integer but we gave it a string and thus we see the error above. The error above is very self explanatory. We were not prepared for this but we should be. You see that this was a ValueError.


try:
    x = int(input("Please enter a number: "))
except ValueError:
    print ('Please enter an integer')
Please enter a number: hey
Please enter an integer

We now have a way of handling the exception called ValueError. We display a message instead of the error. What if this is not enough.


try:
    x = int(input("Please enter a number: "))
    print('batman')
    y = x//0
    print('superman')
    print(y)
except ValueError:
    print ('Please enter an integer')

Please enter a number: 8
batman
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-9a959f723c86> in <module>()
      2     x = int(input("Please enter a number: "))
      3     print('batman')
----> 4     y = x//0
      5     print('superman')
      6     print(y)

ZeroDivisionError: integer division or modulo by zero

Now this is getting interesting. The code threw an error at line 4 and thus everything ran before than but nothing after that. That is the beauty of try except. On the very first exception it jumps directly to the except clause.
Here you will also see that you have another exception called ZeroDivisionError. If you are unsure of what exceptions might arise then just catch them all and display which one occurred.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: hey
something went wrong


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception:
    print ('something went wrong')

Please enter a number: 8
something went wrong

Now we are just displaying something went wrong irrespective of what the exception is. Let us change that.
In the following 2 code blocks you see that the exact exception is displayed.

try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)

Please enter a number: 8
integer division or modulo by zero


try:
    x = int(input("Please enter a number: "))
    y = x//0
    print(y)
except Exception as e:
    print (e)
Please enter a number: hey
invalid literal for int() with base 10: 'hey'

Let us look at the code below

try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')

Please enter a number: 8
8
we did not encounter any exceptions

Here we have changed the y = x//0 to y = x//1. Since we did not encounter any exceptions the else clause executed. The else clause only executes if there are no exceptions. There is however finally which gets executed at the end irrespective of all these.


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: 8
8
we did not encounter any exceptions
I will run no matter what and that is why I am called finally


try:
    x = int(input("Please enter a number: "))
    y = x//1
    print(y)
except Exception as e:
    print (e)
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: hey
invalid literal for int() with base 10: 'hey'
I will run no matter what and that is why I am called finally

You can see that else executed when there were no exceptions but finally always gets executed. Sometimes you might want to have your own exceptions defined. You might want to check or assert for certain things and raise an exception there. Here is how we can do it.


try:
    x = int(input("Please enter a number: "))
    if x < 1:
        raise Exception
    y = x//1
    print(y)
except Exception as e:
    print ('The vallue is less than one')
else:
    print('we did not encounter any exceptions')
finally:
    print('I will run no matter what and that is why I am called finally')

Please enter a number: -1
The vallue is less than one
I will run no matter what and that is why I am called finally

clone my github here.
https://github.com/MrAmbiG/LearningPython

Tuesday, November 14, 2017

My configuration of atom for python

install Atom
open settings (ctrl+,) [windows] or file>settings
font type: consolas
settings>your stylesheet>styles.less
settings>editor>font family-->consolas
settings>editor>font size-->20
settings>editor>show indent guide-->true/check
settings>editor>tab lentgh-->4 for python
settings>editor>scroll past end
packages
--------
>>script
configure script's font size
.script-view .line {
  font-size: 14px;
}
packages>script>viewCode>keymaps>scripts.cson-->change code run keymap to ctrl-b from ctrl-shift-b

>>minimap
>>platformio-ide-terminal
>>autosave>check
>>minimap-highlight-selected
>>flake8
>>python-autopep8
>>file-icons
>>autocomplete-python
settings>format on save>check
Go to userprofile>.atom>init.coffee and add
atom.setWindowDimensions({"width": 1920, "height": 1080})
to open it in always 1920*1080 resolution.
>>click anywhere in tree view and press 'I' (uppercase I). This allows you to see hidden or files and folders which are added to .gitignore file. You can switch between hidden view and and normal view by pressing 'uppercase I' in the tree view.

Monday, November 13, 2017

Add Dns entries to your DNS server

We have an amazing web portal which takes care of generating such scripts for us. We upload data to the portal and gives us scripts with values in it which we can right click and run to complete a task. Today I am going to give you a script which does the same but it takes use input in the form of csv. This is useful when the hosts are not in series or you have only few hosts to update to the dns.
It gives you a csv file.
you update the csv file.
you close the csv file.
you hit enter.
you wait.
it is done.
you can find it at my github repository.
github.com/mrambig/windows


function addDnsEntries {
<#
.SYNOPSIS
    add dns entries to microsoft dns server
.DESCRIPTION
    This will create a csv file with the headers. Fill the details and hit enter.
    Then the script will add the dns entries.
.NOTES
    File Name      : addDnsEntries.ps1
    Author         : Gajendra d ambi
    updated        : November 2017
    Prerequisite   : PowerShell v4+ win7 and upper.
    Copyright      - None
.LINK
    Script posted over: github.com/MrAmbig/
#>
Write-Host "make sure you are running it on dns server"

Write-Host "
A CSV file will be opened (open in excel/spreadsheet)
populate the values,
save & close the file,
Hit Enter to proceed
" -ForegroundColor Blue -BackgroundColor White
$csv = "$PSScriptRoot/HostVds.csv"
get-process | Select-Object netbiosName,ip,zone | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation
Start-Process $csv
Read-Host "Hit Enter/Return to proceed"

$csv = Import-Csv $csv

foreach ($line in $csv) 
    {  # importing data from csv and go line by line
    $hostname = $($line.netbiosName)  
    $ip  = $($line.ip)  
    $zone  = $($line.zone)
    add-dnsserverresourcerecordA -name $hostname -ipv4address $ip -zonename $zone -createptr
    }
} addDnsEntries

Does it work?
you let me know...

Sunday, November 12, 2017

Friday, November 10, 2017

Python 3.6 turtles or drawing stuff


"Turtle" is a module in python which helps us to create some basic drawings. Imagine this as a scrible or whiteboard and you use your code to draw. Why the name turtle? well, Imagine a turtle whose tails is dipped in ink and when it is moving on a whiteboard or paper, the tail leaves the ink on the paper creating thus a diagram or drawing. you control the movement of the turtle and turtle's tail dipped in ink takes care of the drawing. cool..haan..i know. Let us get started with your python shell. I always run 3 commands when i am using a new module to know more and explore it.
help()
dir()
<modulename>.__doc__
make it a habit and it will help you.

import turtle
help(turtle)

also run
>>> dir(turtle)
['Canvas', 'Pen', 'RawPen', 'RawTurtle', 'Screen', 'ScrolledCanvas', 'Shape', 'TK', 'TNavigator', 'TPen', 'Tbuffer', 'Terminator', 'Turtle', 'TurtleGraphicsError', 'TurtleScreen', 'TurtleScreenBase', 'Vec2D', '_CFG', '_LANGUAGE', '_Root', '_Screen', '_TurtleImage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__forwardmethods', '__func_body', '__loader__', '__methodDict', '__methods', '__name__', '__package__', '__spec__', '__stringBody', '_alias_list', '_make_global_funcs', '_screen_docrevise', '_tg_classes', '_tg_screen_functions', '_tg_turtle_functions', '_tg_utilities', '_turtle_docrevise', '_ver', 'addshape', 'back', 'backward', 'begin_fill', 'begin_poly', 'bgcolor', 'bgpic', 'bk', 'bye', 'circle', 'clear', 'clearscreen', 'clearstamp', 'clearstamps', 'clone', 'color', 'colormode', 'config_dict', 'deepcopy', 'degrees', 'delay', 'distance', 'done', 'dot', 'down', 'end_fill', 'end_poly', 'exitonclick', 'fd', 'fillcolor', 'filling', 'forward', 'get_poly', 'get_shapepoly', 'getcanvas', 'getmethparlist', 'getpen', 'getscreen', 'getshapes', 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'inspect', 'isdown', 'isfile', 'isvisible', 'join', 'left', 'listen', 'lt', 'mainloop', 'math', 'mode', 'numinput', 'onclick', 'ondrag', 'onkey', 'onkeypress', 'onkeyrelease', 'onrelease', 'onscreenclick', 'ontimer', 'pd', 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position', 'pu', 'radians', 'read_docstrings', 'readconfig', 'register_shape', 'reset', 'resetscreen', 'resizemode', 'right', 'rt', 'screensize', 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle', 'setundobuffer', 'setup', 'setworldcoordinates', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle', 'simpledialog', 'speed', 'split', 'st', 'stamp', 'sys', 'textinput', 'tilt', 'tiltangle', 'time', 'title', 'towards', 'tracer', 'turtles', 'turtlesize', 'types', 'undo', 'undobufferentries', 'up', 'update', 'width', 'window_height', 'window_width', 'write', 'write_docstringdict', 'xcor', 'ycor']

>>> turtle.__doc__
'\nTurtle graphics is a popular way for introducing programming to\nkids. It was part of the original Logo programming language developed\nby Wally Feurzig and Seymour Papert in 1966.\n\nImagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it\nthe command turtle.forward(15), and it moves (on-screen!) 15 pixels in\nthe direction it is facing, drawing a line as it moves. Give it the\ncommand turtle.right(25), and it rotates in-place 25 degrees clockwise.\n\nBy combining together these and similar commands, intricate shapes and\npictures can easily be drawn.\n\n----- turtle.py\n\nThis module is an extended reimplementation of turtle.py from the\nPython standard distribution up to Python 2.5. (See: http://www.python.org)\n\nIt tries to keep the merits of turtle.py and to be (nearly) 100%\ncompatible with it. This means in the first place to enable the\nlearning programmer to use all the commands, classes and methods\ninteractively when using the module from within IDLE run with\nthe -n switch.\n\nRoughly it has the following features added:\n\n- Better animation of the turtle movements, especially of turning the\n  turtle. So the turtles can more easily be used as a visual feedback\n  instrument by the (beginning) programmer.\n\n- Different turtle shapes, gif-images as turtle shapes, user defined\n  and user controllable turtle shapes, among them compound\n  (multicolored) shapes. Turtle shapes can be stretched and tilted, which\n  makes turtles very versatile geometrical objects.\n\n- Fine control over turtle movement and screen updates via delay(),\n  and enhanced tracer() and speed() methods.\n\n- Aliases for the most commonly used commands, like fd for forward etc.,\n  following the early Logo traditions. This reduces the boring work of\n  typing long sequences of commands, which often occur in a natural way\n  when kids try to program fancy pictures on their first encounter with\n  turtle graphics.\n\n- Turtles now have an undo()-method with configurable undo-buffer.\n\n- Some simple commands/methods for creating event driven programs\n  (mouse-, key-, timer-events). Especially useful for programming games.\n\n- A scrollable Canvas class. The default scrollable Canvas can be\n  extended interactively as needed while playing around with the turtle(s).\n\n- A TurtleScreen class with methods controlling background color or\n  background image, window and canvas size and other properties of the\n  TurtleScreen.\n\n- There is a method, setworldcoordinates(), to install a user defined\n  coordinate-system for the TurtleScreen.\n\n- The implementation uses a 2-vector class named Vec2D, derived from tuple.\n  This class is public, so it can be imported by the application programmer,\n  which makes certain types of computations very natural and compact.\n\n- Appearance of the TurtleScreen and the Turtles at startup/import can be\n  configured by means of a turtle.cfg configuration file.\n  The default configuration mimics the appearance of the old turtle module.\n\n- If configured appropriately the module reads in docstrings from a docstring\n  dictionary in some different language, supplied separately  and replaces\n  the English ones by those read in. There is a utility function\n  write_docstringdict() to write a dictionary with the original (English)\n  docstrings to disc, so it can serve as a template for translations.\n\nBehind the scenes there are some features included with possible\nextensions in mind. These will be commented and documented elsewhere.\n\n'

Once you are done exploring it then let us proceed to some fun stuff. Let us draw a
a line
a triangle
a rectangle
a circle and some fun with all of them.

a turtle always starts from left to right. clear the screen. run the following.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90) # tell amy to move forward for about 90 units

you will see that our amy (turtle) draws a straight line or in other words moves from left to right for about 90 units and leaves a trace of ink on its path.
Let us turn that into a triangle.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)

you will now see that in the new window amy/turtle draws a triangle.
Let us make a rectangle around it. I am sure now you know how it works. So let us try it out.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)

Now our triangle is inside the new rectangle. Why stop there? let us have a circle on these too.

import turtle
sc = turtle.Screen # create a window/screen
amy = turtle.Turtle() # create a turtle named amy
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(120) # turn 120 degrees left
amy.forward(90)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.left(90)
amy.forward(130)
amy.left(90)
amy.forward(180)
amy.circle(180) # a circle with 180 units of radius

I want you to explore more since the motto of this post is only to enable you to explore and not explore. Help you to learn cooking so that you cook for yourself and not to cook and steal the fun of cooking from you. FYI I don't much like cooking. I just make oats twice a day with water/salt/spice and thats it.

Lets not forget these

    • Algorithms are a step by step list of instructions designed to address a problem.
    • Interpreter interpreters a high level programming language. A python interpreter does it line by line. It interpretes the high level programming language to a machine or object language so that the machine executes it.
    • Compiler translates a program completely before the program starts running.
      So an interpreter does the translation bit by bit (one line at a time) where as the compiler does it completely before the program even executes.
    • Program is a collection of instructions that performs a specific task when executed by a computer.
    • Bugs are programming errors
    • Debugging is the process of tracking and correcting bugs.
    • Syntax is the structure or grammar of a program
    • Syntax errors structural defects in the code. (missing colon, comma or incorrect indentation)
    • Runtime errors (exception) structural defects in the code which can only be identified during runtime. These are more of a logical fallacy than structural fallacy.
    • Semantic errors are those where a program does something other than the reason for its creation. ex:  a program should produce the addition of 2 numbers but it produces the multiplication of 2 numbers. 
    • source code is any collection of computer instructions written in a human readable programming language.
    • object code (executable) is a sequence of statements or instructions in a computer language, usually a machine code language (ex: binary - zeros and ones). This is how a computer or machine understands. Basically 
    • Byte code is an intermediate language between source and object code.
      The code or lines of code that you typed is source code. Then a compiler or assembler converts it into a byte code before converting it into object code which can then be fed to the machine.
    • Operators are special tokens that represent mathematical functions such as addition (+), multiplication (*).
      1+2
      In the above line 1, 2 are operands. + symbol is the operator.





    ---continued

Thursday, November 9, 2017

automating creation of vmkernel portgroups with powercli and csv

This is just a continuation of my previous post. this is again a work in progress. keep a watch on my github page for the most updated version of it. If vTool (github.com/mrambig/vmware) isnt enough for you and your hosts are in series then is what you need to create vmkernel portgroups. Go to github.com/vmware/mrambig for more

#start of function
function vmkernelPgCsv
{
Write-Host "
A CSV file will be opened (open in excel/spreadsheet)
populate the values,
save & close the file,
Hit Enter to proceed
" -ForegroundColor Blue -BackgroundColor White
$csv = "$PSScriptRoot/HostVds.csv"
get-process | Select-Object vmhost,vss,portgroup,vlan,ip,mask,vmk,mtu | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation
Start-Process $csv
Read-Host "Hit Enter/Return to proceed"

$csv = Import-Csv $csv

  foreach ($line in $csv) 
 {  # importing data from csv and go line by line
    $vmhost = $($line.vmhost)  
    $vss  = $($line.vss)  
    $portgroup  = $($line.portgroup)
    $vlan  = $($line.vlan)    
    $ip  = $($line.ip)
    $mask  = $($line.mask)
    $vmk  = $($line.vmk)    
    $mtu  = $($line.mtu)    
        
    $esxcli = get-vmhost $vmhost | get-esxcli -v2
    (get-vmhost $vmhost).name
    get-vmhost $vmhost | get-virtualswitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false
    
    # add vmkernel with netstack    
    $esxcliset = $esxcli.network.ip.interface.add 
    $args = $esxcliset.CreateArgs()
    $args.interfacename = "$vmk"
    $args.mtu = "$mtu"    
    $args.portgroupname = "$pg"    
    $esxcliset.Invoke($args)   
     
    # update networking to the vmkernel
    $esxcliset = $esxcli.network.ip.interface.ipv4.set
    $args = $esxcliset.CreateArgs()
    $args.interfacename = "$vmk"
    $args.type = "static"
    $args.ipv4 = "$ip"
    $args.netmask = "$mask"
    $esxcliset.Invoke($args)  
    }
}#End of function

vmkernelPgCsv

creating l3 vmotion with powercli and csv

So sometimes the shortcomings of my vtool at github.com/mrambig/vmware/vtool is that it assumes that the ip addresses are in range when creating vmkernel portgroups for vmware. It also assumes that your hosts are in order. We are working a huge VMware implementation which is being deployed and expanded in installment where this is not the case. This is something that i putting it here for those who might use this in future. Of course i have to still test this with my solution architects for whom I am doing this automation. I am certain that it will work. If not I will post the updated version as always in my github page. github.com/MrAmbiG/vmware


#start of function
function l3vmotion2csv
{
Write-Host "
A CSV file will be opened (open in excel/spreadsheet)
populate the values,
save & close the file,
Hit Enter to proceed
" -ForegroundColor Blue -BackgroundColor White
$csv = "$PSScriptRoot/HostVds.csv"
get-process | Select-Object vmhost,vss,portgroup,vlan,ip,mask,vmk,mtu | Export-Csv -Path $csv -Encoding ASCII -NoTypeInformation
Start-Process $csv
Read-Host "Hit Enter/Return to proceed"

$csv = Import-Csv $csv

  foreach ($line in $csv) 
 {  # importing data from csv and go line by line
    $vmhost = $($line.vmhost)  
    $vss  = $($line.vss)  
    $portgroup  = $($line.portgroup)
    $vlan  = $($line.vlan)    
    $ip  = $($line.ip)
    $mask  = $($line.mask)
    $vmk  = $($line.vmk)    
    $mtu  = $($line.mtu)    
        
    $esxcli = get-vmhost $vmhost | get-esxcli -v2
    (get-vmhost $vmhost).name
    get-vmhost $vmhost | get-virtualswitch -Name $vss | New-VirtualPortGroup -Name $pg -VLanId $vlan -Confirm:$false
    # add vmotion netstack
    $esxcliset = $esxcli.network.ip.netstack.add
    $args = $esxcliset.CreateArgs()
    $args.disabled = $false
    $args.netstack = 'vmotion'    
    $esxcliset.Invoke($args)
    
    # add vmkernel with netstack    
    $esxcliset = $esxcli.network.ip.interface.add 
    $args = $esxcliset.CreateArgs()
    $args.interfacename = "$vmk"
    $args.netstack = 'vmotion'
    $args.mtu = "$mtu"    
    $args.portgroupname = "$pg"    
    $esxcliset.Invoke($args)   
     
    # update networking to the vmkernel
    $esxcliset = $esxcli.network.ip.interface.ipv4.set
    $args = $esxcliset.CreateArgs()
    $args.interfacename = "$vmk"
    $args.type = "static"
    $args.ipv4 = "$ip"
    $args.netmask = "$mask"
    $esxcliset.Invoke($args)  
    }
}#End of function

l3vmotion2csv