bluesxman
Caveat: I've only just started fiddling with Powershell (with VMware's PowerCLI snap-in specifically)
I've been working on this script, it does what I want (to a point), but I had trouble making the output behave correctly so have had to frig it such that I'm generating the CSV myself, rather than using Export-Csv
I was just wondering if someone could help me do it in a less cowboy-ish fashion:
Code: Select all
if ($args.length -eq 0 ) {write-host "You must specify a location" ; exit}
$loc = $args[0]
write-host "Scanning $loc guests..."
Get-VM -location $loc | foreach-object -begin {echo """vmname"",""vlan"",""netname"",""connected"",""startconnected"""} -process{
$vm = $_
$vmname= $vm.name
write-host ": $vmname :"
$netad = echo $vm | Get-NetworkAdapter | select networkname,connectionstate
echo $netad | foreach-object {
$vpg = Get-VirtualPortGroup -VM $vm -name $_.networkname | select vlanid,name
$vlan= $vpg.vlanid
$netname = $vpg.name
$conn = $_.connectionstate.connected
$startconn = $_.connectionstate.startconnected
echo """$vmname"",""$vlan"",""$netname"",""$conn"",""$startconn"""
}
}
----------------------------
#20 Sep 2011 10:58
bluesxman
Managed to teach myself a little more and improve it myself, should anyone care

Code: Select all
if ($args.length -eq 0 ) {write-host "You must specify a location" ; exit}
$location = $args[0]
$oformat = $args[1]
$ofile = $args[2]
write-host "Scanning guests in $location..."
$output = Get-VM -location $location | %{
$_vm = $_
write-host ">>" $_vm.name
echo $_vm | Get-NetworkAdapter | %{
$_nic = $_
Get-VirtualPortGroup -vm $_vm -name $_nic.NetworkName | select `
@{N="VMName";E={$_vm.name}}, `
@{N="IFName";E={$_nic.name}}, `
VLANID, `
NAME, `
@{N="ConnectionState";E={$_nic.connectionstate.connected}}, `
@{N="StartConnected";E={$_nic.connectionstate.startconnected}}
}
}
Switch ($oformat){
csv { if ( $null -eq $ofile ) { Clear-Variable oformat } else { echo $output | Export-CSV -NoTypeInformation "$ofile" } }
auto { echo $output | Format-Table -auto }
default { Clear-Variable oformat }
}
if ( $null -eq $oformat ) { echo $output }
cmd | *sh | ruby | chef
----------------------------
#20 Sep 2011 15:42
jumper
you can use the positional parameter:
untested.ps1
Code: Select all
[CmdletBinding()]
Param(
[Parameter(Position=0,
Mandatory=$True,
HelpMessage="You must specify a location"
)]
$Location,
[Parameter(Position=1)]
[ValidateSet('csv','auto','default')]
$Format='default',
[Parameter(Position=2)]
$File
)
Begin{
Write-Verbose "Scanning guests in $location..."
}
End{
Try{
# code here
}
Catch{
# code error
}
finally{
# format data
}
}