Writing a PowerShell cmdlet to accept a script block as a parameter

The rename-element accepts the script block (I think ...) as a parameter, so I can do something like this if I want to rename a bunch of files (for example):

Dir *.ps1 | Rename-item -NewName {$_.Name -replace ".ps1" ".txt" }

I am writing a cmdlet to rename some elements and would like to be able to use syntax like this for the new name, but how to declare a parameter to accept a script block like this or a simple line?

+3
source share
2 answers

.NET(#/VB), , , , . PowerShell. , , , , , :

[Parameter]
public ScriptBlock NewName { get; set; }

[Parameter(ValueFromPipeline = true)]
public string OldName { get; set; }

protected override void ProcessRecord()
{
    Collection<PSObject> results = NewName.Invoke(this.OldName);
    this.Host.UI.WriteLine("New name is " + results[0]);
}

, , , $_ , $args [0]. , , - .

OTOH, Rename-Item NewName , . NewName , (), PowerShell . , $_ , :

[Parameter(ValueFromPipelineByPropertyName = true)]
public string NewName { get; set; }

[Parameter(ValueFromPipeline = true)]
public string OldName { get; set; }

protected override void ProcessRecord()
{
    this.Host.UI.WriteLine("New name is " + this.NewName);
}
+4

. -NewName script. :

Function Do-MyRename {
  param([ScriptBlock]$sb)

  dir *.ps1| Rename-Item -NewName $sb
}
+3

Source: https://habr.com/ru/post/1716811/


All Articles