简体   繁体   English

在PowerCLI脚本中从CSV文件设置VLAN

[英]Setting VLAN from CSV File in PowerCLI Script

I am trying to compile a PowerCLI script to help automate the creation of VMs from a CSV file's data. 我正在尝试编译PowerCLI脚本,以帮助自动从CSV文件的数据创建VM。 Currently the script I am running looks like this: 目前,我正在运行的脚本如下所示:

# Specify vCenter Server, vCenter Server username and vCenter Server user password
 write-host “Please specify vCenter Server and enter credentials” -foreground green
 $vc = read-Host "Connect to which vCenter Server?"
 write-host “Connecting to vCenter Server $vc” -foreground green

 $CSVPath = "$ScriptRoot\PROD_VMRequestTEST.xlsx.csv"    

 Connect-VIServer -Server $vc

 $CSVFile = Import-Csv -Path $CSVPath

 Import-Csv -Path $CSVPath

# Specify vCenter Server Virtual Machine & Templates folder
 $Folder = “Discovered virtual machine”

#
# Specify the vSphere Cluster

$Cluster = 'vSphere 5.5 RND'

$esx = Get-Cluster $Cluster | Get-VMHost -State connected

Import-Csv -Path $CSVPath | %{

  Write-Host “Creation of VM $_.Name initiated”  -ForegroundColor green

  New-VM -Name $_.Name -VMHost ($esx | Get-Random) -Location $Folder

  Write-Host “Power On of the  VM $_.name initiated”  -ForegroundColor green

  Start-VM -VM $_.Name -confirm:$false -RunAsync

}

I have encountered a few examples online dealing with setting the VLAN via PowerCLI but none of them seem to relate directly to my example of using the CSV file to determine the VLAN. 我在网上遇到了一些通过PowerCLI设置VLAN的示例,但是它们似乎都与我使用CSV文件确定VLAN的示例没有直接关系。

One example I tried using with my script was: 我尝试与脚本一起使用的一个示例是:

$VMhost = Get-vmhost $_.VMHost  
$PortGroup = Get-VirtualPortgroup -name $_.VLAN -VMhost $VMhost

However, I get errors relating to the -Name argument in that line. 但是,在该行中出现了与-Name参数有关的错误。

On the script context, I believe the error is causing because one of the columns value seems empty(in your case its Name ). 在脚本上下文中,我相信是由于该列值之一似乎为空(在您的情况下为Name )所导致的错误。 I can see that you are getting all the values in a foreach loop. 我可以看到您正在foreach循环中获取所有值。 I would recommend you to create a sample csv, insert only 2 set of data and see if it works. 我建议您创建一个示例csv,仅插入2组数据并查看其是否有效。 This way atleast you can narrow down the issue. 这样至少可以缩小问题范围。

Hope this helps...!!! 希望这可以帮助...!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM