Monday, March 7, 2016

UNITS OF MEMORY

There are two units of memory: - a) Bit or Binary and b) Byte.

BIT- BIT is a short form of Binary Digit. One bit expresses a 1 or 0 in a binary digit.
BYTE- A Byte consists of 8 Bits. A Byte can represent a single character, such as a letter, a digit or a punctuation mark.
1 Character = 1byte = 8bits
1 Kilobyte (KB)      = 1024bytes
1Megabyte (MB)    = 1024kilobytes
1 Gigabyte (GB)     = 1024megabytes
1 Terabyte (TB)      = 1024 Gigabytes
1 Petabyte (PB)       = 1024 Terabytes
1 Exabyte (EB)        = 1024 Petabytes
1 Zettabyte (ZB)      = 1024 Exabytes
1 Yettabyte (YB)     = 1024 Zettabyte

NOTE: - Each 1 and 0 is known as ‘binary digit’ or a ‘bit’.

Sunday, March 6, 2016

Powershell change value inside XML file

[System.Xml.XmlDocument]$file = new-object System.Xml.XmlDocument
$file.load("D:\baba\Launcher.en-US.resx")
$xml_peoples= $file.SelectNodes("/root/data[@name='CompanyName']")
foreach ($person in $xml_peoples) {
   $person.value="baba"
   }
   $file.Save("D:\baba\Launcher.en-US.resx")

VMware PowerCLI create Vlan in vSwitch of all host using standard switch

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential


Foreach ($vmhost in (get-vmhost))
{
 $vswitch3=Get-VirtualSwitch -VMHost  $vmhost.name -name vSwitch0
 $ch=1
 while($ch -le 254)
 {
 $vl="VLAN"+$ch.ToString()

 New-VirtualPortGroup -VirtualSwitch $vswitch3  -Name $vl  -VLanID $ch
 $ch=$ch+1
 }

}

VMware PowerCLI vm vMotion

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential
$a = Get-Date
echo $a.Hour

if($a.Hour -ge 15)
{

    $vms=get-folder -name fol1 |Get-VM
    foreach($item in $vms)
    {


        Get-VM -Name $item.name | Move-VM –Destination (Get-VMHost jockeyhost1)

    }
}

VMware PowerCLI get full vm inventory with all the details like IP, OS,State etc

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
$ErrorActionPreference = "SilentlyContinue"
$vmm=get-vm

foreach($vm in $vmm)
{
$vv=get-vm -name $vm.name | select @{N="IPAddress";E={@($_.guest.IPAddress[0])}}
write-host $vm.Name.ToString(),":",$vm.VMHost.Name.ToString(),":",$vm.Guest.OSFullName.ToString(),":",$vv.IPAddress,":",$vm.Guest.State.ToString(),":",$vm.NumCpu.ToString()
}

VMware PowerCLI get full detail of a vm or list of vm

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “VM Name”
$Sheet.Cells.Item(1,2) = “CPU”
$Sheet.Cells.Item(1,3) = “RAM”
$Sheet.Cells.Item(1,4) = “Status”
$Sheet.Cells.Item(1,5) = “Folder”
$Sheet.Cells.Item(1,6) = “OS”
$Sheet.Cells.Item(1,7) = “HardDisks”
$Sheet.Cells.Item(1,8) = “Total Space”
$Sheet.Cells.Item(1,9) = “Used Space”
$Sheet.Cells.Item(1,10) = “Physical Host”
$Sheet.Cells.Item(1,11) = “|”


$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True

$intRow = 2

$colItems=get-vm
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name

 $powerstate = $objItem.PowerState
If ($PowerState -eq 1) {$power = “Powerd On”}
Else {$power = “Powerd Off”}
$folder1= $objItem.Folder.ToString()
$Guest1 = $objItem.Guest.ToString()
$HardDisks1 = $objItem.HardDisks.Filename

$allhdd=""
$sep=""
foreach($_ in $HardDisks1)
{
$allhdd=$allhdd.ToString() +$sep.ToString()+$_.ToString()
$sep=","

}
$ProvisionedSpaceGB1 = $objItem.ProvisionedSpaceGB.ToString()
$UsedSpaceGB1 = $objItem.UsedSpaceGB.ToString()
$VMHost1 = $objItem.VMHost.Name.ToString()
$Sheet.Cells.Item($intRow,2) = $objItem.NumCPU
$Sheet.Cells.Item($intRow,3) = $objItem.MemoryMB
$Sheet.Cells.Item($intRow,4) = $power
$Sheet.Cells.Item($intRow,5) = $folder1
$Sheet.Cells.Item($intRow,6) = $Guest1
$Sheet.Cells.Item($intRow,7) = $allhdd
$Sheet.Cells.Item($intRow,8) = $ProvisionedSpaceGB1
$Sheet.Cells.Item($intRow,9) = $UsedSpaceGB1
$Sheet.Cells.Item($intRow,10) = $VMHost1

$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()

VMware PowerCLI add 1 TB Thin HDD to a vm

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
#Add 1.7 TB HDD to vm
$vmm=get-folder -name vm-fol1 |get-vm

foreach($vm in $vmm)
{

$ds=get-vm -name $vm| get-datastore


New-HardDisk -vm $vm  -Datastore $ds -StorageFormat Thin -CapacityKB 1.835e+9
}

VMware PowerCLI create Standard Switch and port group

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
#To get information of network adapter of a vm

Get-VM -Name classroom | Get-NetworkAdapter

#To get all the VLAN port groups of a Host including all vsitch
Get-VirtualSwitch -VMHost tech-jockeyhost1 |Get-VirtualPortGroup

Foreach ($Host in (get-vmhost))
{
 $testvs =  New-VirtualSwitch -VMHost $Host -Name vSwitch1 -Nic vmnic3,vmnic4

 New-VirtualPortGroup -VirtualSwitch $testvs  -Name VLAN04  -VLanID 04
 New-VirtualPortGroup -VirtualSwitch $testvs  -Name VLAN05  -VLanID 05
}



VMware PowerCLI vm shutdown by folder

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
$fl=get-folder jockeyfolder1,jockeyfolder2,backupfolder1,prodfolder1

foreach($fol in $fl)
{
write-host "Folder name " $fol
$vm=get-folder -name $fol.name |Get-VM | Where-Object{$_.PowerState -eq "PoweredOn"} |select name
foreach($_ in $vm)
{
write-host $_.name
Shutdown-VMGuest -VM $_.name -Confirm:$false
}
}


VMware PowerCLI set Limit on vm CPU, Memory and Harddisk IOPS

clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential
$vmlist = get-vm

foreach ($vmm in $vmlist)
    {
    $item=get-vm $vmm |select NumCpu,MemoryMB
    $cpulimit=$item.NumCpu*2000
    $ramlimit=$item.MemoryMB+100
    get-VMResourceConfiguration -VM $vmm |Set-VMResourceConfiguration -CPULimitMhz $cpulimit -MemLimitMB $ramlimit
 
 
    $disk = Get-HardDisk -VM $vmm | where {$_.Name -ne "Hard Disk" }
    get-VMResourceConfiguration -VM $vmm | Set-VMResourceConfiguration -Disk $disk -DiskLimitIOPerSecond 38

    write-host $cpulimit
    Write-Host $ramlimit

 
    }

VMware PowerCLI find vm in Datastore if it is not in inventory

#Useful to find vm if its disconnected somehow and don't know where vm is present
$dstore=Get-Datastore
clear
foreach($dss in $dstore)
{
write-host $dss.Name


Get-ChildItem  -Path vmstore:\"UK Datacenter"\$dss |Select-String -Pattern "tech-jockey-vm1"

}

VMware PowerCLI find vmsn, ctk and delta files across LUN

$dstore=Get-Datastore
clear
foreach($dss in $dstore)
{
write-host $dss.Name


$vm=Get-ChildItem -Path vmstore:\"UK Datacenter"\$dss |select name

    foreach($fol in $vm)
    {
    write-host $fol.Name
    $file=$fol.Name



    Get-ChildItem  -Path vmstore:\"UK Datacenter"\$dss\$file|Select-String -Pattern "vmsn"
    Get-ChildItem  -Path vmstore:\"UK Datacenter"\$dss\$file|Select-String -Pattern "delta"
    Get-ChildItem  -Path vmstore:\"UK Datacenter"\$dss\$file|Select-String -Pattern "ctk"

    }
}

VMware PowerCLI All in One Report

write-host "Name -- VMware capacity details script V.1.0.0"
Write-Host "=============================================="
Write-Host""
echo "Loading VMWARE dll..."
for($i=1;$i -le 100;$i++)
{
Start-Sleep -m 50
Write-Host -NoNewline "."
}
Write-Host""
Write-Host""
Add-PSSnapin VMware.VimAutomation.Core
$Admin = Read-Host "Enter user name to connect to VC [domian\username]"
$sysdrv=$env:SystemDrive
if(!(Test-Path -Path $sysdrv\vccred))
{
echo "Crecential folder vccred from system drive has been deleted by someone"
echo "Creating New credential folder"
md $sysdrv\vccred
$SecureString = Read-Host -AsSecureString 'Enter password'
ConvertFrom-SecureString $SecureString > $sysdrv\vccred\securestring.txt
echo "Credential created in the system drive"
echo "Loading credential"
$Password = Get-Content $sysdrv\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
write-host "1. USA vCenter `n2. Japan vCenter `n3. UK vCenter`n"
$ch=read-host "Which vCenter you want to connect[1,2,3] :"
if($ch -eq 1)
{
Connect-VIServer 111.222.71.93 -SaveCredentials -Credential $Credential
}
if($ch -eq 2)
{
Connect-VIServer 55.77.88.62 -SaveCredentials -Credential $Credential
}
if($ch -eq 3)
{
Connect-VIServer 98.67.90.43 -SaveCredentials -Credential $Credential
}
}
else
{
echo "Loading credential"
$Password = Get-Content $sysdrv\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
write-host "1. USA vCenter `n2. Japan vCenter `n3. UK vCenter`n"
$ch=read-host "Which VC you want to connect[1,2,3] :"

if($ch -eq 1)
{
Connect-VIServer 111.222.71.93 -SaveCredentials -Credential $Credential
}

if($ch -eq 2)
{
Connect-VIServer 55.77.88.62 -SaveCredentials -Credential $Credential
}

if($ch -eq 3)
{
Connect-VIServer 98.67.90.43 -SaveCredentials -Credential $Credential
}

}

echo "Rendering Screen ..."
for($i=1;$i -le 100;$i++)
{
Start-Sleep -m 50
Write-Host -NoNewline "."
}
Write-Host""
Write-Host""
clear
write-host "Name -- VMware capacity details script V.1.0.0"
Write-Host "=============================================="
Write-Host""
echo "Please select the Report option from below choices"
echo "___________________________________________________________________________________"
echo "1. VM based report"
echo "2. Host based report"
echo "3. Storage based report"
echo "4. Cluster based report"
echo "___________________________________________________________________________________"
echo ""
$chh= read-host "Enter your choice [1,2,3,4] : "
#vm based report
if($chh -eq 1)
{
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “VM Name”
$Sheet.Cells.Item(1,2) = “CPU”
$Sheet.Cells.Item(1,3) = “RAM”
$Sheet.Cells.Item(1,4) = “Status”
$Sheet.Cells.Item(1,5) = “Folder”
$Sheet.Cells.Item(1,6) = “OS”
$Sheet.Cells.Item(1,7) = “HardDisks”
$Sheet.Cells.Item(1,8) = “Total Space”
$Sheet.Cells.Item(1,9) = “Used Space”
$Sheet.Cells.Item(1,10) = “Physical Host”
$Sheet.Cells.Item(1,11) = “|”
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems=get-vm
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$powerstate = $objItem.PowerState
If ($PowerState -eq 1) {$power = “Powerd On”}
Else {$power = “Powerd Off”}
$folder1= $objItem.Folder.ToString()
$Guest1 = $objItem.Guest.ToString()
$HardDisks1 = $objItem.HardDisks.Filename
$allhdd=""
$sep=""
foreach($_ in $HardDisks1)
{
$allhdd=$allhdd.ToString() +$sep.ToString()+$_.ToString()
$sep=","
}
$ProvisionedSpaceGB1 = $objItem.ProvisionedSpaceGB.ToString()
$UsedSpaceGB1 = $objItem.UsedSpaceGB.ToString()
$VMHost1 = $objItem.VMHost.Name.ToString()
$Sheet.Cells.Item($intRow,2) = $objItem.NumCPU
$Sheet.Cells.Item($intRow,3) = $objItem.MemoryMB
$Sheet.Cells.Item($intRow,4) = $power
$Sheet.Cells.Item($intRow,5) = $folder1
$Sheet.Cells.Item($intRow,6) = $Guest1
$Sheet.Cells.Item($intRow,7) = $allhdd
$Sheet.Cells.Item($intRow,8) = $ProvisionedSpaceGB1
$Sheet.Cells.Item($intRow,9) = $UsedSpaceGB1
$Sheet.Cells.Item($intRow,10) = $VMHost1

$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
}

#host based report
if($chh -eq 2)
{

$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Status”
$Sheet.Cells.Item(1,2) = “Connection”
$Sheet.Cells.Item(1,3) = “CPU Speed (Mhz)”
$Sheet.Cells.Item(1,4) = “Used CPU (Mhz)”
$Sheet.Cells.Item(1,5) = “Storage Partition”
$Sheet.Cells.Item(1,6) = “Hyper Threading”
$Sheet.Cells.Item(1,7) = “Vendor”
$Sheet.Cells.Item(1,8) = “Total RAM”
$Sheet.Cells.Item(1,9) = “Server Model”
$Sheet.Cells.Item(1,10) = “Name”
$Sheet.Cells.Item(1,11) = “DNS Name”
$Sheet.Cells.Item(1,12) = “No of Logical CPU”
$Sheet.Cells.Item(1,13) = “Cluster”
$Sheet.Cells.Item(1,14) = “CPU Type”
$Sheet.Cells.Item(1,15) = “Time Zone”
$Sheet.Cells.Item(1,16) = “ESXi Vesrion”

$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems=Get-VMHost
foreach ($objItem in $colItems)
{
$PowerState1 =$objItem.PowerState.ToString()
$ConnectionState1= $objItem.ConnectionState.ToString()
$CpuTotalMhz1= $objItem.CpuTotalMhz
$CpuUsageMhz1= $objItem.CpuUsageMhz
$DiagnosticPartition1= $objItem.DiagnosticPartition.ToString()
$HyperthreadingActive1= $objItem.HyperthreadingActive
$Manufacturer1= $objItem.Manufacturer
$MemoryTotalMB1= $objItem.MemoryTotalMB
$Model1= $objItem.Model
$Name1= $objItem.Name.ToString()
$NetworkInfo1= $objItem.NetworkInfo.ToString()
$NumCpu1= $objItem.NumCpu.ToString()
$Parent1= $objItem.Parent.ToString()
$ProcessorType1= $objItem.ProcessorType.ToString()
$TimeZone1= $objItem.TimeZone.ToString()
$Version1= $objItem.Version.ToString()
$Sheet.Cells.Item($intRow,1) = $PowerState1
$Sheet.Cells.Item($intRow,2) = $ConnectionState1
$Sheet.Cells.Item($intRow,3) = $CpuTotalMhz1
$Sheet.Cells.Item($intRow,4) = $CpuUsageMhz1
$Sheet.Cells.Item($intRow,5) = $DiagnosticPartition1
$Sheet.Cells.Item($intRow,6) = $HyperthreadingActive1
$Sheet.Cells.Item($intRow,7) = $Manufacturer1
$Sheet.Cells.Item($intRow,8) = $MemoryTotalMB1
$Sheet.Cells.Item($intRow,9) = $Model1
$Sheet.Cells.Item($intRow,10) = $Name1
$Sheet.Cells.Item($intRow,11) = $NetworkInfo1
$Sheet.Cells.Item($intRow,12) = $NumCpu1
$Sheet.Cells.Item($intRow,13) = $Parent1
$Sheet.Cells.Item($intRow,14) = $ProcessorType1
$Sheet.Cells.Item($intRow,15) = $TimeZone1
$Sheet.Cells.Item($intRow,16) = $Version1
$intRow = $intRow + 1
}
$WorkBook.EntireColumn.AutoFit()
}

#storage based report
if($chh -eq 3)
{
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Name”
$Sheet.Cells.Item(1,2) = “Connected”
$Sheet.Cells.Item(1,3) = “Total Space [GB]”
$Sheet.Cells.Item(1,4) = “Free Space [GB]”
$Sheet.Cells.Item(1,5) = “Storage Path”
$Sheet.Cells.Item(1,6) = “Congestion [Millisec]”
$Sheet.Cells.Item(1,7) = “IOControlEnabled”
$Sheet.Cells.Item(1,8) = “Filesystem Type”
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems=Get-Datastore
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$Name1= $objItem.Name.ToString()
$Accessible1 = $objItem.Accessible.ToString()
$CapacityGB1= $objItem.CapacityGB.ToString()
$CapacityMB1 = $objItem.CapacityMB.ToString()
$FreeSpaceGB1= $objItem.FreeSpaceGB.ToString()
$FreeSpaceMB1 = $objItem.FreeSpaceMB.ToString()
$DatastoreBrowserPath1= $objItem.DatastoreBrowserPath.ToString()
$CongestionThresholdMillisecond1 = $objItem.CongestionThresholdMillisecond.ToString()
$StorageIOControlEnabled1= $objItem.StorageIOControlEnabled.ToString()
$Type1 = $objItem.Type.ToString()
$freemb=$objItem.FreeSpaceMB
$allmb=$objItem.CapacityMB
$used1= $allmb - $freemb
$Sheet.Cells.Item($intRow,1) = $Name1
$Sheet.Cells.Item($intRow,2) = $Accessible1
$Sheet.Cells.Item($intRow,3) = $CapacityGB1
$Sheet.Cells.Item($intRow,4) = $FreeSpaceGB1
$Sheet.Cells.Item($intRow,5) = $DatastoreBrowserPath1
$Sheet.Cells.Item($intRow,6) = $CongestionThresholdMillisecond1
$Sheet.Cells.Item($intRow,7) = $StorageIOControlEnabled1
$Sheet.Cells.Item($intRow,8) = $Type1
$intRow = $intRow + 1
}

$WorkBook.EntireColumn.AutoFit()
}

#cluster based report
if($chh -eq 4)
{
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Cluster Name”
$Sheet.Cells.Item(1,2) = “DRS Status”
$Sheet.Cells.Item(1,3) = “Drs Automation Level”
$Sheet.Cells.Item(1,4) = “HA Status”
$Sheet.Cells.Item(1,5) = “HA Failover Level”
$Sheet.Cells.Item(1,6) = “HA Restart Priority”
$Sheet.Cells.Item(1,7) = “Swap File Location”
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2
$colItems=Get-Cluster
foreach ($objItem in $colItems)
{
$Name1=$objItem.Name
$DrsEnabled1=$objItem.DrsEnabled
$DrsAutomationLevel1=$objItem.DrsAutomationLevel.tostring()
$HAEnabled1=$objItem.HAEnabled
$HAFailoverLevel1=$objItem.HAFailoverLevel
$HARestartPriority1=$objItem.HARestartPriority.tostring()
$VMSwapfilePolicy1=$objItem.VMSwapfilePolicy.tostring()
$Sheet.Cells.Item($intRow,1) = $Name1
$Sheet.Cells.Item($intRow,2) = $DrsEnabled1
$Sheet.Cells.Item($intRow,3) = $DrsAutomationLevel1
$Sheet.Cells.Item($intRow,4) = $HAEnabled1
$Sheet.Cells.Item($intRow,5) = $HAFailoverLevel1
$Sheet.Cells.Item($intRow,6) = $HARestartPriority1
$Sheet.Cells.Item($intRow,7) = $VMSwapfilePolicy1
$intRow = $intRow + 1
}

$WorkBook.EntireColumn.AutoFit()
}
echo "Removing temp variables and exiting"
for($i=1;$i -le 50;$i++)
{
Start-Sleep -m 50
Write-Host -NoNewline "."
}

Saturday, March 5, 2016

VMware PowerCLI add postfix to vm name


clear
$folderid=get-folder | get-vm |select name

foreach($vmn in $folderid)
{

$dis=$vmn.name.ToString()+"_expired_by_script"
 Set-VM -VM $vmn.name -Name $dis -Confirm:$false

}

VMware PowerCLI move powered on vm to a specific Folder

$vmm=Get-VMHost jockey-host01 | Get-VM | Where-Object {$_.PowerState -eq "PoweredOn"} |select name


foreach($nvm in $vmm)
{

Move-Vm -VM $nvm.name -Destination(Get-Folder -Name PowerON-VMS)

}

VMware PowerCLI VM Resource Limit Report

#VM Resource Limit Report
clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

clear
   
$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “VM Name”
$Sheet.Cells.Item(1,2) = “No Of Cpu”
$Sheet.Cells.Item(1,3) = “Cpu Limit”
$Sheet.Cells.Item(1,4) = “CPU Share”
$Sheet.Cells.Item(1,5) = “Total Ram”
$Sheet.Cells.Item(1,6) = “RAM Limit”
$Sheet.Cells.Item(1,7) = “RAM Share”
$Sheet.Cells.Item(1,8) = “Disk Detail”

$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True

$intRow = 2

$vmlist = get-vm

foreach ($vmm in $vmlist)
    {
   
    $vmname=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty VM
    $no_of_cpu=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty NumCpuShares
    $cpu_limit=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty CpuLimitMhz
            if($cpu_limit -eq -1)
            {$cpulimit="Unlimited"}else{$cpulimit=$cpu_limit}
    $cpu_share=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty CpuSharesLevel
    $total_ram=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty NumMemShares
    $ram_limit=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty MemLimitMB
            if($ram_limit -eq -1)
            {$ramlimit="Unlimited"}else{$ramlimit=$ram_limit}
    $ram_share=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty MemSharesLevel

    $disk=get-VMResourceConfiguration -VM $vmm| Select -ExpandProperty DiskResourceConfiguration
    $dskdetail=":"
    $flag=1
        foreach($dsk in $disk)
        {
         if($dsk.DiskLimitIOPerSecond -eq -1)
            {
             $dsklimit="Unlimited"
             }
        else
            {
            $dsklimit=$dsk.DiskLimitIOPerSecond
            }
       
        $dsk_share=$dsk.DiskSharesLevel
        $dskdetail=$dskdetail+":Limit of Disk-"+$flag.ToString()+":"+$dsklimit.ToString()+":"
        $flag=$flag+1
        }
     
$Sheet.Cells.Item($intRow,1) = $vmname.tostring()
$Sheet.Cells.Item($intRow,2) = $no_of_cpu.tostring()
$Sheet.Cells.Item($intRow,3) = $cpulimit.tostring()
$Sheet.Cells.Item($intRow,4) = $cpu_share.tostring()
$Sheet.Cells.Item($intRow,5) = $total_ram.tostring()
$Sheet.Cells.Item($intRow,6) = $ramlimit.tostring()
$Sheet.Cells.Item($intRow,7) = $ram_share.tostring()
$Sheet.Cells.Item($intRow,8) = $dskdetail.tostring()

 $intRow = $intRow + 1

    }

$WorkBook.EntireColumn.AutoFit()

Powershell get HP Enclosure details through OA API

#make sure you have HP OA API is installed
$con = Connect-HPOA -OA 172.16.10.20 -Username tech-jockey-Password tech-jock-pass
$ssta = Get-HPOAServerStatus -Bay All $con
$ssta.Blade | Select-Object -Property Bay, Power, CurrentWattageUsed, Health, UnitIdentificationLED, VirtualFan | Format-Table *
Disconnect-HPOA $con
Find-HPOA -Range 172.16.10.10-254 -Role Active
$ssta.Hostname

VMware PowerCLI get detailed VM report in simple way and export to Excel sheet

#VM Report
clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “VM Name”
$Sheet.Cells.Item(1,2) = “CPU”
$Sheet.Cells.Item(1,3) = “RAM”
$Sheet.Cells.Item(1,4) = “Status”
$Sheet.Cells.Item(1,5) = “Folder”
$Sheet.Cells.Item(1,6) = “OS”
$Sheet.Cells.Item(1,7) = “HardDisks”
$Sheet.Cells.Item(1,8) = “Total Space”
$Sheet.Cells.Item(1,9) = “Used Space”
$Sheet.Cells.Item(1,10) = “Physical Host”
$Sheet.Cells.Item(1,11) = “|”
$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2

$colItems=get-vm
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name

 $powerstate = $objItem.PowerState
If ($PowerState -eq 1) {$power = “Powerd On”}
Else {$power = “Powerd Off”}
$folder1= $objItem.Folder.ToString()
$Guest1 = $objItem.Guest.ToString()
$HardDisks1 = $objItem.HardDisks.Filename

$allhdd=""
$sep=""
foreach($_ in $HardDisks1)
{
$allhdd=$allhdd.ToString() +$sep.ToString()+$_.ToString()
$sep=","

}
$ProvisionedSpaceGB1 = $objItem.ProvisionedSpaceGB.ToString()
$UsedSpaceGB1 = $objItem.UsedSpaceGB.ToString()
$VMHost1 = $objItem.VMHost.Name.ToString()
$Sheet.Cells.Item($intRow,2) = $objItem.NumCPU
$Sheet.Cells.Item($intRow,3) = $objItem.MemoryMB
$Sheet.Cells.Item($intRow,4) = $power
$Sheet.Cells.Item($intRow,5) = $folder1
$Sheet.Cells.Item($intRow,6) = $Guest1
$Sheet.Cells.Item($intRow,7) = $allhdd
$Sheet.Cells.Item($intRow,8) = $ProvisionedSpaceGB1
$Sheet.Cells.Item($intRow,9) = $UsedSpaceGB1
$Sheet.Cells.Item($intRow,10) = $VMHost1

$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()

$dt=get-date

$day=$dt.Day.ToString()
$hour=$dt.Hour.ToString()
$min=$dt.Minute.ToString()
$month=$dt.Month.ToString()
$sec=$dt.Second.ToString()
$yr=$dt.Year.ToString()
$filename="VM_Report_"+$day+"_"+$month+"_"+$yr+"_"+$hour+"_"+$min+"_"+$sec

$filepath="C:\jockey\"+$filename+".xlsx"

echo $filepath
echo "1"

$Excel.SaveAs($filepath)
$excel.Close()

VMware PowerCLI Storage report detailed

#Storage Report
clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Name”
$Sheet.Cells.Item(1,2) = “Connected”
$Sheet.Cells.Item(1,3) = “Total Space [GB]”
$Sheet.Cells.Item(1,4) = “Free Space [GB]”
$Sheet.Cells.Item(1,5) = “Storage Path”
$Sheet.Cells.Item(1,6) = “Congestion [Millisec]”
$Sheet.Cells.Item(1,7) = “IOControlEnabled”
$Sheet.Cells.Item(1,8) = “Filesystem Type”

$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True

$intRow = 2

$colItems=Get-Datastore
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$Name1= $objItem.Name.ToString()
$Accessible1 = $objItem.Accessible.ToString()
$CapacityGB1= $objItem.CapacityGB.ToString()
$CapacityMB1 = $objItem.CapacityMB.ToString()
$FreeSpaceGB1= $objItem.FreeSpaceGB.ToString()
$FreeSpaceMB1 = $objItem.FreeSpaceMB.ToString()
$DatastoreBrowserPath1= $objItem.DatastoreBrowserPath.ToString()
$CongestionThresholdMillisecond1 = $objItem.CongestionThresholdMillisecond.ToString()
$StorageIOControlEnabled1= $objItem.StorageIOControlEnabled.ToString()
$Type1 = $objItem.Type.ToString()
$freemb=$objItem.FreeSpaceMB
$allmb=$objItem.CapacityMB
$used1= $allmb - $freemb
$Sheet.Cells.Item($intRow,1) = $Name1
$Sheet.Cells.Item($intRow,2) = $Accessible1
$Sheet.Cells.Item($intRow,3) = $CapacityGB1
$Sheet.Cells.Item($intRow,4) = $FreeSpaceGB1
$Sheet.Cells.Item($intRow,5) = $DatastoreBrowserPath1
$Sheet.Cells.Item($intRow,6) = $CongestionThresholdMillisecond1
$Sheet.Cells.Item($intRow,7) = $StorageIOControlEnabled1
$Sheet.Cells.Item($intRow,8) = $Type1
$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()
$dt=get-date
$day=$dt.Day.ToString()
$hour=$dt.Hour.ToString()
$min=$dt.Minute.ToString()
$month=$dt.Month.ToString()
$sec=$dt.Second.ToString()
$yr=$dt.Year.ToString()
$filename="Storage_Report_"+$day+"_"+$month+"_"+$yr+"_"+$hour+"_"+$min+"_"+$sec

$filepath="C:\jockey\"+$filename+".xlsx"

echo $filepath
echo "1"

$Excel.SaveAs($filepath)
$excel.Close()

VMware PowerCLI get Host(Esxi Host) detailed Report

#Host Report   , make sure MS Excel is installed
clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Status”
$Sheet.Cells.Item(1,2) = “Connection”
$Sheet.Cells.Item(1,3) = “CPU Speed (Mhz)”
$Sheet.Cells.Item(1,4) = “Used CPU (Mhz)”
$Sheet.Cells.Item(1,5) = “Storage Partition”
$Sheet.Cells.Item(1,6) = “Hyper Threading”
$Sheet.Cells.Item(1,7) = “Vendor”
$Sheet.Cells.Item(1,8) = “Total RAM”
$Sheet.Cells.Item(1,9) = “Server Model”
$Sheet.Cells.Item(1,10) = “Name”
$Sheet.Cells.Item(1,11) = “DNS Name”
$Sheet.Cells.Item(1,12) = “No of Logical CPU”
$Sheet.Cells.Item(1,13) = “Cluster”
$Sheet.Cells.Item(1,14) = “CPU Type”
$Sheet.Cells.Item(1,15) = “Time Zone”
$Sheet.Cells.Item(1,16) = “ESXi Vesrion”

$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True

$intRow = 2

$colItems=Get-VMHost
foreach ($objItem in $colItems)
{
$PowerState1 =$objItem.PowerState.ToString()
$ConnectionState1= $objItem.ConnectionState.ToString()
$CpuTotalMhz1= $objItem.CpuTotalMhz
$CpuUsageMhz1= $objItem.CpuUsageMhz
$DiagnosticPartition1= $objItem.DiagnosticPartition.ToString()
$HyperthreadingActive1= $objItem.HyperthreadingActive
$Manufacturer1= $objItem.Manufacturer
$MemoryTotalMB1= $objItem.MemoryTotalMB
$Model1= $objItem.Model
$Name1= $objItem.Name.ToString()
$NetworkInfo1= $objItem.NetworkInfo.ToString()
$NumCpu1= $objItem.NumCpu.ToString()
$Parent1= $objItem.Parent.ToString()
$ProcessorType1= $objItem.ProcessorType.ToString()
$TimeZone1= $objItem.TimeZone.ToString()
$Version1= $objItem.Version.ToString()
$Sheet.Cells.Item($intRow,1) = $PowerState1
$Sheet.Cells.Item($intRow,2) = $ConnectionState1
$Sheet.Cells.Item($intRow,3) = $CpuTotalMhz1
$Sheet.Cells.Item($intRow,4) = $CpuUsageMhz1
$Sheet.Cells.Item($intRow,5) = $DiagnosticPartition1
$Sheet.Cells.Item($intRow,6) = $HyperthreadingActive1
$Sheet.Cells.Item($intRow,7) = $Manufacturer1
$Sheet.Cells.Item($intRow,8) = $MemoryTotalMB1
$Sheet.Cells.Item($intRow,9) = $Model1
$Sheet.Cells.Item($intRow,10) = $Name1
$Sheet.Cells.Item($intRow,11) = $NetworkInfo1
$Sheet.Cells.Item($intRow,12) = $NumCpu1
$Sheet.Cells.Item($intRow,13) = $Parent1
$Sheet.Cells.Item($intRow,14) = $ProcessorType1
$Sheet.Cells.Item($intRow,15) = $TimeZone1
$Sheet.Cells.Item($intRow,16) = $Version1

$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()

$dt=get-date

$day=$dt.Day.ToString()
$hour=$dt.Hour.ToString()
$min=$dt.Minute.ToString()
$month=$dt.Month.ToString()
$sec=$dt.Second.ToString()
$yr=$dt.Year.ToString()
$filename="Host_Report_"+$day+"_"+$month+"_"+$yr+"_"+$hour+"_"+$min+"_"+$sec

$filepath="C:\jockey\"+$filename+".xlsx"

echo $filepath
echo "1"

$Excel.SaveAs($filepath)
$excel.Close()

VMware PowerCLI get vm details from MAC address

$report =@()
Get-VM -name tech-jockey* | Get-View | %{
 $VMname = $_.Name
 $_.guest.net | where {$_.MacAddress -eq "00:88:56:ca:77:78"} | %{
        $row = "" | Select VM, MAC
        $row.VM = $VMname
        $row.MAC = $_.MacAddress
        $report += $row
  }
  }
$report

VMware PowerCLI get Folder wise VM details

clear
$fol_list=get-folder

foreach($_ in $fol_list)
{

    $thisfol=$_.name
    write-host " Folder Name : " $thisfol
    $vms=get-folder -name $thisfol |get-vm |select name
    foreach($item in $vms)
    {
        write-host $item.name
    }
}

Powershell Find user is logged in where

clear
$ErrorActionPreference = "SilentlyContinue"
$net=2
while($net -le 3)
{
$i=2
while($i -le 254)
{
$ipp=$i.ToString()
$ntt=$net.ToString()
$pre="192.168."+$ntt+"." + $ipp
$mn=[Net.IPAddress]::Parse($pre)
write-host $mn
query session /server:$mn
echo "================"
$i=$i+1
}
$net=$net+1
}

Powershell get hostname of entire subnet

clear
$ErrorActionPreference = "SilentlyContinue"
$i=1
while($i -le 255)
{
$ipp=$i.ToString()
$pre="192.168.1." + $ipp
$addr=$pre
[System.Net.Dns]::GetHostbyAddress($addr) |select AddressList, Hostname
$i=$i+1
}

VMware PowerCLI find vm parent folder

clear
$folderid=get-vm -name tech-jockey-vm1,tech-jockey-vm2,tech-jockey-vm3 |select name

foreach($vmn in $folderid)
{
$folderparent=get-view $vmn
$p=get-view $folderparent.Parent
$pp=get-view $p.Parent |select name
write-host "VMname :" $vmn.Name.ToString() ":" "Child Folder :"  $p.Name  ":" "Parent Folder :" $pp.Name
}

VMware PowerCLI check vm disk type (Thin/Thik)

clear
$dd=Get-VM |select name
foreach($vm in $dd)
{

Get-vm $vm.Name | get-harddisk | select Parent,StorageFormat
Write-Host "=========================================================================="
}

VMware PowerCLI find vm is present of not in the inventory after comparing with .csv list

##############################################################################
#create a file named file.csv and format it as below
#
#Name
#vm1
#vm2
#vm3
#
#
##############################################################################
$dd=Import-Csv c:\me\file.csv
foreach($vl in $dd)
{
$vv=""
   
            $vv=get-vm -name $vl.name -ErrorAction SilentlyContinue
         
            if($vv.name -eq $vl.name)
                {
                write-host "found :" $vl.name
                }
                else
                {
                write-host "VM Not Found :" $vl.name
                }
                $vv=""
   
 
}


VMware PowerCLI enable/disable vm network

$vmm=get-vm -name tech-jockey-vm1 |select name

foreach($vmn in $vmm)
{
#to disable the NIC
Get-VM -Name $vmn.name | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$false -confirm:$false
}




# to enable NIC
#Get-VM -Name $vmn.name | Get-NetworkAdapter | Set-NetworkAdapter -Connected:$true -confirm:$false

VMware PowerCLI to get Datastore(LUN) detailed report

# Please note that you will need the VMware powershell plugins and a installed MS Excel on the machine running the code.
clear

$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Name”
$Sheet.Cells.Item(1,2) = “Connected”
$Sheet.Cells.Item(1,3) = “Total Space [GB]”
$Sheet.Cells.Item(1,4) = “Total Space [MB]”
$Sheet.Cells.Item(1,5) = “Free Space [GB]”
$Sheet.Cells.Item(1,6) = “Free Space [MB]”
$Sheet.Cells.Item(1,7) = “Used Space [MB]”
$Sheet.Cells.Item(1,8) = “Storage Path”
$Sheet.Cells.Item(1,9) = “Congestion [Millisec]”
$Sheet.Cells.Item(1,10) = “IOControlEnabled”
$Sheet.Cells.Item(1,11) = “Filesystem Type”

$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True
$intRow = 2

$colItems=Get-Datastore
foreach ($objItem in $colItems)
{
$Sheet.Cells.Item($intRow,1) = $objItem.Name
$Name1= $objItem.Name.ToString()
$Accessible1 = $objItem.Accessible.ToString()
$CapacityGB1= $objItem.CapacityGB.ToString()
$CapacityMB1 = $objItem.CapacityMB.ToString()
$FreeSpaceGB1= $objItem.FreeSpaceGB.ToString()
$FreeSpaceMB1 = $objItem.FreeSpaceMB.ToString()
$DatastoreBrowserPath1= $objItem.DatastoreBrowserPath.ToString()
$CongestionThresholdMillisecond1 = $objItem.CongestionThresholdMillisecond.ToString()
$StorageIOControlEnabled1= $objItem.StorageIOControlEnabled.ToString()
$Type1 = $objItem.Type.ToString()
$freemb=$objItem.FreeSpaceMB
$allmb=$objItem.CapacityMB
$used1= $allmb - $freemb

$Sheet.Cells.Item($intRow,1) = $Name1
$Sheet.Cells.Item($intRow,2) = $Accessible1
$Sheet.Cells.Item($intRow,3) = $CapacityGB1
$Sheet.Cells.Item($intRow,4) = $CapacityMB1
$Sheet.Cells.Item($intRow,5) = $FreeSpaceGB1
$Sheet.Cells.Item($intRow,6) = $FreeSpaceMB1
$Sheet.Cells.Item($intRow,7) = $used1
$Sheet.Cells.Item($intRow,8) = $DatastoreBrowserPath1
$Sheet.Cells.Item($intRow,9) = $CongestionThresholdMillisecond1
$Sheet.Cells.Item($intRow,10) = $StorageIOControlEnabled1
$Sheet.Cells.Item($intRow,11) = $Type1

$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()

VMware PowerCLI create vm in simple way

#vm name is supposed to be here
$vmname="tech-jockey-vm1","tech-jockey-vm2","tech-jockey-vm3"

#Template name is supposed to be here
$TL="RHEL7"
$TW="Windows_Srv_2012"
clear
#Host name is supposed to be here                                          
$host01="tech-jockey-host01"
$host02="tech-jockey-host02"

foreach($vm in $vmname)
{

write-host "Creating VM..."
echo $vm

new-vm -Name $vm -Template $TL -VMHost ( Get-VMHost -Name $host01 ) -Location ( Get-Folder -name New_VM) -Datastore tech-jockey-lun01

#Start-Sleep -s 60
write-host "Created VM..."
echo $vm
}

VMware PowerCLI Cluster detail

# please note that you will need the VMware Powershell plugins and a copy of Excel on the machine running the code.
# MS Excel should be installed
# It will show cluster details
#Cluster Name
#DRS Status
#Drs Automation Level
#HA Status
#HA Failover Level
#HA Restart Priority
#Swap File Location
#Cluster Report
clear
Add-PSSnapin VMware.VimAutomation.Core
$Admin ="tech-jockey\jockey-admin"
$Password = Get-Content c:\vccred\securestring.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $Admin, $Password
Connect-VIServer tech-jockey-vCenter -SaveCredentials -Credential $Credential

$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
$Excel = $Excel.Workbooks.Add()
$Addsheet = $Excel.sheets.Add()
$Sheet = $Excel.WorkSheets.Item(1)
$Sheet.Cells.Item(1,1) = “Cluster Name”
$Sheet.Cells.Item(1,2) = “DRS Status”
$Sheet.Cells.Item(1,3) = “Drs Automation Level”
$Sheet.Cells.Item(1,4) = “HA Status”
$Sheet.Cells.Item(1,5) = “HA Failover Level”
$Sheet.Cells.Item(1,6) = “HA Restart Priority”
$Sheet.Cells.Item(1,7) = “Swap File Location”


$WorkBook = $Sheet.UsedRange
$WorkBook.Font.Bold = $True

$intRow = 2

$colItems=Get-Cluster
foreach ($objItem in $colItems)
{
$Name1=$objItem.Name
$DrsEnabled1=$objItem.DrsEnabled
$DrsAutomationLevel1=$objItem.DrsAutomationLevel.tostring()
$HAEnabled1=$objItem.HAEnabled
$HAFailoverLevel1=$objItem.HAFailoverLevel
$HARestartPriority1=$objItem.HARestartPriority.tostring()
$VMSwapfilePolicy1=$objItem.VMSwapfilePolicy.tostring()
$Sheet.Cells.Item($intRow,1) = $Name1
$Sheet.Cells.Item($intRow,2) = $DrsEnabled1
$Sheet.Cells.Item($intRow,3) = $DrsAutomationLevel1
$Sheet.Cells.Item($intRow,4) = $HAEnabled1
$Sheet.Cells.Item($intRow,5) = $HAFailoverLevel1
$Sheet.Cells.Item($intRow,6) = $HARestartPriority1
$Sheet.Cells.Item($intRow,7) = $VMSwapfilePolicy1
$intRow = $intRow + 1

}

$WorkBook.EntireColumn.AutoFit()

$dt=get-date

$day=$dt.Day.ToString()
$hour=$dt.Hour.ToString()
$min=$dt.Minute.ToString()
$month=$dt.Month.ToString()
$sec=$dt.Second.ToString()
$yr=$dt.Year.ToString()
$filename="Cluster_Report_"+$day+"_"+$month+"_"+$yr+"_"+$hour+"_"+$min+"_"+$sec

$filepath="C:\jockey\"+$filename+".xlsx"

echo $filepath
echo "1"

$Excel.SaveAs($filepath)
$excel.Close()

VMware PowerCLI set multipath policy for all the luns present on physical Host

$hstn=Get-VMHost tech-jockey-host* |select name

clear
foreach($hsst in $hstn)
{
$vvv=Get-VMHost -name $hsst.name  | Get-ScsiLun |select CanonicalName,MultipathPolicy
foreach($vm in $vvv)
{

if($vm.MultipathPolicy -eq "MostRecentlyUsed")
{
write-host $vm.CanonicalName," | "$vm.MultipathPolicy
Get-VMHost -name $hsst.name  | Get-ScsiLun -CanonicalName  $vm.CanonicalName | Set-ScsiLun -MultipathPolicy RoundRobin
}
}
}

Menu driven Active directoty user management through Powershell

clear-host
Import-module ActiveDirectory
echo " Welcome To jockey.com Domain"
echo ""
echo ""

echo "Your Options are"
echo ""
echo ""

echo " 1.Create New User"
echo " 2.Create New Group"
echo " 3.Modify User"
echo " 4.Modify Group"
echo " 5.Delete Object"
echo ""
echo ""
$ch=Read-Host "Enter Your Choice "
if($ch -eq 1)
{



echo ""
echo ""
         $fn=read-host " Enter First Name :"
$ln=read-host " Enter Last Name  :"


$ll=$ln.length

if($ll -gt 4)
{
$fin=$fn.substring(0,1)+$ln.Substring(0,5)

}
else
{
$fin=$fn.substring(0,1)+$ln

}

$Strn=$fin
$StrName="cn="+$Strn
$strClass="User"
$objADSI=[ADSI]"LDAP://ou=test,dc=jockey.com,dc=com"
$objUser=$objADSI.create($strClass,$StrName)



$objUser.put("givenName",$fn)
$objUser.put("sn",$ln)



$objUser.put("DisplayName",$Strn)
$objUser.put("description","this is the new user in jockeydomain")
$objUser.put("physicalDeliveryOfficeName","RQ2")
$objUser.put("telephoneNumber","8888888888")
$phn=$Strn+"@jockey.com.com"
$objUser.put("mail",$phn)
$objUser.put("wwwHomePage","http://google.com")
$objUser.put("profilePath","\\london\profiles\myNewUser")
$objUser.put("scriptPath","logon.vbs")
$objUser.put("homeDirectory","\\london\users\myUser")
$objUser.put("homeDrive","H:")

$objUser.SetInfo()






$objUser.SetInfo()

$a = new-object -comobject wscript.shell
$b = $a.popup("User Created Successfully",0,"jockey.com.com",1)
}
else
{
$a = new-object -comobject wscript.shell
$b = $a.popup("Please Select Correct Option",0,"jockey.com.com",1)
}
$objUser.psbase.InvokeSet("AccountDisabled", $False)
$objUser.SetInfo()



SQL Server backup

"BACKUP DATABASE dummy-db TO DISK ='C:\backup.bak'" > bak.sql

osql -U sa -P dummy-pass -S testdbserver\testdbinstance -i bak.sql

Powershell create secure string password

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Users\administrator> $SecureString = Read-Host -AsSecureString 'Enter password'
Enter password: **************

PS C:\Users\administrator> $SecureString
System.Security.SecureString

PS C:\Users\administrator> ConvertFrom-SecureString $SecureString

01000000d08c9ddf0115d1118c7a00c04fc297eb0100000099e2f79c9fed634eaf83589ff64d2480000000000200000000000366
000003b556d623f8680402e7ed65f46c7eb670000000004800000a0000000100000004f9320384e717f68e8bd5df2548d4519200


PS C:\Users\administrator> ConvertFrom-SecureString $SecureString >jockey.TXT
PS C:\Users\administrator> START jockey.TXT

Powershell create GUI form

[void][reflection.assembly]::LoadWithPartialName(“System.Windows.Forms”)
$form = new-object Windows.Forms.Form
$form.Text = “tech-jockey”
$button = new-object Windows.Forms.Button
$button.text=”Hello Jockey”
$button.Dock=”fill”
$button.add_click({$form.close()})
$form.controls.add($button)
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()

Powershell get CPU time interval sample

Get-counter "\Processor(*)\% Processor Time" -SampleInterval 1 -MaxSamples 20 | Export-counter -Path c:\data1.blg

Powershell Find machine is physical or vm

(get-wmiobject win32_computersystem).model

Powershell Open website

$global:ie = New-Object -com "InternetExplorer.Application"
$global:ie.Navigate("http://192.168.1.100/dummy_site")
$global:ie.visible = $true

Powershell NT rights management

Real Life Scenario
I need to change 300 something computers/servers to where the Deny Access from the network includes three users.
Well that’s simple- there is a group policy item for that! Perfect..however sometimes you may not have the appropriate rights to administer group policy, maybe you searched and found this article because of that?
Anyways- this is the powershell way to automate!
For this example, I’ve used a list of computers instead of the AD because I was given a list.


$computers = Get-Content c:\computerlist.txt

foreach ($computer in $computers)
{
ntrights.exe -m \\$computer -u firstUser +r SeDenyNetworkLogonRight
ntrights.exe -m \\$computer -u secondUser +r SeDenyNetworkLogonRight
ntrights.exe -m \\$computer -u thirdUser +r SeDenyNetworkLogonRight
}


Powershell Instantly get free space in GB in C:\ drive

Disable system hibernation
If you don’t use Hibernation but it is activated, you can recover some few gigabytes. The file C:\hyberfil.sys is usually pretty huge (about 75% of the total amount of RAM) so no need to keep that kind of file, especially if you got a lot of RAM. To delete this file, simply disable hibernation in the Advanced Power Settings in the Control Panel or by typing this command :

1
powercfg -h off

Powershell working with Access control list and permission

Param($Server = 'jocket-test-server')
  $ShareSecurity = Get-WmiObject win32_LogicalShareSecuritySetting -ComputerName $Server
  foreach($Share in $ShareSecurity)
  {
    $sharenames = $Share.Name
    $ACLS = $Share.GetSecurityDescriptor().Descriptor.DACL
    foreach($ACL in $ACLS)
    {
    $User = $ACL.Trustee.Name
    switch ($ACL.AccessMask)
      {
      2032127   {$Perm = “Full Control”}
      1245631   {$Perm = “Change”}
      1179817   {$Perm = “Read”}
      }
    $myObj = “” |Select-Object ShareName,User,Permission, NTFS_User, NTFS_Rights
    $myObj.ShareName = $sharenames
    $myObj.User = $User
    $myObj.Permission = $Perm
    $myObj
    }
    }

Powershell Get list of all installed software including Windows update KB

Function Get-InstalledSoftware{
Param([String[]]$Computers)
If (!$Computers) {$Computers = $ENV:ComputerName}
$Base = New-Object PSObject;
$Base | Add-Member Noteproperty ComputerName -Value $Null;
$Base | Add-Member Noteproperty Name -Value $Null;
$Base | Add-Member Noteproperty Publisher -Value $Null;
$Base | Add-Member Noteproperty InstallDate -Value $Null;
$Base | Add-Member Noteproperty EstimatedSize -Value $Null;
$Base | Add-Member Noteproperty Version -Value $Null;
$Results =  New-Object System.Collections.Generic.List[System.Object];

ForEach ($ComputerName in $Computers){
$Registry = $Null;
Try{$Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$ComputerName);}
Catch{Write-Host -ForegroundColor Red "$($_.Exception.Message)";}

If ($Registry){
$UninstallKeys = $Null;
$SubKey = $Null;
$UninstallKeys = $Registry.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Uninstall",$False);
$UninstallKeys.GetSubKeyNames()|%{
$SubKey = $UninstallKeys.OpenSubKey($_,$False);
$DisplayName = $SubKey.GetValue("DisplayName");
If ($DisplayName.Length -gt 0){
$Entry = $Base | Select-Object *
$Entry.ComputerName = $ComputerName;
$Entry.Name = $DisplayName.Trim();
$Entry.Publisher = $SubKey.GetValue("Publisher");
[ref]$ParsedInstallDate = Get-Date
If ([DateTime]::TryParseExact($SubKey.GetValue("InstallDate"),"yyyyMMdd",$Null,[System.Globalization.DateTimeStyles]::None,$ParsedInstallDate)){
$Entry.InstallDate = $ParsedInstallDate.Value
}
$Entry.EstimatedSize = [Math]::Round($SubKey.GetValue("EstimatedSize")/1KB,1);
$Entry.Version = $SubKey.GetValue("DisplayVersion");
[Void]$Results.Add($Entry);
}
}
}
}
$Results
}

Function Get-InstalledSoftware{
Param([String[]]$Computers)
If (!$Computers) {$Computers = $ENV:ComputerName}
$Base = New-Object PSObject;
$Base | Add-Member Noteproperty ComputerName -Value $Null;
$Base | Add-Member Noteproperty Name -Value $Null;
$Base | Add-Member Noteproperty Publisher -Value $Null;
$Base | Add-Member Noteproperty InstallDate -Value $Null;
$Base | Add-Member Noteproperty EstimatedSize -Value $Null;
$Base | Add-Member Noteproperty Version -Value $Null;
$Base | Add-Member Noteproperty Wow6432Node -Value $Null;
$Results =  New-Object System.Collections.Generic.List[System.Object];

ForEach ($ComputerName in $Computers){
$Registry = $Null;
Try{$Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$ComputerName);}
Catch{Write-Host -ForegroundColor Red "$($_.Exception.Message)";}

If ($Registry){
$UninstallKeys = $Null;
$SubKey = $Null;
$UninstallKeys = $Registry.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Uninstall",$False);
$UninstallKeys.GetSubKeyNames()|%{
$SubKey = $UninstallKeys.OpenSubKey($_,$False);
$DisplayName = $SubKey.GetValue("DisplayName");
If ($DisplayName.Length -gt 0){
$Entry = $Base | Select-Object *
$Entry.ComputerName = $ComputerName;
$Entry.Name = $DisplayName.Trim();
$Entry.Publisher = $SubKey.GetValue("Publisher");
[ref]$ParsedInstallDate = Get-Date
If ([DateTime]::TryParseExact($SubKey.GetValue("InstallDate"),"yyyyMMdd",$Null,[System.Globalization.DateTimeStyles]::None,$ParsedInstallDate)){
$Entry.InstallDate = $ParsedInstallDate.Value
}
$Entry.EstimatedSize = [Math]::Round($SubKey.GetValue("EstimatedSize")/1KB,1);
$Entry.Version = $SubKey.GetValue("DisplayVersion");
[Void]$Results.Add($Entry);
}
}

If ([IntPtr]::Size -eq 8){
                $UninstallKeysWow6432Node = $Null;
                $SubKeyWow6432Node = $Null;
                $UninstallKeysWow6432Node = $Registry.OpenSubKey("Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall",$False);
                    If ($UninstallKeysWow6432Node) {
                        $UninstallKeysWow6432Node.GetSubKeyNames()|%{
                        $SubKeyWow6432Node = $UninstallKeysWow6432Node.OpenSubKey($_,$False);
                        $DisplayName = $SubKeyWow6432Node.GetValue("DisplayName");
                        If ($DisplayName.Length -gt 0){
                        $Entry = $Base | Select-Object *
                            $Entry.ComputerName = $ComputerName;
                            $Entry.Name = $DisplayName.Trim();
                            $Entry.Publisher = $SubKeyWow6432Node.GetValue("Publisher");
                            [ref]$ParsedInstallDate = Get-Date
                            If ([DateTime]::TryParseExact($SubKeyWow6432Node.GetValue("InstallDate"),"yyyyMMdd",$Null,[System.Globalization.DateTimeStyles]::None,$ParsedInstallDate)){                    
                            $Entry.InstallDate = $ParsedInstallDate.Value
                            }
                            $Entry.EstimatedSize = [Math]::Round($SubKeyWow6432Node.GetValue("EstimatedSize")/1KB,1);
                            $Entry.Version = $SubKeyWow6432Node.GetValue("DisplayVersion");
                            $Entry.Wow6432Node = $True;
                            [Void]$Results.Add($Entry);
                        }
                        }
                }
                }
}
}
$Results
}

Powershell folder mirroring

#creating scheduled task to sync folder every one minute
schtasks /create /RU jockeygrp\baba /RP Ethic@@!!! /TN newtesttask /TR "robocopy d:\datasrc d:\datadest" /sc MINUTE /mo 01





#for delete this task


schtasks /delete /TN "newtesttask" /f



schtasks /create /RU jockeygrp\baba /RP Ethic@@!!! /TN newtesttask /TR "robocopy d:\datasrc d:\datadest /copyall /mir" /sc MINUTE /mo 01

Powershell check disk activities

Clear-Host
$numRep=3
$Sleep=5
$Idle1=$DiskTime1=$T1=$Idle2=$DiskTime2=$T2=$numRep=3

for ($i=1; $i -le $numRep; $i++)
{
$Disk = Get-WmiObject -class Win32_PerfRawData_PerfDisk_LogicalDisk `
-filter "name= '_Total' "
[Double]$Idle1 = $Disk.PercentIdleTime
[Double]$DiskTime1 = $Disk.PercentDiskTime
[Double]$T1 = $Disk.TimeStamp_Sys100NS

start-Sleep $Sleep

$Disk = Get-WmiObject -class Win32_PerfRawData_PerfDisk_LogicalDisk `
-filter "name= '_Total' "
[Double]$Idle2 = $Disk.PercentIdleTime
[Double]$DiskTime2 = $Disk.PercentDiskTime
[Double]$T2 = $Disk.TimeStamp_Sys100NS

"Repetition $i ... counting to $numRep..."

$PercentIdleTime =(1 - (($Idle2 - $Idle1) / ($T2 - $T1))) * 100
"`t Percent Disk Idle Time is " + "{0:n2}" -f $PercentIdleTime
$PercentDiskTime =(1 - (($DiskTime2 - $DiskTime1) / ($T2 - $T1))) * 100
"`t Percent Disk Time is " + "{0:n2}" -f $PercentDiskTime

}

Powershell IIS Website, AppPool management/automation

$strSvr = "test-pc"

    New-PSSession $strSvr

Write-host " starting server connection"
    Enter-PSSession -ComputerName $strSVR

write-host " ending server connection"

    $strName = "tech-jockey.com"
    $strUsr=   "tech-jockey.com\jockey"
    $strPass = "teremeresapne@123"
    $strPath = "c:\newsite"
    $strNewURL = ""

    #Load WebAdmin Snap-in if needed.
    $iisVersion = Get-ItemProperty "HKLM:\software\microsoft\InetStp";
    if ($iisVersion.MajorVersion -eq 7)
    {
        if ($iisVersion.MinorVersion -ge 5)
        {
            Import-Module WebAdministration;
        }        
        else
        {
            if (-not (Get-PSSnapIn | Where {$_.Name -eq "WebAdministration";}))
            {
                        Add-PSSnapIn WebAdministration;
            }
        }
    }
write-host "creating application pool"
    #Create App Pool
    $AppPoolName="NewWebsitePool"
    New-WebAppPool -Name $AppPoolName
    Set-ItemProperty ("IIS:\AppPools\" + $AppPoolName) -name processModel.identityType -value 3
    Set-ItemProperty ("IIS:\AppPools\" + $AppPoolName) -name processModel.username -value $strUsr

    Set-ItemProperty ("IIS:\AppPools\" + $AppPoolName) -name processModel.password -value $strPass

   write-host "creating website"
    #Create Web Site
    $WebSiteName="NewWebSite"
    New-Website –Name $WebSiteName –Port 81 –HostHeader $strNewURL –PhysicalPath $strPath
    Set-ItemProperty ("IIS:\Sites\" + $WebSiteName) -name applicationPool -value $AppPoolName
    Set-ItemProperty ("IIS:\Sites\" + $WebSiteName) -name ..username -value $strUsr
    Set-ItemProperty ("IIS:\Sites\" + $WebSiteName) -name ..password -value $strPass
   write-host "ending connection"


    #Exit Remote Session
    Exit-PSSession
    Remove-PSSession -ComputerName $strSvr
Import-Module WebAdministration
start-website -Name $WebSiteName

Powershell compare two files

$file1=import-csv -path "C:\tech-jockey\test1.csv"
$file2=import-csv -path "C:\tech-jockey\test2.csv"
$r=Compare($file1 $file2)
if ($r -eq 0)
{
write-host "equal"
}
else
{
write-host "not equal"
}

Powershell prevent anything from Copy and lock clipboard

for ($nk=10; $nk -le 60000; $nk++)
{
powershell -NoProfile -STA -Command {
Add-Type -Assembly PresentationCore
[Windows.Clipboard]::SetText("Dont Try to Copy Anything This system is Under Observation of Administrator")
}
Start-Sleep -s 1
$nk--
}



Powershell set LDAP user default password from csv list

$user = 'abc\testadmin'
$pass = 'passtest'
$login = New-Object System.Management.Automation.PSCredential -ArgumentList @($user,(ConvertTo-SecureString -String $pass -AsPlainText -Force))

Import-Module ActiveDirectory
$list=IMPORT-CSV "C:\myLdap\ldapuserlist.csv"
echo "Setting pasword"
foreach($_ in $list)
{
$Uname="cn=" + $_.UserName + ",CN=Users,DC=tech-jockey,DC=com"

Set-ADAccountPassword –Identity $Uname -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "default-password" –Force) -Partition "DC=tech-jockey,DC=com" -Credential $login -server 192.168.1.100:78910

Enable-ADAccount -Identity $Uname  -Credential $login -Partition "DC=tech-jockey,DC=com" -server 192.168.1.100:78910
}
echo "Completed"

Powershell create,start and delete service at remote computer


SET user=abc\testadmin
SET pass=mypass

sc \\testcomputer123.tech-jockey.com create "DummyAspService" binpath= D:\DummyAspService\DummyAspService.exe start= auto OBJ= %user% PASSWORD= %pass%


sc \\testcomputer123.tech-jockey.com START "DummyAspService" OBJ= %user% PASSWORD= %pass%


sc \\testcomputer123.tech-jockey.com Delete "DummyAspService" OBJ= %user% PASSWORD= %pass%

Powershell working on remote process and web service/server

$user = 'abc\testadmin'
$pass = 'passtest'
$login = New-Object System.Management.Automation.PSCredential -ArgumentList @($user,(ConvertTo-SecureString -String $pass -AsPlainText -Force))

#in below code we are bypassing excution policy to prevent popup
Invoke-Command -ComputerName testcomputer123 -ScriptBlock {set-executionpolicy bypass –force;\\testcomputer123\execfiles\stopkill.ps1} -Credential $login


#In stopkill.ps1 we will write below code to start and stop website,not only website we can even kill any process or and service even shutdown machine

#stopkill.ps1
Import-Module WebAdministration
kill -Name "TestASPDOTNET_DUMMY_Service" -Force
stop-website -Name "Default web Site"
start-website -Name "Default web Site"

Powershell Remoting in simple way

$user = 'abc\testadmin'
$pass = 'abcpassword'
$login = New-Object System.Management.Automation.PSCredential -ArgumentList @($user,(ConvertTo-SecureString -String $pass -AsPlainText -Force))

#In above line we have created credential to login which has access to remote location
#make sure that psremoting is enable at both side
#make sure abc\testadmin has right permission on 192.168.1.100


start-process \\192.168.1.100\hello.bat -Credential $login #it will trigger hello.bat at remote location

Invoke-Command -ComputerName testcomputer1 -ScriptBlock { \\192.168.1.100\bye.bat } -Credential  $login #it will trigger bye.bat at remote location

Invoke-Command -ComputerName testcomputer1 -ScriptBlock { \\192.168.1.100\InstallHyper-V.ps1 } -Credential  $login #it will trigger .ps1 file at remote location

Powershell get file and folder details, count size of local/network location

set-location D:\data #set the location from where need to perform command
#below command will list details of all the folder and files which are there in d:\data it will show last writetime ,creation time etc
get-childitem *.* | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} | select-object LastWriteTime, CreationTime, Name, Length >> D:\status.txt


set-location \\192.168.1.100 #doing same to shared location
get-childitem *.* | sort-object @{Expression={$_.LastWriteTime-$_.CreationTime}; Ascending=$false} | select-object LastWriteTime, CreationTime, Name, Length >> D:\netstatus.txt


set-location D:\countfile
$fileCount=(get-childitem).count #it will count no of item at specific location and share output in txt file
$fileCount >> D:\statuscount.txt




set-location D:\networkshare #below script will show details with size in MB and other details
$abs=Get-ChildItem |
Format-Table  -AutoSize Mode, LastWriteTime, Name,
     @{ Label="Length"; alignment="Left";
       Expression={
                    if($_.PSIsContainer -eq $True)
                        {((New-Object -com  Scripting.FileSystemObject).GetFolder( $_.FullName).Size)/1024/1024
echo "MB"
}

                    else
                        {$_.Length}
                  }
     };
$abs >> D:\statusfol\size.txt

Create notepad Virus

Create a batch file with .BAT extention and put below lines and save it

@ECHO off
:top
START %SystemRoot%\system32\notepad.exe
GOTO top

Powershell script to LogOff computer if LAN cable disconnected

On Error Resume Next

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
While(1)
arrComputers = Array("localhost")
For Each strComputer In arrComputers
 

   Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
   Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter where NetConnectionID='raj'", "WQL", _
                                          wbemFlagReturnImmediately + wbemFlagForwardOnly)

   For Each objItem In colItems
         
     
      if(objItem.NetConnectionStatus=7)then

Set WSHShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "C:\WINDOWS\system32\logoff"
end if

     
   Next
next


   
Wend

Powershell get network information

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer)
Set colItems = objWMIService.InstancesOf("Win32_NetworkAdapter")
For Each objItem in colItems
Wscript.Echo objItem.Description
Wscript.Echo objItem.NetConnectionStatus
Next

Create Fool Virus

Set wshShell = wscript.CreateObject("WScript.Shell")
do
wscript.sleep 100
wshshell.sendkeys "You are a fool."
loop


save file as .vbs extention

Create Enter key Virus

Set wshShell = wscript.CreateObject("WScript.Shell")
do
wscript.sleep 100
wshshell.sendkeys "~(enter)"
loop


save file as .vbs extention

How to create BackSpace Virus

MsgBox "Let's go back a few steps"
Set wshShell =wscript.CreateObject("WScript.Shell")
do
wscript.sleep 100
wshshell.sendkeys "{bs}"
loop

save file as .vbs extention

Powershell Modify user properties

$objuser=[ADSI]"LDAP://cn=user1,ou=test,dc=tech-jockey,dc=com"
$objuser.Put("Samaccountname","user1")
$objuser.Put("givenname","myuser")
$objuser.Put("initials","raj")
$objuser.Put("sn","User")
$objuser.Put("displayname","new user")
$objuser.Put("description","user created by ldap")
$objuser.Put("telephoneNumber","8888888888")
$objuser.Put("mail","abcd@gmail.com")
$objuser.Put("wwwhomepage","http://www.google.com")
$objuser.setinfo()

Delete user by powershell

$strclass="user"
$strname="cn=user1"
$objadsi=[ADSI]"LDAP://ou=test,dc=tech-jockey,dc=com"
$objuser=$objadsi.delete($strclass,$strname)

Create user in powershell

$strclass="User"
$strname="cn=user1"
$objadsi=[ADSI]"LDAP://ou=test,dc=tech-jockey,dc=com"
$objuser=$objadsi.create($strclass,$strname)
$objuser.Put("sAMAccountName","user1")
$objuser.setinfo()

Create OU in powershell

$strClass="organizationalUnit"
$StrOUName="ou=test"
$objADSI=[ADSI]"LDAP://dc=tech-jockey,dc=com"
$objOU=$objADSI.create($strClass,$StrOUName)
$objOU.setInfo()

Magic of DOS

telnet towel.blinkenlights.nl

PowerShell Logo


Thursday, March 3, 2016

ESXi Open Network Ports

A limited number of network ports are open on ESXi. The most
important ports and services are the following:
80 — This port serves a reverse proxy that is open only to
display a static Web page that you see when browsing to the
server. Otherwise, this port redirects all traffic to port 443 to
provide SSL-encrypted communications to the ESXi host.
443 (reverse proxy) — This port also acts as a reverse proxy to
a number of services to provide SSL-encrypted communica
-
tion to these services. The services include the
VMware Virtual
Infrastructure API (VI API)
, which provides access to the RCLIs,
VI Client, VirtualCenter Server, and the SDK.
427 (service location protocol) — This port provides access for
the service location protocol, a generic protocol to search for
the VI API.
5989 — This port is open for the CIM server, which is an inter
-
face for Third-party management tools.
902 — This port is open to support the older VIM API, specifi
-
cally the older versions of the VI Client and VirtualCenter.

Time synchronize in windows server

1. Use Google, Bing, or other preferred search engine to locate trusted NTP time servers. These are typically provided by government or other network organizations.

2. Log onto the domain controller with administrative credentials and launch a command prompt

3. Stop the time service with the following command: net stop w32time

4. Enter the following command to configure the NTP time servers: w32tm /config /syncfromflags:manual /manualpeerlist:”time server 1, time server 2, time server 3” then hit enter. The command should complete successfully.

5. Inform the domain controller that these are trusted server with the following command: w32tm /config /reliable:yes

6. Restart the time service: net start w32time

7. Review the results by entering: w32tm /query /configuration

8. Ensure the settings are the desired ones. Then close the command prompt. The NTP servers have now been configured.

Check list of VMs exists in vCenter or not

Solution -- Created by tech-jockey on OCT 9 2015
Usecase:-
In a situation when you are handeling large virtualized environment and you have for example 5000 of vms running.
Your manager gives you list of 600 vms and asking you to verify whether they are running or not.
If you decided to do it manually in vCenter then you are wasting time.
Use below script to get this thing done in one shot
1. Create a csv file and put the vm names there like below
_______________
Name
vm1
vm2
vm3
vm4
_______________
2. save it as file.csv or anyname which you want
3. Use below script which will check and show whether vm found or not found after doing comparison from your sheet.
$dd=Import-Csv c:\neeraj\file.csv #importing your file.csv file to get list of vms
foreach($vl in $dd)
{
$vv=""
$vv=get-vm -name $vl.name -ErrorAction SilentlyContinue #for any other error it will ignore
if($vv.name -eq $vl.name)
{
write-host "found :" $vl.name
}
else
{
write-host "VM Not Found :" $vl.name
}
$vv=""

#at the end you will see which vm is found which is not found

OpenStack 3 node cluster initial setup

Magical windows command

A magical windows command can do almost all the administrative task.

Press WINKEY+R
Type shell:::{ED7BA470-8E54-465E-825C-99712043E01C}
 Press Enter key
And see the magic

 

OpenStack(devtack version) Installation in Ubuntu 14.4. server

  1. Let’s take a machine with Ubuntu 14.4 server installed in it.
  2. I am assuming minimal installation
  3. You can create git clone of openstack devstack package
  4. First install git by apt-get install git
  5. Now run git command which will create a clone git clone https://git.openstack.org/openstack-dev/devstack
  6. cd devstack; ./stack.sh
These are the steps required to install it but the moment you will start it will show you multiple errors.
The very first error is it will tell you can you can’t run stack.sh in root mode
You can create a user stack and set the password in additional way
#useradd stack;passwd stack
But I recommend to run the script which you can fine in devstack directory which will create required users.
#./tools/create-stack-user.sh
[Note- make sure you have mapped the hostname in DNS , if not put the entry in /etc/hosts file]
Now switch to the user stack and run the script which will show you permission error.
Change the ownership and permission by below command
#chown -R stack:stack /tech-jockey_test/devstack

Now I think it’s time to run the final script but it will create issue and give you error that it is not able to download the package from GIT_BASE=${GIT_BASE:-git://www.github.com}
Now your task is to open a file vim /devstack/stackrc
Go to line no 164 and modify the line as follows(replace git with https).
GIT_BASE=${GIT_BASE:-https://www.github.com}
All set now run the script ./stack.sh it will ask you to enter password for its diff services.
Once you enter the passwords it will take around 20 minute to install the bundle and then you can access openstack by opening its in browser.
This is your host IP address: 192.168.122.123
This is your host IPv6 address: ::1
Horizon is now available at http://dummy_IP/
Keystone is serving at http://Dummy_IP:5000/
The default users are: admin and demo
The password: dummy

Creating iSCSI SAN [Tested]

Guys,
In a VMware environment often i get this requirement when people ask for separate iscsi lun to test MS cluster.
It's mandatory item for quorum disk.
Challenge -- Storage team have their own standard and they don't want any interruption in their standard as it may affect planned capacity.
There are some famous solution in the market which are:-
1. Use StarWind software to create your own private SAN on vm -- this software is free for one month only.
2.Use OpenFiler which is opensource and with many features -- It do not support Microsoft clustering technique, means you can not create quorum disk.
3.Use Nexenta software defined storage -- It is free upto 18TB but configuration is big headache.
4.Attach a disk in Linux and configure it as ISCSI storage -- Management is not friendly
Microsoft released their iSCSI Software Target.
To general they opened up a world of possibilities for smaller companies (as well as IT Pros and hobbyists) who use servers,
but cannot justify spending thousands of dollars on a Storage Area Network (SAN) device.
In this article I will show you how to create a virtual SAN in your environment.
Installing the iSCSI Software Target (available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=45105d7f-8c6c-4666-a305-c8189062a0d0)
or http://www.microsoft.com/en-us/download/details.aspx?id=19867 is a simple process.
It comes as a self-extracting package which installs seamlessly on any Windows Server 2008 R2 operating system (RTM or SP1). Once installed it appears under Administrative Tools.
Before we create our iSCSI Target we will create two VHD files: One as our Witness Disk and one for Shared Storage. Right-click on Devicesand click Create Virtual Disk.
In the Create Virtual Disk Wizard type the full name (including directory structure) of the VHD file you want to create. The Witness Disk does not have to be very big (8GB is my norm), but the Shared Storage Disk should be as large as you would need it to be… depending on what you will be storing it might need to be quite large.
  1. In the Welcomescreen click Next.
  2. In the Filescreen type the name and location of the VHD file you want to create (c:\disks\Witness.vhd) and click Next.
  3. In the Sizescreen enter the size of the VHD in megabytes (for the Witness disk enter 8192) and click Next.
  4. In the Descriptionscreen enter a description (Witness Disk) and click Next.
  5. On the Access screen click leave the fields blank and click Next. We will configure this once we create our Target.
  6. On the Completing the Create Virtual Disk Wizardscreen click Finish.
Make sure to repeat these steps for the Shared Storage disk, changing only the file name, description, and size appropriately.
For each VHD two files will be created – the Virtual Hard Disk file which will be Fixed Disks, and a Microsoft iSCSI Software Target Change Tracking Bitmap file, which is a .cbm file that Microsoft uses for integrity checking.
Now that our storage is allocated we will create our iSCSI Target. To begin we will right-click on iSCSI Targets in the navigation pane and click Create iSCSI Target.
  1. In the Welcome screen click Next.
  2. In the iSCSI Target Identificationscreen enter the name of your iSCSI target. This will be the name of yourLogical Unit Number (LUN). You can also optionally enter a description. Click Next.
NOTE: Although not a requirement, it is a best practice to exclude punctuation, especially periods and dashes, as they are used in the iSCSI Qualified Name (IQN) that will be created by both the target and initiator.
  1. In the iSCSI Initiators Identifiersscreen we will select the Windows machines that will be able to access the iSCSI target. Click on Advanced…to enter the DNS domain name, IP address, MAC address, or multiple pre-determined IQNs. In most cases the iSCSI Initiators of your devices will not have been enabled yet, but by entering their IP address you can save extra steps later.
There are two components of an iSCSI SAN – the target, which is the LUN on the actual SAN device, and the initiator, which is the computer that will be accessing it. Because SANs are commonly used with clusters, it is possible to have several initiators configured to access a single target. However if the target is not configured for the initiator, it will be invisible to that system when it tries to access it.
  1. Click Next on the iSCSI Initiators Identifiersscreen, then click Finishon the Completing the Create iSCSI Target Wizard screen.
At this point your iSCSI target has been created. We can look at the properties by right-clicking on the iSCSI Target we created and clickProperties.
The LUN properties box should have five tabs: General, iSCSI Initiators, Authentication, Virtual Disks, and Advanced.
Under the General tab you will see (for the first time?) your IQN. In the example created for this article it is iqn.1991-05.com.microsoft:ski-storage-lun1-target. This convention may appear long and convoluted, but it can be broken down into two parts… the device manufacturer and the actual target.
Because we are using the iSCSI Software Target, the manufacturer is Microsoft, and because their domain name (microsoft.com) was registered in May of 1991 the first part of our iqn is 1991-05.com.microsoft. (If you had an EMC device, you would have an IQN of iqn.1997-07.com.emcJ
The first part of the IQN is separated from the second part by a colon. The actual target (LUN1) is on a server called Ski-Storage, hence ski-storage-lun1-target.
Under the iSCSI Initiators tab you can see, add, edit, and remove initiators. This will be important if you plan to add new initiators to a cluster, for example.
Under the Authentication tab you can set CHAP (Control Host Authentication Protocol). This is the only method of authentication supported by iSCSI.
Under the Virtual Disks tab we will add our pre-created VHDs.
1) Click Add…
2) Select both disks and click OK.
3) In the LUN Properties screen click OK.
At this point our LUN is created and populated, and ready to go! Now it is a simple matter of pointing our initiators to the device.
In Windows Server, click Start – Administrator Tools – iSCSI Initiator to launch the iSCSI Initiator. If this is the first time you are running it on your server you will be warned that in order to run the Initiator, the Microsoft iSCSI Initiator Service must be running, and that Windows will configure it to auto-start.
In the iSCSI Initiators Properties box there are six tabs: Targets, Discovery, Favorite Targets, Volumes and Devices, RADIUS, and Configuration.
In the Targets tab type the IP address of the server on which you configured your software target, and click Quick-Connect…In the event of a successful connection a Quick Connect window will appear with the IQN of your iSCSI target and the statusConnected in the Status column. Click Done to close the Quick Connect window.
The IQN of your target will now appear in the Discovered Targetslist on the Targets tab.
Click on the Volumes and Devices tab of the iSCSI Initiator Properties window. The Volume List should be blank. Click Auto Configure to automatically configure all of the devices on the discovered target. Two devices should appear.
The rest of what we are doing should be pretty familiar to you.
1) Open Server Manager.
2) Navigate to Disk Management.
There should be two new disks attached to your server.
3) Right-click the 8.00 GB disk and click on-line. Right-click the 64.00 GB disk and click on-line.
4) Right-click the 8.00 GB disk and click Initialize. The Initialize Disk screen should appear, allowing you to select both disks to be initialized. Click OK.
5) Create a Simple Volume on each disk.
  1. On the 8.00 GB disk right-click on the unallocated space and click Create Simple Volume.
  2. In the New Simple Volume Wizardclick Next.
  3. In the Specify Volume Sizescreen click Next.
  4. In the Assign Drive Letter or Pathscreen select Qand click Next.
  5. In the Format Partitionscreen change the Volume Label to Witness Diskand click Next.
  6. On the Completing the New Simple Volume Wizardscreen click Finish.
Repeat the same steps for the 64.00 GB disk, replacing the drive letter with and the label to Shared Storage.
At this point your LUN is created, formatted, and ready for data!

Content of this blog has been moved to GITHUB

Looking at current trends and to make my content more reachable to people, I am moving all the content of my blog https://tech-jockey.blogsp...