如何在Powershell中正确创建具有函数的对象?

时间:2016-11-28 17:28:31

标签: powershell

我们有一个Powershell脚本,可以通过以下方式从json文件为我们的应用程序加载一些配置:

$ourApplicationSettings=Get-Content -Raw -Path $EnvironmentFile | ConvertFrom-Json

现在我有一个包含所有设置的对象,我想创建一些可以直接对$ settings对象或其中某些部分进行操作的函数。

我为Powershell所阅读的最佳实践文章指出,函数应该是以下形式:Verb-Noun,听起来开发人员应该编写如下函数:

Get-OurAppSourceDirectory $ourApplicationSettings
DoSomething-OurApp $ourApplicationSettings

这似乎非常直观,因为它意味着无法轻易找到与OurApp相关的所有功能。

一篇文章提出了一种可能的方法,即使用如下函数:

function New-OurAppConfig {
     $appConfig = Get-Content -Raw -Path $EnvironmentFile | ConvertFrom-Json
     $appConfig
}

但是这样我不知道如何添加成员函数以便我可以写:

$config = New-OurAppConfig
$config.Get-SrcDirectory
$config.Invoke-ActionABC

2 个答案:

答案 0 :(得分:0)

好吧,你可以搜索一下。 Get-Command *ourapp*。所以这不是真的。至于第二个问题:

$config = New-OutAppConfig
$var = Get-SrcDirectory $config
Invoke-ActionABC $var

或者你可以做一个调用所有这些函数的元函数,所以你可以调用它一次就可以了。

此外,您似乎可以使用PowerShell中的类来完成。 https://blogs.technet.microsoft.com/heyscriptingguy/2015/09/04/adding-methods-to-a-powershell-5-class/

答案 1 :(得分:0)

您可以使用Add-Member将脚本方法添加到现有对象:

$foo = '{"value":23}' | ConvertFrom-Json
$foo | Add-Member -Type ScriptMethod -Name Multiply -Value {
  Param($factor)
  $this.value * $factor
}

$foo.Multiply(2)  # output: 46
$foo.Multiply(3)  # output: 69

但是,这种方法有点尴尬,因为v5之前的PowerShell并不是为完整的OO而构建的,因为在配置对象上调用方法感觉很奇怪。

通常情况下,在脚本开头读取配置一次,然后将其用作全局单例:

$cfg = Get-Content 'C:\path\to\your.json' -Raw | ConvertFrom-Json

function Get-Something {
  ...
  Invoke-Other $cfg.Whatever
  ...
}

Get-Something

或使配置成为您的函数的必需参数:

$cfg = Get-Content 'C:\path\to\your.json' -Raw | ConvertFrom-Json

function Get-Something {
  Param(
    [Parameter(Mandatory=$true)
    $Config
  )

  ...
  Invoke-Other $Config.Whatever
  ...
}

Get-Something -Config $cfg
相关问题