Monday, April 14, 2014

Powershell - Compare 2 csv files and list changes



I had huge list of data and require to find out changes. (Sample) As you can see I have 2 csv file with New.csv and old.csv





Below is the inner data of both files. There are some changes between both files.


After running below script on the both file

 $OldCSV = Import-Csv -Path C:\temp\CSV-test\Old.csv   
 $NewCSV = Import-Csv -Path C:\temp\CSV-test\New.csv  
   
 $output = @()  
   forEach ($Column in $OldCsv) {      
     $result = $NewCSV | Where-Object {$Column.Name -eq $_.Name}  
     $CPU = if ($Column.CPU -ne $result.CPU) {"Found Change"}  
     $Powerstate = if ($Column.Powerstate -ne $result.PowerState) {"Previous: " + $Column.powerstate + " | Now:" + $result.powerstate}  
     $output += New-object PSObject -property @{  
       VMname = $Column.Name  
       Powerstate = $powerstate  
       CPU = $cpu  
     }  
   }  
 $output | select-object vmname, CPU, Powerstate | Export-Csv -Path C:\temp\CSV-test\Changes.csv -NoTypeInformation  

Below is the result.


Warning: All the testings are performed in lab environment.

Sunday, April 13, 2014

Collect disk space detail and send it in email Powercli

This script will collect C Drive with less than 20% space on the VM and send email with nice HTML format.

I have improvised this script and can be found it under Versin 2 VM disk space detail send via email Powercli

  #####################################   
  ## http://kunaludapi.blogspot.com   
  ## Version: 1   
  ## Tested this script on   
  ## 1) Powershell v3   
  ## 2) Powercli v5.5   
  ## 3) Vsphere 5.x   
  #####################################  
 Add-PSSnapin vmware.vimautomation.core  
   
 # vCenter username password  
 $vCenterServer = "vCenterserver"  
 $vcenteruser = "domain\user"  
 $vcenterpasswd = "Password"  
   
 #connect vCenter Server  
 Connect-VIServer -Server $vCenterServer -User $vcenteruser -Password $vcenterpasswd  
   
 $FinalResult = @()  
 $Allvms = Get-View -ViewType “VirtualMachine” -filter @{”Guest.GuestState”=”running”; “Guest.GuestFullName”=”Windows"}  
 foreach ($vm in $Allvms) {  
   #Only C disk  
   $DriveC = $vm.Guest.Disk | Where-Object {$_.Diskpath -eq "C:\"}  
     
   #Calculations  
   $Freespace = [math]::Round($DriveC.FreeSpace / 1MB)  
   $Capacity = [math]::Round($DriveC.Capacity / 1MB)  
   $SpaceOverview = "$Freespace" + "/" + "$capacity"  
   $PercentFree = [math]::Round(($FreeSpace)/ ($Capacity) * 100)  
   
   #Report for all vms  
   $report = New-Object psobject  
   $report | Add-Member -MemberType NoteProperty -Name "VMName" -Value $VM.Name  
   $report | Add-Member -MemberType NoteProperty -Name "Free(MB)/Total(MB)" -Value $SpaceOverview  
   $report | Add-Member -MemberType NoteProperty -Name "%Free" -Value $PercentFree  
     
   #VMs with less space on C Drive  
   if ($report."%free" -lt 20) {  
     $finalResult += $report  
   }  
 }  
   
 #HTML format  
 $a = "<style>"  
 $a = $a + "BODY{background-color:peachpuff;}"  
 $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"  
 $a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"  
 $a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod}"  
 $a = $a + "</style>"  
   
 #Send Email  
 $messageParameters = @{  
 Subject = "Alert! VMs with less than 20% on C drive"  
 Body = $finalResult | ConvertTo-HTML -head $a -Body "<H2>VMs with less than 20% on C drive</H2>"  
 From = "SpaceAlert@email.com"  
 To = "Employee@email.com"  
 SmtpServer = "smtp.exchange.com"  
 }
Send-MailMessage @MessageParameters  

Warning: All the testings are performed in lab environment.

Saturday, April 12, 2014

Download logs from all esxi host to desktop to review it later

I got some issue within my virtual environment, and found something suspicious in the ESXi logs.

But due to limited time I was not able to review the logs on the other esxi server. here I have created a script to download logs from all esxi host to your desktop or shared location. which will be helpful to review them later. 

I have used pscp.exe (kept under c:\windows\system32 folder) tool to connect to download logs.

  #####################################   
  ## http://kunaludapi.blogspot.com   
  ## Version: 1   
  ## Tested this script on   
  ## 1) Powershell v3   
  ## 2) Powercli v5.5   
  ## 3) Vsphere 5.x   
  #####################################  
$vcenteruser = "domain\user"
$vcenterpasswd = "Password"
$vCenterServer = "vCenterserver"

Connect-VIServer -Server $vCenterServer -User $vcenteruser -Password $vcenterpasswd    

 $iplist = Get-VMHost  
 $password = "Newsecret"   
 $user = "root"   
  foreach ($ip in $iplist) {   
   mkdir "c:\temp\logs\$ip"  
   cd "c:\temp\logs\$ip"  
   $SSHservice = Get-VMHost $ip | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"}   
   if ($SSHservice.Running -eq $False) {   
    Get-VMHost $ip | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"} | Start-VMHostService     
   }   
   
   $filesource = "/var/log/*"   
   $filedestination = "c:\temp\"  
   $source = $filedestination+$ip+"\vmkwarning.log"  
   $remoteserver = $user+"@"+$ip  
   $destination = $remoteserver+":"+$filesource  
   $dot = "."  
   Write-output "y" | pscp.exe -r -pw $password $destination $dot  
   Get-VMHost $ip | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"} | Stop-VMHostService -Confirm:$false  
  }   

Warning: All the testings are performed in lab environment.

Shutdown virtual datacenter quickly using script

Warning: All the testings are performed in lab environment, use them at your own risk. This blog is created for knowledge purpose, I will not be responsible for any damage.

I found one question on the vmware community that if it is possible to create a script to graceful shutdown all vm's and Esxi hosts in the vCenter Server

So thought its worth a creating powercli script.


 #####################################  
 ## http://kunaludapi.blogspot.com  
 ## Version: 1  
 ## Tested this script on  
 ##  1) Powershell v3  
 ##  2) Powercli v5.5  
 ##  3) Vsphere 5.x  
 #####################################

Add-PSSnapin vmware.vimautomation.core  
   
 # vCenter username password  
 $vcenteruser = "domain\user"  
 $vcenterpasswd = "Password"  
   
 # esxi host usernamd password  
 $esxiuser = "root"  
 $esxipasswd = "password"  
   
 #add your vcenter hostname /  
 $vCenterServer = "vCenterserver"  
 $vCenterDatabase = "vCenterDatabase"  
   
 #connect vCenter Server  
 Connect-VIServer -Server $vCenterServer -User $vcenteruser -Password $vcenterpasswd  
   
 #Gracefull shutdown all vms except vCenterserver  
 Get-VM | Where-Object {$_.name -ne $vCenterServer -and $_.name -ne $vCenterDatabase} | Shutdown-VMGuest -Confirm:$false  
 Start-Sleep -s 300  
   
 #Shutdown all Hosts except the esxi where vCenterserver is running.  
 #Make sure Vcenter and its database are on same host.  
 Get-VMHost | Where-Object {$_.Name -ne (Get-VM $vCenterServer | Get-VMHost).Name} | Stop-VMHost -Confirm:$false -Force  
 $esxihost = (Get-VM $vCenterServer | Get-VMHost).Name  
 Disconnect-VIServer $vCenterServer -Confirm:$false  
   
 #Connect to esxi host where vCenter and its database is hosting  
 Connect-VIServer -Server $esxihost -User $esxiuser -Password $esxipasswd  
   
 #Shutdown vcenter and database server  
 Get-VM | Shutdown-VMGuest -Confirm:$false  
 Start-Sleep -s 300  
   
 #shutdown last remaing host.  
 Get-VMHost | Stop-VMHost -Confirm:$false -Force  
 Disconnect-VIServer $ -Confirm:$false  

Below screenshot tells you how it will shutdown your vmware virtual datacenter.


Friday, April 4, 2014

vExpert 2014

Corey Romero, John Troyer, and the VMware Social Media & Community Team have named 754 vExperts on On April 1, the vExperts 2014 are announced. For the first time, I have been elected for my modest contribution to the amazing VMware community. I feel proud, honored and humbled at the same time.
Congratulations to all the other vExperts! Let’s continue and make it an awesome 2014.
The announcement and the complete list of vExperts can be found http://blogs.vmware.com/vmtn/2014/04/vexpert-2014-announcement.html
I would like to thank all of you for making this possible.

VMware-vExpert-2014-400x57

Wednesday, January 22, 2014

Calculate csv column data and append it in same CSV.

Calculating your CSV column data (sum)  and appending it at the end.

I have named the csv file data.csv and kept it in c:\temp and the CSV file contents looks like this



After running below script.


 $csv= import-csv c:\temp\Data.csv  
 $Numcpu = $csv.Numcpu | measure-object -sum  
 $MemoryTotalGB = $csv.MemoryTotalGB | measure-object -sum  
 $object = New-Object PSObject  
 $object | Add-Member -Name Name -Value "Total" -MemberType NoteProperty  
 $object | Add-Member -Name NumCpu -Value $Numcpu.sum -MemberType NoteProperty  
 $object | Add-Member -Name MemoryTotalGB -Value $MemoryTotalGB.sum -MemberType NoteProperty  
 $object | Export-Csv c:\temp\Data.csv -Append  





Source: https://communities.vmware.com/message/2337062#2337062


Thursday, January 9, 2014

Install softwares on redhat linux using powershell

After deploying trend micro deep security today, I created new task for my self to install its agent rpm on around 150 linux servers. I am not very good in linux scripting, and thought lets try it from windows powershell. In below script i have used pscp.exe and plink.exe tools to connect to linux server from windows. I have mentioned which fiield in the script you need to edit. Copy script from at the end of this blog.


In the script my notepad contents (ip addresses) are like this.

Commands.txt file contents are as below
Results look like this if you are successful.


You might get error something like below. as first time it will cache linux servers key and store in registry, for this servers you will need to rerun the script, and next time it will be succeeded.

root@ password:
Lost connection
PLINK.EXE : The server's host key is not cached in the registry. You
At line:12 char:26
+     Write-Output "yes" | PLINK.EXE -ssh $remoteserver -P 22 -pw $password -m $co ...
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The server's ho...e registry. You:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 dc2:b4:56:aa:05:9c:a9:b8:4d:af:91:fb
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n)
chmod:
cannot access `/tmp/Agent-RedHat_EL6-9.0.0-2008.x86_64.rpm'
: No such file or directory
error:
open of /tmp/Agent-RedHat_EL6-9.0.0-2008.x86_64.rpm failed: No such file or directory





 #####################################  
 ## http://kunaludapi.blogspot.com  
 ## Version: 1  
 ## Tested this script on  
 ##  1) Powershell v3  
 ##  2) Powercli v5.5  
 ##  3) Vsphere 5.x  
 ##  4) Redhat 6.4
 #####################################    

$iplist = Get-Content -path "c:\temp\iplist.txt"  
 $password = "Extrasecret"  
 $fileSource = "C:\temp\Agent-RedHat_EL6-9-2008.x86_64.rpm"  
 $filedestination = "/tmp/"  
 $user = "root"  
 $command = "C:\temp\commands.txt"  
 foreach ($ip in $iplist) {  
   $remoteserver = $user+"@"+$ip  
   $destination = $remoteserver+":"+$filedestination  
   Write-output $password | PSCP.EXE $fileSource $destination  
   Write-Output "yes" | PLINK.EXE -ssh $remoteserver -P 22 -pw $password -m $command  
 }  


Tuesday, December 31, 2013

Change ssh banner / motd message file on all esxi servers using powercli


I got task to update ssh banner message on all the all esxi servers. (Which shows while logging through ssh). This is an easy task using host profiles. But I thought give a shot with powercli to update all esxi servers.

Here idea is to modify /etc/motd file on esxi server and put your banner text. all this you need to using ssh into esxi host from windows.

Default banner page:
Here I have used plink.exe utility from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html which is command line tool for ssh from windows. I downloaded it and copied it on my c:\windows\system32.

Next I created one text file called motd.txt and put it under c:\scripts folder for easy access and the content of the files are as in the screenshot.
#Note:  You can add line cp /etc/motd /etc/motd.bac on first line to backup motd file.
first line echo "      +=======" > /etc/motd (Be aware - only one greater than sign will replace/overwrite everything in the /etc/motd file)
rest of the lines echo " |        |" >> /etc/motd" (double greater than sign will append data)

Now to ssh into esxi server SSH service must be running, which I have enabled through powercli

Note: I have tested this script in my lab environment first.Make sure password for the all esxi are same.
 #####################################   
  ## http://kunaludapi.blogspot.com   
  ## Version: 1   
  ## Tested this script on   
  ## 1) Powershell v3   
  ## 2) Powercli v5.5   
  ## 3) Vsphere 5.x   
  ####################################  
 $cred = Get-Credential -Message "Vcenter or esxi username and password"  
 Connect-Viserver vcenterserver -Credential $cred  
 Add-PSSnapin vmware.vimautomation.core  
 $command = "C:\scripts\motd.txt"  
 $esxiHosts = Get-VMHost   
 $root = "root"  
 $Passwd = "Newpassword"  
 foreach ($esxiHost in $esxiHosts) {  
   $SSHservice = $esxiHost | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"}  
   if ($SSHservice.Running -eq $False) {  
     $esxiHost | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"} | Start-VMHostService      
   }  
   Write-Output "yes" | plink.exe -ssh root@$esxihost -P 22 -pw $passwd -m $command  
   $esxiHost | Get-VMHostService | where {$psitem.key -eq "tsm-ssh"} | Stop-VMHostService -Confirm:$false  
 }  

Output:

Monday, December 30, 2013

Extended VM inventory using powercli


Here is my another scripts which fetch information about all the VM from vcenter. Information includes internal partitions capacity and remaining, installed OS version v/s configured OS version on settings, vmtools info, vcenter server, rdm info, Nic types, snapshots, etc all this information from one script.

You can save this script to ps1 file and can be export to csv by using export-csv command.

lets assume you copied the code in text file and saved it in "c:\temp" folder with name "vm-inventory.ps1"

PS C:\temp>.\vm-inventory.ps1 | export-csv c:\temp\vmlist.csv -notypeinformation

Note: This script has been tested on Powercli 5.5 and Powershell v3
In second line of this script replace #vcenterserver with your vcenter ip or hostname

Add-PSSnapin vmware.vimautomation.core
Connect-Viserver #vcenterserver   
#####################################  
 ## http://kunaludapi.blogspot.com  
 ## Version: 1  
 ## Tested this script on  
 ##  1) Powershell v3  
 ##  2) Powercli v5.5  
 ##  3) Vsphere 5.x  
 ####################################
 function Get-VMinventory {  
 function Get-RDMDisk {  
   [CmdletBinding()]  
   param (  
     [Parameter(Mandatory=$True)]  
     [string[]]$VMName  
     )  
         $RDMInfo = Get-VM -Name $VMName | Get-HardDisk -DiskType RawPhysical, RawVirtual  
         $Result = foreach ($RDM in $RDMInfo) {  
          "{0}/{1}/{2}/{3}"-f ($RDM.Name), ($RDM.DiskType),($RDM.Filename), ($RDM.ScsiCanonicalName)     
         }  
         $Result -join (", ")  
 }  
 function Get-vNicInfo {  
   [CmdletBinding()]  
   param (  
     [Parameter(Mandatory=$True)]  
     [string[]]$VMName  
     )  
         $vNicInfo = Get-VM -Name $VMName | Get-NetworkAdapter  
         $Result = foreach ($vNic in $VnicInfo) {  
           "{0}={1}"-f ($vnic.Name.split("")[2]), ($vNic.Type)  
         }  
         $Result -join (", ")  
 }  
 function Get-InternalHDD {  
   [CmdletBinding()]  
   param (  
     [Parameter(Mandatory=$True)]  
     [string[]]$VMName  
     )  
         $VMInfo = Get-VMGuest -VM $VMName # (get-vm $VMName).extensiondata  
         $InternalHDD = $VMInfo.ExtensionData.disk   
         $result = foreach ($vdisk in $InternalHDD) {  
           "{0}={1}GB/{2}GB"-f ($vdisk.DiskPath), ($vdisk.FreeSpace /1GB -as [int]),($vdisk.Capacity /1GB -as [int])  
         }  
         $result -join (", ")  
 }  
   foreach ($vm in (get-vm)) {  
     $props = @{'VMName'=$vm.Name;  
           'IP Address'= $vm.Guest.IPAddress[0]; #$VM.ExtensionData.Summary.Guest.IpAddress  
           'PowerState'= $vm.PowerState;  
           'Domain Name'= ($vm.ExtensionData.Guest.Hostname -split '\.')[1,2] -join '.';            
           'vCPU'= $vm.NumCpu;  
           'RAM(GB)'= $vm.MemoryGB;  
           'Total-HDD(GB)'= $vm.ProvisionedSpaceGB -as [int];  
           'HDDs(GB)'= ($vm | get-harddisk | select-object -ExpandProperty CapacityGB) -join " + "            
           'Datastore'= (Get-Datastore -vm $vm) -split ", " -join ", ";  
           'Partition/Size' = Get-InternalHDD -VMName $vm.Name  
           'Real-OS'= $vm.guest.OSFullName;  
           'Setting-OS' = $VM.ExtensionData.summary.config.guestfullname;  
           'EsxiHost'= $vm.VMHost;  
           'vCenter Server' = ($vm).ExtensionData.Client.ServiceUrl.Split('/')[2].trimend(":443")  
           'Hardware Version'= $vm.Version;  
           'Folder'= $vm.folder;  
           'MacAddress' = ($vm | Get-NetworkAdapter).MacAddress -join ", ";  
           'VMX' = $vm.ExtensionData.config.files.VMpathname;  
           'VMDK' = ($vm | Get-HardDisk).filename -join ", ";  
           'VMTools Status' = $vm.ExtensionData.Guest.ToolsStatus;  
           'VMTools Version' = $vm.ExtensionData.Guest.ToolsVersion;  
           'VMTools Version Status' = $vm.ExtensionData.Guest.ToolsVersionStatus;  
           'VMTools Running Status' = $vm.ExtensionData.Guest.ToolsRunningStatus;  
           'SnapShots' = ($vm | get-snapshot).count;  
           'DataCenter' = $vm | Get-Datacenter;  
           'vNic' = Get-VNICinfo -VMName $vm.name;  
           'PortGroup' = ($vm | Get-NetworkAdapter).NetworkName -join ", ";  
           'RDMs' = Get-RDMDisk -VMName $VM.name  
           #'Department'= ($vm | Get-Annotation)[0].value;  
           #'Environment'= ($vm | Get-Annotation)[1].value;  
           #'Project'= ($vm | Get-Annotation)[2].value;  
           #'Role'= ($vm | Get-Annotation)[3].value;  
           }  
     $obj = New-Object -TypeName PSObject -Property $Props  
     Write-Output $obj | select-object -Property 'VMName', 'IP Address', 'Domain Name', 'Real-OS', 'vCPU', 'RAM(GB)', 'Total-HDD(GB)' ,'HDDs(GB)', 'Datastore', 'Partition/Size', 'Hardware Version', 'PowerState', 'Setting-OS', 'EsxiHost', 'vCenter Server', 'Folder', 'MacAddress', 'VMX', 'VMDK', 'VMTools Status', 'VMTools Version', 'VMTools Version Status', 'VMTools Running Status', 'SnapShots', 'DataCenter', 'vNic', 'PortGroup', 'RDMs' # 'Folder', 'Department', 'Environment' 'Environment'  
   }  
 }  
 Get-VMinventory   

Output: 



You can let me know what else can I can add to fetch any other information regarding vm in this script. Keep on checking comment you might find some answers.

extra extended vm inventory using powershell Part 2


Saturday, December 21, 2013

PowerCLI esxi host Physical nic info in nice table format

This powershell script gets information about physical nic CDP, Bandwidth, Duplex, Svswitch or dvswitch connected to etc.. Replace 192.168.33.21 with your vcenter or esxi host FQDN or IP address.

I have tested this script with powershell v3, powercli v5.5 and vsphere 5.x.

 #####################################  
 ## http://kunaludapi.blogspot.com  
 ## Version: 1  
 ## Tested this script on  
 ##  1) Powershell v3  
 ##  2) Powercli v5.5  
 ##  3) Vsphere 5.x  
 #####################################  
   
 Add-PSSnapin VMware.VimAutomation.core  
 Add-PSSnapin VMware.VimAutomation.Vds  
   
 $vCenterCred = Get-Credential -Message "vCenter server or esxi credentials"  
 $vcenterServer = "192.168.33.21"  
   
 Connect-viServer -server $vcenterServer -Credential $vCenterCred  
   
 $Collection = @()  
   
 $Esxihosts = Get-VMHost | Where-Object {$_.ConnectionState -eq "Connected"}  
 foreach ($Esxihost in $Esxihosts) {  
   $Esxcli = Get-EsxCli -VMHost $Esxihost  
   $Esxihostview = Get-VMHost $EsxiHost | get-view  
   $NetworkSystem = $Esxihostview.Configmanager.Networksystem  
   $Networkview = Get-View $NetworkSystem  
       
   $DvSwitchInfo = Get-VDSwitch -VMHost $Esxihost  
   if ($DvSwitchInfo -ne $null) {  
     $DvSwitchHost = $DvSwitchInfo.ExtensionData.Config.Host  
     $DvSwitchHostView = Get-View $DvSwitchHost.config.host  
     $VMhostnic = $DvSwitchHostView.config.network.pnic  
     $DVNic = $DvSwitchHost.config.backing.PnicSpec.PnicDevice  
   }  
     
   $VMnics = $Esxihost | get-vmhostnetworkadapter -Physical   #$_.NetworkInfo.Pnic  
   Foreach ($VMnic in $VMnics){  
       $realInfo = $Networkview.QueryNetworkHint($VMnic)  
       $pNics = $esxcli.network.nic.list() | where-object {$vmnic.name -eq $_.name} | Select-Object Description, Link           
       $Description = $esxcli.network.nic.list()  
       $CDPextended = $realInfo.connectedswitchport  
         if ($vmnic.Name -eq $DVNic) {  
             
           $vSwitch = $DVswitchInfo | where-object {$vmnic.Name -eq $DVNic} | select-object -ExpandProperty Name  
         }  
         else {  
           $vSwitchname = $Esxihost | Get-VirtualSwitch | Where-object {$_.nic -eq $VMnic.DeviceName}  
           $vSwitch = $vSwitchname.name  
         }  
   $CDPdetails = New-Object PSObject  
   $CDPdetails | Add-Member -Name EsxName -Value $esxihost.Name -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name VMNic -Value $VMnic -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name vSwitch -Value $vSwitch -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Link -Value $pNics.Link -MemberType NoteProperty   
   $CDPdetails | Add-Member -Name PortNo -Value $CDPextended.PortId -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Device-ID -Value $CDPextended.devID -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Switch-IP -Value $CDPextended.Address -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name MacAddress -Value $vmnic.Mac -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name SpeedMB -Value $vmnic.ExtensionData.LinkSpeed.SpeedMB -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Duplex -Value $vmnic.ExtensionData.LinkSpeed.Duplex -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Pnic-Vendor -Value $pNics.Description -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name Pnic-drivers -Value $vmnic.ExtensionData.Driver -MemberType NoteProperty  
   $CDPdetails | Add-Member -Name PCI-Slot -Value $vmnic.ExtensionData.Pci -MemberType NoteProperty  
   $collection += $CDPdetails  
   }  
 }  
   
 $Collection | Sort-Object esxname, vmnic | ft *  
   
 Disconnect-VIserver * -confirm:$false  
Output:


I  have written script to pull information from CDP as well as LLDP also check this link.

Save complete virtual PortGroup information Settings - Powercli

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

Saturday, November 16, 2013

Generate random password - Powershell

I have written below script to generate random password with required characters and length. This script helps whenever I want to configure complex passwords to services or any account user.


function Generate-Password {
$alphabets= "abcdefghijklmnopqstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"

$char = for ($i = 0; $i -lt $alphabets.length; $i++) { $alphabets[$i] }

for ($i = 1; $i -le 9; $i++)
{
Write-host -nonewline $(get-random $char)
if ($i -eq 9) { write-host `n }
}
}

Generate-Password



Procedure 
1) To run this script you will require powershell on your OS, on windows 7 it is by default available.
2) Copy this yellow text content to notepad and save it as a .ps1 extenstion. (in my case file name is script.ps1 and file is kept at c:\temp location so path will be c:\temp\script.ps1)
3) Open Powershell (run as administrator)
4) You will need to change executionpolicy of powershell so script can execute. type below command to change it. You will require admin rights for the same.
               Set-executionpolicy unrestricted
Press y to confirm
5) Then run the script which you have stored as a .ps1 with below command. (Read step 2 carefully)
               c:\temp\script.ps1
6) Every time you follow step 5 it will generate different password. 


Powershell AD password (unique) reset and send email