Archive

Posts Tagged ‘Scripting’

Installing VMware SDK with Visual Studio 2010 / Visual Studio 2010 Express – workaround

March 31, 2011 Leave a comment

This is just a quick workaround to get the installation done – nothing else (really a reminder to myself)

I have a project to provision VMs from a customised front-end,
I have created a C# tool – that integrates with SCCM as well as our various asset management tools and some scripting environments, to allow for a ‘1 button deployment’

Of course . . to be a true one button deployment, I’d like to be able to actually create a VM when using the same ‘Big Red Button’

Anyway, my development environment happens to be Visual Studio 2010 – so yes simple . . let’s get going, surely we just follow the setup guide provided at :

http://www.vmware.com/support/developer/vc-sdk/visdk400pubs/sdk40setupguide.pdf – page 19

Well, that would work, except that the SDK kit has not yet gotten the relevant batch files for a Visual Studio 2010 installation.

The solution to get the installation working was to get a copy of the amended cmd from the VMWare communities:
http://communities.vmware.com/servlet/JiveServlet/download/1225636-21465/genvimstubs2.cmd
and copy it to your .\sdk\samples\DotNet directory

Next, go to : Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools and select Visual Studio Command Prompt (2010)

Now, make sure that you have the environmental variable VCINSTALLDIR set to point to your Visual Studio installation path (type ‘set’ to see your environmental variables)
I had to set it like this:

SET VSINSTALLDIR="c:\Program Files (x86)\Microsoft Visual Studio 10.0"

Finally, I had to run the installer.]
In my case, the SDK was at d:\VMWare\SDK\samples, so I ran:

D:\VMWare\SDK\samples\DotNet>genvimstubs2.cmd d:\VMWare\SDK\wsdl\vim25 Vim25Api stage Vim25Objects.cs . Vim25Service2005

Installation looks like this:

D:\VMWare\SDK\samples\DotNet>genvimstubs2.cmd d:\VMWare\SDK\wsdl\vim25 Vim25Api
stage Vim25Objects.cs . Vim25Service2005
Checking and Creating stage
The system cannot find the file specified.
Microsoft (R) Web Services Description Language Utility
[Microsoft (R) .NET Framework, Version
2.0.50727.1432]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file ‘stage\Vim25Objects.cs’.
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.4926
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

Microsoft (R) Xml Serialization support utility
[Microsoft (R) .NET Framework, Version
2.0.50727.1432]
Copyright (C) Microsoft Corporation. All rights reserved.
Serialization Assembly Name: Vim25Service2005.XmlSerializers, Version=0.0.0.0, C
ulture=neutral, PublicKeyToken=null.
Generated serialization assembly for assembly D:\VMWare\SDK\samples\DotNet\vim25
service2005.dll –> ‘.\Vim25Service2005.XmlSerializers.dll’.
Optimizing generated stubs…
Microsoft (R) Visual C# 2008 Compiler version 3.5.30729.4926
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

Stub generation Done.
ECHO is off.

From here you can continue using the instructions in the getting started guide above.

Categories: Scripting, VMWare Tags: ,

Function : Get-Function

February 24, 2011 Leave a comment

Here’s a time saver… well a quick function that has saved me a whole herd of time when trying to find a function that has been “forgotten”

Function Get-Function ($searchterm,[switch]$DEFINITION)
{
	$functions = @(Get-Command "*$searchterm*" -CommandType "Function")
	"`nFunctions matching ""$searchterm""`n" | Write-Host -ForegroundColor Green
	if (!$DEFINITION) {$functions | %{$_.name}} else {$functions | %{"`n$($_.name)" | Write-Host -f Yellow ;$_.definition}}
}

sal gf Get-Function

the last line is setting an alias “gf”
– so let’s try this on something familiar… we had a function searching for apps…

Command: gf apps
Output:
Functions matching “apps”
Get-Apps
Get-CoreApps
Get-InstalledApps
Set-InfsApps

Ahh – “installed apps”, let’s try that one again, and get Details this time:

Command: gf installedapps -de
Output:
Functions matching “installedapps”
Get-InstalledApps
param (
$computername=$env:computername,
$regkey_x64 = “SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall”,
$regkey_x86 = “SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall”,
[switch]$DISPLAY,
[switch]$EXCLUDE32,
[switch]$EXCLUDE64
)
$bits_to_search = @()
if (!$EXCLUDE32){$bits_to_search += “x86”}
if (!$EXCLUDE64){$bits_to_search += “x64”}

$apps = @()
foreach ($bit in $bits_to_search)
{
$regkey = Get-Variable “regkey_$bit” | %{$_.value}
if (Test-Path HKLM:$regkey)
{
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(“LocalMachine”,$computername)
$key = $reg.OpenSubKey($regkey)
$SubKeys = $key.GetSubKeyNames() | %{$key.OpenSubKey($_)}

foreach ($subkey in $subkeys)
{
$app = $subkey | select @{N=”Bit”;E={$bit}},`
@{N=”Name”;E={$_.getvalue(‘DisplayName’)}},`
@{N=”Version”;E={$_.GetValue(‘DisplayVersion’)}},`
@{N=”Publisher”;E={$_.GetValue(‘Publisher’)}}
if ($app.name) {$apps += $app}
}
}
$key.Close()
$reg.Close()
}

# Remove duplicates, but annoyingly names like of “C++” error when using “-match”
$unique_apps = @()
foreach ($app in $apps)
{
if (!($unique_apps | ?{$_.Bit -eq $app.bit} | ?{$_.name -eq $app.name} |
?{$_.version -eq $app.version})) {$unique_apps += $app}
}

return $unique_apps | sort bit,name,version

Comparing IPs using Powershell – Script of the Day

February 21, 2011 Leave a comment

Ever needed to script around IP addressing issues on hosts and needed to determine whether 2 hosts are in fact on the same subnet or not?

Try the following Function


Function Compare-Subnets {
param (
[parameter(Mandatory=$true)]
[Net.IPAddress]
$ip1,

[parameter(Mandatory=$true)]
[Net.IPAddress]
$ip2,

[parameter()]
[alias("SubnetMask")]
[Net.IPAddress]
$mask ="255.255.255.0"
)

if (($ip1.address -band $mask.address) -eq ($ip2.address -band $mask.address)) {$true}
else {$false}

}

The code simply does a binary comparison of the 2 IP addresses.

– much like you used to do when you first did TCPIP subnetting (some of you may remember this)

To use it, the syntax is simply as follows

Compare-Subnets -IP1 $IP1 -IP2 $IP2 -mask $SubnetMask

and the return is simply a boolean True or False. – Simple

e.g.PS:115 >Compare-Subnets -ip1 10.2.208.151 -ip2 10.2.208.251 -mask 255.255.255.240
False

Function : Get-InstalledApps

February 16, 2011 Leave a comment

So there I was happily using

gwmi win32_product 

to get me a list of installed applications, but this is slow, and often we just want a quick verification that an application is installed or not.

Thanks to powershell.com and their “PowerTip of the Day” I was reminded about hitting the registry for this information…
So, inspired by their code, I hacked together a quick function to do this.

Note the removal of duplicates was first done as per the concept here Script of the Day – remove duplicate lines in a CSV file but there were a few entries with special characters in their names, eg “C++” that don’t play nicely with “-match” so this was recoded comparing each entry of the object. This is going to be slower, but still solves the “Get Installed Applications” faster than the WMI route!

Function Get-InstalledApps 
{
	param (
		$computername=$env:computername,
		$regkey_x86 = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
		$regkey_x64 = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
		[switch]$DISPLAY
		)

	$apps = @()	
	foreach ($bit in "x86","x64")
	{	
		$regkey = Get-Variable "regkey_$bit" | %{$_.value}
		if (Test-Path HKLM:$regkey)
		{
			$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$computername)
			$key = $reg.OpenSubKey($regkey)
			$SubKeys = $key.GetSubKeyNames() | %{$key.OpenSubKey($_)}
	
			foreach ($subkey in $subkeys)
			{
				$app = $subkey | select @{N="Bit";E={$bit}},`
										@{N="Name";E={$_.getvalue('DisplayName')}},`
										@{N="Version";E={$_.GetValue('DisplayVersion')}},`
										@{N="Publisher";E={$_.GetValue('Publisher')}}
				if ($app.name) {$apps += $app}
				}
			}
		    $key.Close()
		    $reg.Close()
		}
   
	# Remove duplicates, but annoyingly names like of "C++" error when using "-match"
	$unique_apps = @()
	foreach ($app in $apps) 
	{
		if (!($unique_apps | ?{$_.Bit -eq $app.bit} | ?{$_.name -eq $app.name} | 
		?{$_.version -eq $app.version})) {$unique_apps += $app}
	}

return $unique_apps | sort bit,name,version
}

Script of the Day – Creating AD groups without QAD cmdlets

February 10, 2011 1 comment

We’re automating some server builds and need to create AD groups to manage resource access to each Server (company policy)
We use SCCM for deployment and I wanted to automate the groups (at build time)
Also, I did not want to have any dependencies on external Modules (so I want to do this without the quest tools)

I found a few documents online for creating AD groups that went without the quest tools, but found that most did not work.

You see, our key problem was that we wwanted to create Domain Local Security Groups.
In VBScript, this was pretty simple, as on the ‘put’ portion of group creation, you just told the script to apply both Group type constants, using an or statement.
The theory was that this would work in Powershell too (and many online script seemed to indicate that it would) – but the group types being created were inconsistent.

Below are the constants for the different group types:

Value GroupType
2 Global distribution group
4 Domain local distribution group
8 Universal distribution group
-2147483646 Global security group
-2147483644 Domain local security group
-2147483640 Universal security group

So creating a Domain Local Security group is as simple as:

$groupType = -2147483644
$objOU = [ADSI]"LDAP://localhost:389/OU=YourOUName,DC=Example,DC=com"
$GroupName = "MyNewGroup"
$objGroup = $objOU.Create("group", "CN=" + $GroupName)
$objGroup.Put("groupType", $groupType )
$objGroup.Put("sAMAccountName", $GroupName )
$objGroup.SetInfo()

Of course you can change the LDAP binding to a DC (rather than localhost) and you can change the GroupType by amending the value of $GroupType
Even better, you could wrap it into a Function, with a switch statement to take care of Group type selection.

Happy days.

Script of the Day – shutdown your VMware ESX estate with PowerCLI

February 7, 2011 Leave a comment

The following script is straight from
http://www.virtu-al.net/2010/01/06/powercli-shutdown-your-virtual-infrastructure/

I have used it a few times and it is very effective and easy to use.


Connect-VIServer MyVIServer

# Get All the ESX Hosts
$ESXSRV = Get-VMHost

# For each of the VMs on the ESX hosts
Foreach ($VM in ($ESXSRV | Get-VM)){
# Shutdown the guest cleanly
$VM | Shutdown-VMGuest -Confirm:$false
}

# Set the amount of time to wait before assuming the remaining powered on guests are stuck
$waittime = 200 #Seconds

$Time = (Get-Date).TimeofDay
do {
# Wait for the VMs to be Shutdown cleanly
sleep 1.0
$timeleft = $waittime - ($Newtime.seconds)
$numvms = ($ESXSRV | Get-VM | Where { $_.PowerState -eq "poweredOn"}).Count
Write "Waiting for shutdown of $numvms VMs or until $timeleft seconds"
$Newtime = (Get-Date).TimeofDay - $Time
} until ((@($ESXSRV | Get-VM | Where { $_.PowerState -eq "poweredOn" }).Count) -eq 0 -or ($Newtime).Seconds -ge $waittime)

# Shutdown the ESX Hosts
$ESXSRV | Foreach {Get-View $_.ID} | Foreach {$_.ShutdownHost_Task($TRUE)}

Write-Host "Shutdown Complete"

BE WARNED – IF YOU TEST THIS ON YOUR LIVE ENVIRONEMT, YOU’RE GOING TO GET IN TROUBLE!!!!

Script of the Day – changing ESX NTP servers

February 2, 2011 Leave a comment

The following script will amend the NTP server settings for all ESX hosts in your VC

$ntp1 = <ipaddress>"
$ntp2 = "<ipaddress>"
$oldntp = "<ipaddress>"
$oldntp2 = "<ipaddress>"

Add-PSSnapin VMware.VimAutomation.Core
connect-viserver -server &lt;vcentername&gt; -credential (Get-Credential)

$vmhosts = Get-VMHost

foreach ($element in $vmhosts)
{
Remove-VMHostNtpServer -NtpServer $oldntp -VMHost $element
Remove-VMHostNtpServer -NtpServer $oldntp2 -VMHost $element
Add-VmHostNtpServer -NtpServer $ntp1 -VMHost $element
Add-VmHostNtpServer -NtpServer $ntp2 -vmhost $element

$ntpd = Get-Vmhostservice -VMHost $element | where {$_.key -eq 'ntpd'}
Restart-VMHostService $ntpd -Confirm:$false
}

VMKFSTOOLS Man Pages

February 1, 2011 Leave a comment
VMKFSTOOLS                 VMware ESX Server Manual                 VMKFSTOOLS

NAME
     vmkfstools - VMware ESX Server file system management tool

SYNOPSIS
     vmkfstools OPTIONS
     vmkfstools OPTIONS PARTITION
     vmkfstools OPTIONS DEVICE
     vmkfstools OPTIONS PATH

COPYRIGHT
     VMware ESX Server is Copyright 2000-2006 VMware, Inc. All rights
     reserved.

DESCRIPTION
     vmkfstools is a program for creating and manipulating virtual disks, file
     systems, logical volumes and physical storage devices on the VMware ESX
     Server. It supports the creation of a VMware ESX Server File System
     (VMFS) on a partition of a disk, and the management of files (such as
     virtual disks) stored on VMFS.

     OPTIONS is one or more command-line options that specify the operation.
     The file or VMFS file system being manipulated may be specified after the
     options by a relative or absolute file path name in the /vmfs hierarchy.

     The PARTITION argument is used for specifying partitions, and should be
     of the form vmhbaA:T:L:P where A, T, L and P are integers representing
     adapter, target, LUN and partition respectively. The partition digit must
     be greater than zero.  For example, vmhba0:2:3:1 refers to the first par-
     tition on LUN 3, target 2, HBA 0.

     The DEVICE argument is used for specifying devices, and should be a path
     name beginning with /vmfs/devices, which is the mount point of the device
     file system. There are sub-mounts for each device class. For example,
     /vmfs/devices/disks for local or SAN-based disks, /vmfs/devices/lvm for
     VMKernel logical volumes, /vmfs/devices/generic for generic SCSI devices
     like tape drives, etc.

     The PATH argument is used for specifying a VMFS file system or file, and
     should be an absolute or relative path that names a directory or a file
     under /vmfs.  For example, a VMFS file system could be specified via a
     path such as:

     /vmfs/volumes/<file_system_UUID> or /vmfs/volumes/<file_system_label>

     A VMFS file would be specified via a path such as:

     /vmfs/volumes/<file_system_label|file_system_UUID>/[dir]/myDisk.vmdk or
     myDisk.vmdk

     if the current working directory is the parent directory of myDisk.vmdk.
:

FILE SYSTEM OPTIONS
     The long and short forms of options, shown here listed together, are
     equivalent.

     -C, --createfs vmfs3
     -b, --blocksize #[mMkK]
     -S, --setfsname fsName
         Create a VMFS file system on the specified partition,
         e.g. vmhba1:0:0:1. The partition becomes the file systemâs head
         partition. The file block size can be specified via the ´-b´
         option. The default file block size is 1MB. The file block size
         must be either 1MB, 2MB, 4MB or 8MB. In ESX Server 3, VMFS-2 file
         systems are read-only in that users will not be allowed to create
         or modify them. VMFS-3 file systems will not be accessible from
         ESX 2.x hosts.

         The -S option sets the label of the VMFS file system, and can only
         be used in conjunction with the ´-C´ option. This label can then
         be used to specify a VMFS file system in subsequent vmkfstools
         commands or in a virtual machine configuration file. The label
         will also appear in a listing produced by ´ls -l /vmfs/volumes´
         as a symbolic link to the VMFS file system. VMFS labels can be up
         to 128 characters long. They cannot contain leading or trailing
         spaces. After creating the file system, the label can be changed
         using the command ´ln -sf /vmfs/volumes/<FS UUID>
         /vmfs/volumes/<New label>´.

     -Z, --extendfs extension-partition
         Extend an existing VMFS-3 file system with the specified head
         partition by adding another partition designated by
         ´extension-partition´. A VMFS-3 file system can have at most 32
         partitions. This option will not work on VMFS-2 file systems as
         they are read-only in ESX Server 3.

     -P, --queryfs
     -h, --human-readable
         List the attributes of a VMFS file system when used on any file or
         directory of a VMFS file system. It lists the VMFS version number,
         the number of partitions constituting the specified VMFS file
         system, the file system label (if any), file system UUID,
         available space, and a listing of the device names of all the
         partitions constituting the file system. If partitions backing
         VMFS file system go offline then the number of partitions and
         available space reported change accordingly. The ´h´ option
         causes sizes to be printed in human-readable format (such as 5k,
         12.1M, or 2.1G).

FILE SYSTEM UPGRADE OPTIONS
     VMFS-2 to VMFS-3 file system upgrade is a two step process. Before file
     system upgrade can begin the `vmfs2` and `vmfs3` drivers must be unloaded
     and the auxiliary file system driver, `fsaux`, should be loaded. The
:
     first step of upgrade uses the `-T` option. Once the first step com-
     pletes, the auxiliary file system driver, `fsaux`, must be unloaded and
     the `vmfs2` and `vmfs3` drivers reloaded. The second step of file system
     upgrade makes use of the `-u` option.

     -T, --tovmfs3
     -x, --upgradetype [zeroedthick|eagerzeroedthick|thin]
         Converts a VMFS-2 file system to VMFS-3 format, preserving all files
         on the file system. Only file systems with block size 8MB or less
         can be converted. The conversion is in-place and the auxiliary file
         system driver (`fsaux`) module must be loaded. ESX Server will
         try to ensure that no local process or remote ESX Server is currently
         accessing the VMFS file system to be converted. The conversion is a
         one-way operation and once the VMFS-2 file system is converted to
         VMFS-3 file system, it cannot be rolled back to VMFS-2. The `-x
         thin` option results in the conversion of VMFS-2 files into
         thin-provisioned VMFS-3 files (as opposed to thick-provisioned
         files). File blocks that are part of a ´thick´ file, but were
         never written to, are discarded from the file to enable storage
         overcommitment.  The default upgrade option, `-x zeroedthick`,
         retains the properties of ´thick´ files across the upgrade.
         The `-x eagerzeroedthick` option eagerly zeroes out previously
         unwritten blocks. Note that the upgrade process may run much longer
         when invoked with the `-x eagerzeroedthick` option, as opposed
         to the other two options.

     -u, --upgradefinish /vmfs/volumes/<file system label|file system UUID>
         Once the first step of file system upgrade has completed (using
         `-T`), the `vmfs2` and `vmfs3` modules must be reloaded and
         the `-u` option used to complete the upgrade.

VIRTUAL DISK OPTIONS
     -c, --createvirtualdisk #[gGmMkK]
     -a, --adaptertype [buslogic|lsilogic] srcFile
     -d, --diskformat [zeroedthick|eagerzeroedthick|thick|thin]
         Create a virtual disk with the specified size on the VMFS file
         system. The size is specified in bytes by default, but can be
         specified in kilobytes, megabytes or gigabytes by adding a suffix
         of ´k´, ´m´, or ´g´ respectively. The ´adaptertype´ option
         allows users to indicate which device driver should be used to
         communicate with the virtual disk. See the `SUPPORTED DISK
         FORMATS` section for details on the disk formats supported by
         the ´-d´ option. The default disk format is ´zeroedthick´. The
         `-d eagerzeroedthick` option is used to create `thick` virtual
         disk with zeroed out contents.

     -U, --deletevirtualdisk
         Delete files associated with the specified virtual disk.

     -E, --renamevirtualdisk srcDisk
         Rename files associated with a specified virtual disk to the
         specified name.
:

     -i, --clonevirtualdisk srcDisk
     -d, --diskformat [rdm:<device>|rdmp:<device>|raw:<device>|thin|2gbsparse]
         Create a copy of a virtual disk or raw disk. The copy will be in
         the specified disk format. See the `SUPPORTED DISK FORMATS´
         section for details on the disk formats supported by the ´-d´
         option. To clone ESX REDO logs while preserving their hierarchy, use
         the Service Console command ´cp(1)´.

     -e, --exportvirtualdisk dstDisk
         This operation is deprecated. Use ´-i srcDisk -d 2gbsparse´ to
         achieve what it used to.

     -X, --extendvirtualdisk #[gGmMkK]
         Extend the specified VMFS virtual disk to the specified length. This
         command is useful for extending the size of a virtual disk
         allocated to a virtual machine after the virtual machine has been
         created. However, this command requires that the guest operating
         system has some capability for recognizing the new size of the
         virtual disk and taking advantage of this new size (e.g. by
         updating the file system on the virtual disk to take advantage of
         the extra space).

     -M, --migratevirtualdisk
         Migrate an ESX2 virtual disk to an ESX3 virtual disk.

     -r, --createrdm /vmfs/devices/disks/...
         Map a raw disk to a file on a VMFS file system. Once the mapping
         is established, it can be used to access the raw disk like a
         normal VMFS virtual disk. The ´file length´ of the mapping is
         the same as the size of the raw disk that it points to.

     -q, --queryrdm
         List the attributes of a raw disk mapping. When used with a
         ´rdm:<device>´ or ´raw:<device>´ specification, it prints out the
         vmhba name of the raw disk corresponding to the mapping
         referenced by the <device>. It also prints out identification
         information for the raw disk (if any).

     -z, --createrdmpassthru /vmfs/devices/disks/...
         Map a passthrough raw disk to a file on a VMFS file system. This
         allows a virtual machine to bypass the VMKernel SCSI command
         filtering layer done for VMFS virtual disks. Once the mapping is
         established, it can be used to access the passthrough raw disk
         like a normal VMFS virtual disk.

     -Q, --createrawdevice /vmfs/devices/generic/...
         Create a raw device descriptor file on a VMFS file system. This
         should only be used for generic SCSI devices like tape drives.

     -v, --verbose #
         This option is ignored for the queryrdm option. Setting the
:
        verbosity level will list additional information for the virtual disk
         configuration.

     -g, --geometry
         Get the geometry information (cylinders, heads, sectors) of a
         virtual disk.

     -w, --writezeros
         Initialize the virtual disk with zeros. Any existing data on virtual
         disk is lost.

     -j, --inflatedisk
         Convert a `thin` virtual disk to `thick` with the additional
         guarantee that any data on `thin` disk is preserved and any blocks
         that were not allocated get allocated and zeroed out.

SUPPORTED DISK FORMATS
     These are the arguments that can be passed to the ´-d´ option for the
     ´-c´ (create virtual disk) and ´-i´ (clone virtual disk) operations.

     `zeroedthick`
         This is the default option when creating new virtual disks.
         A zeroed thick disk has all space allocated at creation
         time, and this space is wiped clean of any previous contents on the
         physical media.

     `eagerzeroedthick`
         An eager zeroed thick disk has all space allocated and zeroed out at
         creation time. Such disks may take longer time during creation
         compared to other disk formats.

     `thick`
         A thick disk has all space allocated at creation time. This
         space may contain stale data as it exists on the physical media.

     `thin`
         Space required for thin-provisioned virtual disk is allocated and
         zeroed on demand as opposed to upon creation.

     `rdm`
         Virtual compatibility mode raw disk mapping.

     `rdmp`
         Physical compatibility mode (pass-through) raw disk mapping.

     `raw`
         Raw device.

     `2gbsparse`
         A sparse disk with 2GB maximum extent size. Disks in this format
         can be used with other VMware products.

:
     -s, --scan adapterName
         Scan a specified adapter for devices and/or LUNs. This option is
         especially useful for adapters which are connected to storage area
         networks (SANs). If a new device or LUN becomes accessible via the
         adapter, ESX Server will register this new device or LUN and
         make it usable by virtual machines. If an existing device or LUN
         is not being used and now appears to be gone, it will be removed from
         ESX Server data structures and will no longer be accessible to
         virtual machines.

     -L, --lock [reserve|release|lunreset|targetreset|busreset] /vmfs/devices/disks/...
         Manage SCSI reservations on physical targets or LUNs. These
         commands can interrupt the operations of other servers on a storage
         area network (SAN), so they should be used with great caution. The
         `reserve` command will reserve the specified raw disk.
         After the reservation, other servers will get a SCSI reservation
         conflict if they attempt to access that disk, but the server that did
         the reservation will be able to access the disk normally. The
         `release` command will release the reservation on the specified
         disk. Other servers will be able to access the disk again. The
         `lunreset` command resets a single LUN only instead of all
         the LUNs attached to a target. The `targetreset`  and `busreset`
         command will reset target and bus respectively causing SCSI
         reservations to be dropped. This option is potentially disruptive to
         all servers sharing the storage and is only meant to be used
         in the context of Clustering.


EXAMPLES
     vmkfstools -C vmfs3 -b 1m -S myVMFS vmhba1:3:0:1

     Creates a new VMFS-3 file system with label `myVMFS` on the 1st partition
     of target 3 and LUN 0 of vmhba adapter 1. The file block size is 1MB.

     vmkfstools -Z vmhba0:1:2:4 vmhba1:3:0:1

     Extends the newly created file system by adding the 4th partition of tar-
     get 1 and LUN 2 of vmhba adapter 0. As a result, the file system will
     span two partitions - vmhba1:3:0:1 and vmhba0:1:2:4. Here, vmhba1:3:0:1
     is the name of the head partition of the file system that is to be
     extended.

     vmkfstools -c 2048m /vmfs/volumes/myVMFS/myOS.vmdk

     Creates a 2GB VMFS virtual disk with the name `myOS.vmdk` on the VMFS
     file system named `myVMFS`. This virtual disk may then be accessed by a
     virtual machine.

     vmkfstools -i /vmfs/volumes/templates/gold-master.vmdk /vmfs/vol-
     umes/myVMFS/myOS.vmdk

     Clones the contents of a gold master virtual disk image from a template
     repository to a virtual disk named `myOS.vmdk` on the VMFS file system
     called myVMFS. A virtual machine can be configured to use this virtual
     disk by adding the following lines to its configuration file:

       scsi0:0.present = TRUE
       scsi0:0.fileName = /vmfs/volumes/myVMFS/myOS.vmdk

     vmkfstools -r /vmfs/devices/disks/vmhbaX:Y:Z:0 foo-rdm.vmdk

     Creates a mapping file, `foo-rdm.vmdk`, to the raw disk `vmhbaX:Y:Z:0`.
     The mapping file `foo-rdm.vmdk` is created in the current VMFS working
     directory, and can be used in a virtual machine in the same manner as in
     the previous example.

     vmkfstools -s vmhba1

     Scan adapter vmhba1 for any new targets or LUNs and for any removed tar-
     gets or LUNs.

VMnix                            May 11, 2006                            VMnix

Script of the day – writing to a cell in Excel

January 31, 2011 Leave a comment

Ever needed to inject info to a cell in an Excel spreadsheet – repeatedly . . . you can do so from Powershell . . like so:

Function write-excel ($ExcelFile, $WorkSheet, $Column, $Row, $Value) 
{
<#
	.SYNOPSIS
	 Write value(s) to Excel cells 
	.DESCRIPTION
	 No return - Updates an Excel Cell
	.PARAMETER  
		e.g. Specify the requested parameter, if not specified this will be prompted
	.EXAMPLE
		PS C:\> write-excel $ExcelFile $WorkSheet $Column $Row $Value
#>
	$File = (ls $ExcelFile).FullName
	# Open Excel
	$Excel = New-Object -Com Excel.Application
	
	# Prevent Overwrite and Macro Prompt
	$Excel.displayalerts=$False 

	# Open Template File 

	$WorkBook = $Excel.Workbooks.Open($File)
	$WorkSheet = $WorkBook.Worksheets.Item("$WorkSheet")
	$Worksheet.Cells.Item($Row,$Column) = $Value

	# Setting All Variables to Null

	$WorkBook.SaveAs($ExcelFile,1)
	$Excel.Quit()
 	$WorkBook = $Null
	$WorkSheet = $Null
	$Excel = $Null

	# Releasing Object Wrapper

	[GC]::Collect()
}

Script of the day – ping a range of IP addresses

January 28, 2011 Leave a comment

Friday today, so just a quick and easy script . . nothing clever

In PowerShell, ping functionality can be handled by using the ‘test-connection’ cmdlet, or simply using .Net

A ping using test-connection is just:

$object = New-Object system.Net.NetworkInformation.Ping
$object.Send('127.0.0.1')

You can wrap it as function to get even more out of this:

function ping-ip {
param( $ip )
trap {$false; continue}
$timeout = 1000
$object = New-Object system.Net.NetworkInformation.Ping
(($object.Send($ip, $timeout)).Status -eq 'Success')
}
ping-ip 127.0.0.1
ping-ip "news.bbc.com"

You can use this function to ping IP addresses or hostnames and will get either TRUE or FALSE as a return . . so you can use this in an if statement or similar

e.g.

If (Ping-IP "labserver001.local"){write-host "Lab domain appears to be online"}

You can add a loop to create your own network segment scan:

0..255 | % { $ip = "192.168.2.$_"; "$ip = $(ping-ip $ip)" }