Okay, so I'm far from being a PowerShell expert so probably there is some concept I didn't get quite right but here goes.
If I do this:
Import-Module VMware.VimAutomation.Core
Connect-VIServer -Server <vcenter> -User <user> -Password <password>
$vm = Read-Host "Insert VM name"
Write-Host "VM string: " $vm
$vm = Get-VM -Name $vm | Get-View
Write-Host "VM name: " $vm.name
The output is (pretend the Read-Host input was "vm1"):
VM string: vm1
VM name: vm1
Now, if I do this:
param
(
[string]$vm
)
Import-Module VMware.VimAutomation.Core
Connect-VIServer -Server <vcenter> -User <user> -Password <password>
$vm = Read-Host "Insert VM name"
Write-Host "VM string: " $vm
$vm = Get-VM -Name $vm | Get-View
Write-Host "VM name: " $vm.name
The output is (pretend the Read-Host input was "vm1"):
VM string: vm1
VM name: (blank)
The above is just a small part of a bigger script but I was able to reduce to just these steps when troubleshooting the problem described above.
What exactly is the difference between the first and second case that causes the blank output when I add the "param" section?
Thank you very much for your time.
The problem is not as much the Param section, the problem is the fact that you define $vm as being of [string] type.
You are changing the type of the $vm variable in your script, from [string] to [VMware.VimAutomation.Types.VirtualMachine]
But the param says it is [string], and a [string] type does not have a Name property.
Don't change the type of your variables on the fly, unless you know what you are doing.
Rather use separate variables for separate types.
Something like this for example
param(
[string]$vmName,
[VMware.Vim.VirtualMachine]$vm
)
$vmName = Read-Host "Insert VM name"
Write-Host "VM string: " $vmName
$vm = Get-VM -Name $vmName | Get-View
Write-Host "VM name: " $vm.name
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
The problem is not as much the Param section, the problem is the fact that you define $vm as being of [string] type.
You are changing the type of the $vm variable in your script, from [string] to [VMware.VimAutomation.Types.VirtualMachine]
But the param says it is [string], and a [string] type does not have a Name property.
Don't change the type of your variables on the fly, unless you know what you are doing.
Rather use separate variables for separate types.
Something like this for example
param(
[string]$vmName,
[VMware.Vim.VirtualMachine]$vm
)
$vmName = Read-Host "Insert VM name"
Write-Host "VM string: " $vmName
$vm = Get-VM -Name $vmName | Get-View
Write-Host "VM name: " $vm.name
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Well, like I said, not really a PowerCLI expert so I had no idea. Too long working with shell and javascript so the "variable fixed type" concept skipped my mind completely.
Thank you very much.