当 CSV 字段不存在时,Powershell 函数参数获取意外值

标签 powershell powershell-cmdlet

我正在编写一个可以接受管道输入的 PowerShell 函数。具体来说,我正在使用 Import-CSV 对其进行测试。许多参数不是强制性的,这意味着有时 CSV 不会包含这些列。对于 bool 值,这可以按预期工作,但对于字符串值,缺失的 CSV 字段会在字符串字段中生成行对象的副本。

这是一个示例问题参数:

[Parameter(Mandatory=$False,
       ValueFromPipeline=$True,
       ValueFromPipelinebyPropertyName=$True,
       HelpMessage="TCP Port of the remote server")]
[Alias('Port', 'Remote Server Port')]
[string]$RemoteServerPort = "5500",

现在,如果该字段丢失,我希望该值为指定的“5500”,但我得到的是:

$RemoteServerPort = @{Name=KG; IP=10.1.1.1; Username=Admin; Password=}

我环顾四周,但坦率地说,我什至不知道要搜索什么。

最佳答案

这是因为您指定了 ValueFromPipeline=$True,以便 PoSh 在无法通过属性名称绑定(bind)参数时将管道对象强制为 string。您可以通过从此参数中删除 ValueFromPipeline=$True 并引入另一个要绑定(bind)到管道对象的参数来解决该问题,即类似这样的

function MyTestFunc() {

    param(
        [Parameter(ValueFromPipeline=$True)]
        [object]$PipedObj,

        [Parameter(Mandatory=$False,
               ValueFromPipelinebyPropertyName=$True,
               HelpMessage="TCP Port of the remote server")]
        [Alias('Port', 'Remote Server Port')]
        [string]$RemoteServerPort = "5500"
    )

    Write-Host "Port: $RemoteServerPort / Obj: $PipedObj"
}


$o1 = [pscustomobject]@{"Server" = "123"; "Port" = "12345"}
$o2 = [pscustomobject]@{"Server" = "1234"; "OS" = "Win3.1"}

$o1 | MyTestFunc
$o2 | MyTestFunc

将导致

Port: 12345 / Obj: @{Server=123; Port=12345}
Port: 5500 / Obj: @{Server=1234; OS=Win3.1}

详细了解幕后实际发生情况的一种方法是使用 Trace-Command ,如下所示

Trace-Command ParameterBinding {$o2 | MyTestFunc} -PSHost

关于当 CSV 字段不存在时,Powershell 函数参数获取意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536800/

相关文章:

c# - PowerShell 通过远程注册表获取证书

windows - 净用户 $userName/domain

windows - PowerShell 中 New-ItemProperty 的小问题

powershell - 如何设置默认位置以在 profile.ps1 中启动?

powershell - Get-AdComputer -filter 参数不接受 Get-Date 输出

powershell - Azure Powershell 失败并出现模糊错误 : One or more errors occurred

powershell - 从脚本位置 powershell 创建 zip

powershell - 如何在 Powershell v3.0 中查找新的 cmdlet

powershell - 以正确的、多操作系统友好的方式引用 System.Management.Automation.dll

.net - PowerShell 和 StringBuilder