PowerShell中多个变量声明的最佳方法

时间:2017-01-31 07:03:14

标签: powershell-v3.0

声明我们想要在脚本中使用的输入变量的最佳方法是什么?

截至目前,我要么在脚本上面声明所有需要的变量,要么在主脚本中创建一个单独的VariableDeclaration.ps1和点源。

有没有更好的方法来完成这项工作?

我想这样做的原因是因为我希望我的同行能够轻松地使用脚本而不需要太多的脚本知识。他们可以轻松编辑单独文件(可能是INI或XML)中定义的变量,而无需触及主脚本。

有什么建议吗?

变量声明示例:

#Customer_details
$CustomerID = '100'
$CustomerName = "ABCorp"
$vCenterName = "vCenter.ABCorp.com"
$vCenterUserName = "administrator@vsphere.local"
$vCenterPassword = ConvertTo-SecureString -String "ABCorp123" -AsPlainText -Force;
$CustomerPODLocation = "VW1"
$DatacenterName = "ABCorpDC"
$ClusterName = "ABCorpcluster"
$InfraResourcePoolName = $CustomerID + "-" + $CustomerName + "-" + "Infrastructure"
$FolderName = $CustomerID + "-" + $CustomerName
$ConnectionType = "S2S"
$VLANID = '237'
$PortGroupName = $ConnectionType  + "-" + $CustomerID + "-" + $CustomerName + "-" + $VLANID
$NumberofPorts = '1024'

1 个答案:

答案 0 :(得分:0)

"最佳方式"是非常主观的。这实际上取决于您想要实现的目标以及编辑文件的人员。点源.ps1文件基本上意味着您正在执行该脚本(在当前上下文中而不是像常规执行那样的子上下文)。您的示例文件需要哪个,因为它不仅包含数据,还包含代码(ConvertTo-SecureString,连接操作)。

在配置文件中包含代码可能会有问题,因为任何能够编辑该文件的人都可以在其中放置任意代码。其他格式没有这个缺点,但可能需要additional code for parsing(INI)或者更难以为人类编辑(XML)。

最好的妥协可能是使用包含key=value条目的平面文件,并通过ConvertFrom-StringData解析它:

$config = Get-Content 'C:\path\to\config.txt' -Raw | ConvertFrom-StringData

这将从配置文件中的键/值对创建一个哈希表。文件格式类似于INI,但不完全相同(不允许任何部分,评论以#而不是;开头。)

但配置文件并不是所有类型数据的最佳位置。通常,您将静态信息放在配置文件中,并使绑定的信息经常更改parameter到脚本。

示例:

config.ps1

$foo = 'something'   # static information, unlikely to change between script runs
...

script.ps1

[CmdletBinding()]
Param(
  # required value that is likely to change between script runs
  [Parameter(Mandatory=$true)]
  [string]$Bar,

  # default value that works most of the time, but which you want to
  # be able to override on the fly
  [Parameter(Mandatory=$false)]
  [int]$Baz = 42,

  ...
)

# read static configuration
. .\config.ps1

...

请注意,将纯文本凭据存储在文件中通常是不好的做法。如果您的脚本用于交互式使用,您可能需要考虑提示输入凭据,而不是将它们放在文件中。