VMware Cloud Community
vespavbb
Enthusiast
Enthusiast

check if $var VM is correct

Hi

I have a simple question but with massiv impact. How to improve security and avoid empty variables

We have a workflow running here and I give you an example.

$vm is the imput parameter and should contain the vm name. BUT if for some reason the paramet is emty, that would mean that the simple command

get-vm $vm |  Update-Tools would update all VMs and reboot all VM´s in the datacenter..BANG hundreds of VM will go down!

If I doe a get-vm ""   all VM´s will be selected.

Any Idea to secure this kind of situation

Is it enough to create a fresh vmobject like this...

#VM Inventory names to match

$vm = "vm123"   # how to avoid $vm = ""

$vm = $vm.ToUpper()

$vmobj = (get-vm | where {$_.Name -eq $vm -and $_.PowerState -eq "PoweredOn"}).name     # I changed -matsch to -eq to make it more secure

#####update tools example#####

Write-Host " Update VMware Tools on" $vmobj -ForegroundColor Green

get-vm $vmobj |  Update-Tools

VCP4,VCP5,VCP6,VCP7,VCP8
0 Kudos
3 Replies
LucD
Leadership
Leadership

That is strange, when I do a Get-VM -Name '' I get an error.

Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

At line:1 char:14

+ get-vm -name ''

+              ~~

    + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetVM

Which PowerCLI version are you using?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vespavbb
Enthusiast
Enthusiast

you are right I was a litte bit to hastily

but if you try like this

$vm =""

$vmobj = (get-vm | where {$_.Name -match $vm -and $_.PowerState -eq "PoweredOn"}).name

get-vm $vmobj

so the -match is the dangerous part.

but how could I easy check if the $vm is not empty and only one element and does not contain"*"?

VCP4,VCP5,VCP6,VCP7,VCP8
0 Kudos
LucD
Leadership
Leadership

You can do a lot of testing on a variable.

For example like this

if($vm -is [string] -and $vm.Length -gt 0 -and $vm -ne '*'){

    Get-VM | where{$_.Name -match $vm} | Select -ExpandProperty Name

}


It will check if $vm is a non-empty string that does not contain '*'.

But that check for '*' is not required since the -match operator expects a RegEx expression on the right operand, and just '*' is not a valid RegEx expression.

Also, there are other dangerous combinations like '.', '.+', '\w' ...

Are you going to test all these?

If you want to avoid all potentially dangerous combinations, you will probably have to rethink the logic of your script.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos