从 XML 填充参数列表 [英] Populate parameter list from XML

查看:58
本文介绍了从 XML 填充参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 ID 列表拉入 powershell 参数验证集,如下所示:

I need to pull a list of IDs into a powershell paramater validateset like so:

function Do-Stuff {
   [Cmdletbinding()] 
   param(
        [ValidateSet("Seattle","NewYork","London","Atlanta" )]
        [String]$Site
    )

我不想手动指定集合中的城市,而是从已经列出所有城市的现有 xml 文档中提取.加载后,站点名称将出现在 $xml.var.sites.id 中.这是可能的,而且可能更重要的是,这是一个好主意吗?

Instead of manually specifying the cities in the set, I'd like to pull from an existing xml document that already lists them all. Once loaded, the site names appear in $xml.var.sites.id. Is this possible, and probably more importantly, is it a good idea?

推荐答案

或者,如果您想使用文件进行验证,您可以使用 ValidateScript 而不是 ValidateSet像这样:

Alternatively, if you want to use an file to validate against you can use ValidateScript instead of ValidateSet like such:

function Do-Stuff {
   [Cmdletbinding()] 
   param(
        [ValidateScript({if(([xml](gc c:\temp\config.xml)).getElementsByTagName("City").Name -contains $_){$true}else{throw ([xml](gc c:\temp\config.xml)).getElementsByTagName("City").Name}} )]
        [String]$Site
    )

这是基于极其简单的 XML 文件:

That's based on the ridiculously simplistic XML file:

<?xml version="1.0"?>
<City_Validation_List>
    <City Name="Seattle"></City>
    <City Name="Atlanta"></City>
</City_Validation_List>

所以,无论如何,您可以使用 ValidateScript 来运行脚本块作为验证,您可以在其中从 XML 文件加载内容.ValidateSet 另一方面必须有一个预定义的字符串数组来验证.

So, anyway, you can use ValidateScript to run a scriptblock as validation, in which you could load things from an XML file. ValidateSet on the other hand has to have a pre-defined array of strings to validate against.

这篇关于从 XML 填充参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆