【问题标题】:Is it possible to have an optional Key property in a DSC resource?DSC 资源中是否可以有可选的 Key 属性?
【发布时间】:2014-12-04 23:09:53
【问题描述】:

我正在创建一个自定义 DSC 资源,我希望某个属性成为资源键的一部分,但同时是可选的:

  • 如果用户确实在配置中指定了它,它应该是键的一部分,这样就无法创建两个具有相同值的实例。

  • 1234563但没有设置这个可选参数

基本上我想要的是以下内容:

schema.mof 文件

[ClassVersion("1.0.0.0"), FriendlyName("cMyResource")]
class Mobiltec_cMyResource : OMI_BaseResource
{
    [Key, Description("Name")] string Name;
    [Key, Description("Key1")] string Key1;
    [Key, Description("This is a key only if it is specified")] string OptionalKey2;
    [Write, Description("Ensures"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] string Ensure;
};

我想要的实现的简单表示:

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory)][string]$Name,
        [Parameter(Mandatory)][string]$Key1,

        # Note that this is not mandatory
        [string]$OptionalKey2,

        [ValidateSet("Present","Absent")][string]$Ensure = "Present"
    )
...
}

及用法:

有效:

cMyResource Res1
{
    Name = 'name'
    Key1 = 'key1'
    OptionalKey2 = 'key2'
    OtherParameter = 'param'
}

cMyResource Res2
{
    Name = 'name'
    Key1 = 'key1'
    OptionalKey2 = 'otherKey2'
    OtherParameter = 'param'
}

同样有效:

cMyResource Res1
{
    Name = 'name'
    Key1 = 'key1'
    OtherParameter = 'param'
}

cMyResource Res2
{
    Name = 'name'
    Key1 = 'otherKey1'
    OtherParameter = 'param'
}

cMyResource Res3
{
    Name = 'name'
    Key1 = 'otherKey1'
    OptionalKey2 = 'key2'
    OtherParameter = 'param'
}

当我将属性声明为键时,每当我尝试在配置中使用资源而不指定它时,我都会收到此错误:

cMyModule\cMyResource : 类 'cMyResource' 需要 为属性提供“字符串”类型的值 '可选键2'。在:167 字符:9 + cMyResource Res1 + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Write-Error], ParentContainsErrorRecordException + FullyQualifiedErrorId : MissingValueForMandatoryProperty,cMyModule\cMyResource

【问题讨论】:

标签: powershell wmi dsc


【解决方案1】:

据我所知,根据我的经验,答案是否定的。

拥有[key] 属性意味着它是必需的。

此外,没有[key] 属性的 DSC 资源无法正常工作。不久前我尝试创建一个,直到实施时没有任何抱怨,此时 LCM 抛出关于没有关键属性的错误。

【讨论】:

  • 如果真的不可能,您会建议某种解决方法来维持这种行为吗?也感谢关于没有关键属性的提示。
  • 一种可能的解决方法是不对该属性使用[key][key] 存在时,您希望将其附加到属性上吗?
  • 只是不使用[Key] 我不允许指定两个仅在该属性上发散的资源,但我想要那个。请注意,在我的问题中,第二个有效配置包含 Res2 和 Res3,它们的区别仅在于此可选键。如果我删除密钥,它们将无法在同一配置中一起指定。
  • 啊,明白了,我知道你现在要做什么了。我不确定这是否可行,但也许在 DSC 中保留参数可选,但给它一个虚拟的默认值。在 MOF 中,将其设为 [key]。理想情况下,默认值满足[key],并且在 DSC 端,无需指定任何内容。
  • 您甚至可以像这样在 MOF 文件中发布默认值:[Key] String ConfigurationPath = "MACHINE/WEBROOT/APPHOST";,但您仍然会收到错误 Class 'xIisMimeTypeMapping' requires that a value of type 'String' be为属性“ConfigurationPath”提供
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
相关资源
最近更新 更多