如果您有多个参数在调用命令或脚本时需要一个值,我知道您可以像这样传递它:
$parameters = @{
    name = "John"
    last_name = "Doe"
}
Run Code Online (Sandbox Code Playgroud)
但是,如果命令或脚本实际上只是希望-T指示诸如标志之类的东西,但参数本身不需要值。如何在变量中设置它?
$optionalT = ""
if ($itNeedsTheT) $optionalT = "-T"
command $optionalT
Run Code Online (Sandbox Code Playgroud)
如果我这样做,它会抱怨以下消息:
Unknown argument 'T' on command line.
Run Code Online (Sandbox Code Playgroud) 在 PowerShell 中,您可以创建一个哈希表,并使用 将这个哈希表添加到您的函数中@,这在 PowerShell中是splatting。
$dict = @{param1 = 'test'; param2 = 12}
Get-Info @dict
Run Code Online (Sandbox Code Playgroud)
可以将字典作为参数集合传递给构造函数或方法吗?
我下载了用于合并 junit 报告的 npm 包 - https://www.npmjs.com/package/junit-merge。
问题是我有多个文件要合并,并且我正在尝试使用字符串变量来保存要合并的文件名。
当我自己编写脚本时,如下所示:
junit-merge a.xml b.xml c.xml 
Run Code Online (Sandbox Code Playgroud)
这有效,正在创建合并文件,但是当我这样做时
$command = "a.xml b.xml c.xml"
junit-merge $command
Run Code Online (Sandbox Code Playgroud)
这是行不通的。错误是
错误:找不到文件
有人遇到过类似的问题吗?
考虑以下简单函数:
function Write-HostIfNotVerbose()
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @args
    }
}
Run Code Online (Sandbox Code Playgroud)
而且效果很好:
现在我想让它成为一个高级函数,因为我希望它继承详细程度首选项:
function Write-HostIfNotVerbose([Parameter(ValueFromRemainingArguments)]$MyArgs)
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @MyArgs
    }
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用:
让我抓狂的是,我无法确定第一个示例与第二$args个示例有何不同。$args
我知道@args默认情况下本机泼溅不适用于高级功能 - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.2#notes
但我希望可以模拟,但也行不通。我的问题是 - 我尝试模拟它的方式有什么问题,以及是否可以在不显示所有参数的Write-Host情况下修复我的代码Write-HostIfNotVerbose
powershell arguments function function-call parameter-splatting
我有这么长的一行,我想让它更容易阅读:
$Mail = "stantastic@example.com"    
Get-ADUser -Server example.com:3268 -Filter {EmailAddress -eq $Mail} -Properties CN,co,Company,Department,DisplayName,SamAccountName,State,Office,EmailAddress 
Run Code Online (Sandbox Code Playgroud)
我读到使用 splatting 很好,所以我正在尝试:
$Params = @{
    Server = 'example.com:3268'
    Filter = '{ EmailAddress -eq $Mail }'
    Properties = 'CN,co,Company,Department,DisplayName,SamAccountName,State,Office,EmailAddress'
}
Get-ADUser @Params
Run Code Online (Sandbox Code Playgroud)
但是运行这个会抛出一个错误:
Get-ADUser:解析查询时出错:'{ EmailAddress -eq stantastic@example.com }' 错误消息:'syntax error' 在位置:'1'。
在行:1 字符:1
+ Get-ADUser @Params
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException
    + FullQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
我错过了什么?