【发布时间】: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
【问题讨论】:
-
如果有人对此问题感兴趣,我已经asked on meta for the creation of the
mofandcimtags。
标签: powershell wmi dsc