gpt4 book ai didi

powershell - 在Get-VM上构建一个有效的foreach循环

转载 作者:行者123 更新时间:2023-12-02 23:27:39 27 4
gpt4 key购买 nike

我试图建立一个循环,将Get-VM cmdlet放入一个数组中,然后让我在每个VM上运行一个foreach语句。当我构建了该阵列时,循环应转到每个VM,构建指定数量的VHD,对其进行初始化,格式化并将它们附加到VM。

脚本中的逻辑起作用。它将构建磁盘并将其附加到VM。我失败的地方是该脚本将错误地指出正在尝试构建的计算机已经创建(我怀疑$ val变量中的作用域错误)。它还将停止并且不会移动到下一个对象。

我怀疑我有作用域错误,而且ForEach-Object可能是执行此脚本的更好方法。但是,此时我迷路了,需要一点帮助。

一如既往,感谢您,并祝您编程愉快!

Write-Host "This script is set up for quickly creating and initilizing VHDs"
$Path = Read-Host "Please enter the path you want to create the drives to. Use the format in this example <E:\VHDS\>"
$fileName = Read-Host "The Drive will be <target>-<number>.vhdx. Please Name the target "
$vhdSize = 1GB
$vmAmount = 1

$GetVM = Get-VM

Foreach ($vm in $GetVM)
{
$n = $vm.Name.ToString()
$val = 0
For($internalCounter = 0; $internalCounter -le $vmAmount; $internalCounter++)
{
$vhdPath = (Join-path $Path ($fileName + '-' + $val + '.vhdx'))
New-VHD -Path $vhdPath -SizeBytes $vhdSize -Fixed
Mount-VHD -Path $vhdPath
$disk = get-vhd -path $vhdPath
Initialize-Disk $disk.DiskNumber
$partition = New-Partition -AssignDriveLetter -UseMaximumSize -DiskNumber $disk.DiskNumber
$volume = Format-Volume -FileSystem NTFS -Confirm:$false -Force -Partition $partition
Dismount-VHD -Path $vhdPath
Add-VMHardDiskDrive -VMName $n -Path $vhdPath
}
$val++
}

最佳答案

$val = 0移动到Foreach循环之前。否则,尽管您在循环结束时增加,但在循环开始时又将其清零,因此$val始终为零。

关于powershell - 在Get-VM上构建一个有效的foreach循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29854483/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com