powershell - 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 与 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
对于更广泛的可重用工具,您可能需要考虑将您的功能组织成模块
推荐阅读
- api - 在 Azure DevOps 中,列出生成定义 API 返回 401
- javascript - 通过列表视图从数据库中删除多个选定项目?
- reactjs - React 中毫秒日期的 PropType
- java - 仅在周末打印日期
- javascript - 在 React Native 中 TextInput 颜色仅更新一次
- swift - 按下后退按钮时 UINavigation 栏消失
- python - 我如何在我的网站上制作一个按钮,当它被点击时。它可以在我的 python 脚本中发送数据
- html - 如何根据屏幕尺寸从离子菜单中动态更改侧面?
- php - 与保存在数据库中的序列化数据的多边形相交
- c# - 当应用程序运行时,如何移动到下一行代码?