首页 > 解决方案 > powershell - 类/函数声明问题

问题描述

我是新手,powershell所以我不确定为什么会收到以下错误:

语句块或类型定义中缺少结束“}”

但从我的 Java 知识来看,一切看起来都是一致的。

我有一种class { method1{} method2{} }结构发生如下:

案例使用

class DoSomething1
{

    <#
         .SYNOPSIS whatever
         .PARAMETER somevalue1
         .PARAMETER somevalue2
         ... etc
    #>

    function DoSomething1
    {
        [cmdletbinding()]
        param
        (
            [parameter(Mandatory = $true, HelpMessage = "help yourself")]
             $somevalue3
        )
     # will add code to constructor later
    }
}

我不确定问题出在哪里,因为当我将方法编写为:

选择

class DoSomething1
{
   DoSomething1()
   {
      # whatever
   }
}

我不确定一个与另一个相比是否有优势,或者我是否在上下文中使用关键字函数,但我想通过在前面cmdletbindings使用来进一步应用和获取帮助信息的概念<# .SYNOPSIS details #>功能命令。

有谁知道我做错了什么?

标签: powershell

解决方案


正如评论中提到的,PowerShell 与 Java 或 C# 不太一样,就 PowerShell 语言功能而言,类是某种“二等公民”。

相反,在 PowerShell 中,我们可以使用称为高级功能的东西来实现类似 cmdlet 的行为- 就像您已经拥有的功能一样:

function DoSomething1
{
    [cmdletbinding()]
    param
    (
        [parameter(Mandatory = $true, HelpMessage = "help yourself")]
         $somevalue3
    )

    # do something with $somevalue3
}

PowerShell 脚本是逐行评估的,因此如果您将这些函数定义之一放入脚本中,任何后续调用都DoSomething1将调用该函数。

根据您尝试自动化的大小和范围,您可能会发现自己拥有大量像这样的小型独立功能。为了更好地组织大型项目中的代码,您可以将函数定义拆分为单独的文件,然后使用.调用运算符执行它们,这将使函数“持久”在当前范围内:

Get-Something.ps1

function Get-Something
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}

Export-Somewhere.ps1

function Export-Somewhere 
{
  [CmdletBinding()]
  param(<# ... #>)
  # ...
}

script.ps1

# Import functions from other the script files
. .\Get-Something.ps1
. .\Export-Somewhere.ps1

# Now we can use the functions in here
Get-Something |Export-Somewhere 

对于更广泛的可重用工具,您可能需要考虑将您的功能组织成模块


推荐阅读