powershell - 对PowerShell 5.1中的错误以正确的语法进行响应

标签 powershell powershell-5.0

我使用PowerShell 5.1并编写脚本供其他管理员使用。当我的函数使用了错误的语法时,我需要能够使用错误代码中的正确语法进行响应。我怎么做?

function Get-2008Servers {
    [CmdletBinding()]
    Param(
        [string]$ReferenceDomain = ""
    )

    $ForestObj = Get-ADForest -Server $ReferenceDomain
    foreach ($Domain in $ForestObj.Domains) {
        Get-ADComputer -Filter 'OperatingSystem -like "*200*"' -Server $ReferenceDomain -Properties Name,lastlogondate,operatingsystem,OperatingSystemServicePack,canonicalname |
            select Name,lastlogondate,operatingsystem,OperatingSystemServicePack,canonicalname |
            sort name -Descending |
            Export-Csv -Force -NoTypeInformation .\output\$ReferenceDomain-NOT2016Servers.csv
    }
}
$result = ls .\output\*-NOT2016Servers.csv
$result

运行函数时:
Get-2008Servers

当您尝试在没有必需选项的情况下运行时,需要提示您添加“-ReferenceDomain”。如何将其写到上面的代码中?

最佳答案

通过添加[Parameter()]属性装饰器并指定Mandatory属性:

param(
    [Parameter(Mandatory = $true)]
    [string]$ReferenceDomain
)

有关about_Functions_Advanced_Parameters属性和Parameter的更多信息,请参见 Mandatory help topic

关于powershell - 对PowerShell 5.1中的错误以正确的语法进行响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57043568/

相关文章:

powershell - 从 Powershell 调用 VBScript ..这是正确的方法吗?

PowerShell 如何从 GAC 添加类型

Powershell,用空格替换 DOT

powershell - 为什么添加到 ArrayList 会计算传递给它的内容?

powershell - 如何将带有附加 Prop 的PSCustomObject转换为自定义类

powershell - 在变量Powershell中传递参数

windows - CA 对 SSL CSR 的 Powershell 脚本签名?

windows - 我们如何在 PowerShell 5.0 中通过标签获取驱动器?

powershell - 如何在命名空间中组织类?

Powershell 5 : documentation support via comments for classes and enums members