powershellparameterspowershell-cmdletscriptblockdelay-bind

For PowerShell cmdlets, can I always pass a script block to a string parameter?


I'm looking at the documentation of PowerShell's Rename-Item cmdlet and there is an example like this.

Get-ChildItem *.txt | Rename-Item -NewName { $_.name -Replace '\.txt','.log' }

This example shows how to use the Replace operator to rename multiple files, even though the NewName parameter does not accept wildcard characters.

This command renames all of the .txt files in the current directory to .log.

The command uses the Get-ChildItem cmdlet to get all of the files in the current folder that have a .txt file name extension. Then, it uses the pipeline operator (|) to send those files to Rename-Item .

The value of NewName is a script block that runs before the value is submitted to the NewName parameter.

Note the last sentence:

The value of NewName is a script block that runs before the value is submitted to the NewName parameter.

Actually NewName is a string:

[-NewName] <String>

So does that means I can always use a script block when the required parameter type is a string?


Solution

  • # Delay-bind script-block argument:
    # The code inside { ... } is executed for each input object ($_) and
    # the output is passed to the -NewName parameter.
    ... | Rename-Item -NewName { $_.Name -replace '\.txt$','.log' }
    

    The call above shows an application of a delay-bind script-block ({ ... }) argument, which is an implicit feature that:


    [1] Error conditions:


    [2] This discrepancy is being discussed in GitHub issue #7157.