2

我正在使用使用自定义对象的 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# 语法,因此欢迎所有解决方案。

4

1 回答 1

3

引入类:

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
于 2016-11-24T13:05:32.230 回答