我在 C# .NET 3.5 - VS2010 中有以下代码,用于初始化自定义对象列表
我也需要在 Powershell 2.0 脚本中做同样的事情。
在不使用 Add-Type 的情况下有什么建议吗?
public static List<ReplaceForDeployFile> CreateReplaceList()
{
var list = new List<ReplaceForDeployFile>()
{
new ReplaceForDeployFile()
{
PathFile = "web.config",
ReplaceList =
new List<ItemReplaceForDeployFile>()
{
new ItemReplaceForDeployFile()
{
ReplaceType = "System.String",
ValueSource = @"value=""Value1""",
ValueForDES = @"value=""Value2""",
},
new ItemReplaceForDeployFile()
{
ReplaceType = "System.String",
ValueSource = @"customErrors mode=""On""",
ValueForDES = @"customErrors mode=""Off""",
},
},
},
};
return list;
}
请您参考如下方法:
我知道 OP 对 PS v2 有限制。然而,即使我们在 v3 中搜索如何执行此操作,Google 也会将我们引向这个问题。我添加此答案是为了帮助可能正在寻找此信息的其他 v3 用户。
便利 Object Initializers可以使用以下语法在 PowerShell 中实现,
$item = [FullyQualifiedClassName]@{Prop1='Value1'; Prop2='Value2'}
OP 的例子
var item = new ItemReplaceForDeployFile() { ReplaceType = "System.String", ValueSource = @"value=""Value1""", ValueForDES = @"value=""Value2""" };
成为
$item = [Namespace.SubNs.ItemReplaceForDeployFile]@{ReplaceType='System.String'; ValueSource='value="Value1"'; ValueForDES='value="Value2"'}
来源:http://blogs.msdn.com/b/powershell/archive/2012/06/14/new-v3-language-features.aspx
New Conversions
Sometimes you want the keys of a hash literal to be ordered. You can now cast to [ordered] and we create an OrderedDictionary instead of HashTable. This only works with literals – if you try it on a variable, the ordering is no longer available.
[ordered]@{a=1; b=2}In a similar manner, you can create custom objects with a simple cast:
[pscustomobject]@{x=1; y=2}This does not create a HashTable; it creates a PSObject with note properties. If you are casting a literal, the note properties are added in the order they appear in the literal. If you are casting anything else, the ordering is determined by the IDictionary iterator.
If a type has a default constructor and settable properties, you can also use a hash table to case an object to that type:
[System.Drawing.Point]@{X=1; Y=2}This will call the default constructor and set the properties named in the hash table.
