我正在使用使用自定义对象的PowerShell编写脚本。但棘手的部分是这个自定义对象使用另一个自定义对象作为属性。我试图用C#语法来做。
当我尝试运行脚本时,我收到此错误:
The type or namespace name 'Disk' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\trumpe\AppData\Local\Temp\orydsmyw.0.cs(1) : public class VirtualMachine{
c:\Users\trumpe\AppData\Local\Temp\orydsmyw.0.cs(2) : >>> public Disk Disks;
c:\Users\trumpe\AppData\Local\Temp\orydsmyw.0.cs(3) : public string IPAddress;
在PowerShell中有没有办法完成它?以下是我在一个文件中的类代码:
Add-Type -Language CSharp @"
public class Disk{
public string VirtualMachineDiskID;
public string StorageID;
public string StorageIdentifier;
public string DiskFileName;
public string StorageProfileID;
public int CapacityKB;
public int ControllerKey;
public int DeviceKey;
public int DiskMode;
public int UnitNumber;
}
"@;
Add-Type -Language CSharp @"
public class VirtualMachine{
public Disk Disks; #<=== This part stops working because it cannot find the type Disk
public string IPAddress;
public string Name;
public string OSFullName;
public string PowerState;
public string ResourcePoolID;
public string TenantID;
public string UniqueId;
public string VirtualMachineID;
public int NumCPU;
public int NumNic;
public int StorageCapacityAllocatedMB;
public int RamAllocatedMB;
public bool IsRemoved;
public bool IsTemplate;
}
"@;
我不仅限于C#语法,所以欢迎所有解决方案。
答案 0 :(得分:3)
powershell-v5.0介绍了课程:
Class Disk{
[string] $VirtualMachineDiskID;
[string] $StorageID;
[string] $StorageIdentifier;
[string] $DiskFileName;
[string] $StorageProfileID;
[int] $CapacityKB;
[int] $ControllerKey;
[int] $DeviceKey;
[int] $DiskMode;
[int] $UnitNumber;
}
Class VirtualMachine {
[Disk] $Disks;
[string] $IPAddress;
[string] $Name;
[string] $OSFullName;
[string] $PowerState;
[string] $ResourcePoolID;
[string] $TenantID;
[string] $UniqueId;
[string] $VirtualMachineID;
[int] $NumCPU;
[int] $NumNic;
[int] $StorageCapacityAllocatedMB;
[int] $RamAllocatedMB;
[bool] $IsRemoved;
[bool] $IsTemplate;
}
$disk = New-Object Disk
$disk.StorageID = 4711
$vm = New-Object VirtualMachine
$vm.Disks = $disk