代码之家  ›  专栏  ›  技术社区  ›  Casey Chester

为什么从函数调用PowerShell代码时行为不同?

  •  2
  • Casey Chester  · 技术社区  · 6 年前

    经验丰富的C开发人员在这里学习PowerShell,所以我确信我错过了一些愚蠢的东西。我要做的是编写一个函数,它只将输入内容以JSON格式写入临时文件。我有一些代码,如果我以“内联”方式运行的话可以正常工作,但是在函数中调用该代码时会写入一个空文件。

    代码如下:

    function Dump-File {
        param (
            [Parameter(Mandatory=$true)]
            $Input
        )
        $tmp = New-TemporaryFile
        $Input | ConvertTo-Json | Out-File $tmp.FullName 
        Write-Output "Dump file written: $($tmp.FullName)"
    }
    
    $args = @{}
    $args.Add('a', 1)
    $args.Add('b', 2)
    $args.Add('c', 3)
    $args.Add('d', 4)
    
    # results in json written to temp file
    $tmp = New-TemporaryFile
    $args | ConvertTo-Json | Out-File $tmp.FullName
    Write-Output "args dumped: $($tmp.FullName)"
    
    # results in empty temp file
    Dump-File $args
    

    有人能帮助我理解为什么称为inline的代码可以工作,但当我将其包装为函数时,相同的代码不能工作吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Sage Pourpre    6 年前

    $Input 是一个自动变量。

    更改您的名称 转储文件 参数到 $somethingelse 将解决您的问题。从不使用 $input 作为参数或变量名。

    自动变量应视为只读。

    关于自动变量

    简短描述

    描述存储状态信息的变量 电源外壳。这些变量由PowerShell创建和维护。

    详细描述

    从概念上讲,这些变量被认为是 只读的。即使它们可以被写,为了向后 它们不应该写入的兼容性。

    以下是PowerShell中的自动变量列表:

    美元投入

    包含枚举传递给函数的所有输入的枚举器。$input变量仅可用于函数和脚本块(未命名函数)。在函数的进程块中,$input变量枚举当前在管道中的对象。当进程块完成时,管道中没有对象,因此$input变量枚举一个空集合。如果函数没有进程块,那么在END块中,$INPUT变量枚举函数的所有输入的集合。

    来源: About_Automatic_Variables

    此信息也可通过 Get-help 命令

    Get-Help about_Automatic_Variables