0

How do I print a list of files by invoking Get-FilesByDate from within the files.ps1 script itself?

$ pwsh files.ps1 
Get-FilesByDate
txt
1
1
/home/thufir/

$ cat files.ps1 

Function Get-FilesByDate
{
 Param(
  [string[]]$fileTypes,
  [int]$month,
  [int]$year,
  [string[]]$path)
   Get-ChildItem -Path $path -Include $filetypes -Recurse |
   Where-Object {
   $_.lastwritetime.month -eq $month -AND $_.lastwritetime.year -eq $year }
} #end function Get-FilesByDate

Write-Output Get-FilesByDate("txt",1,1,"/home/thufir/")

Additionally, or alternately, populate an array with the file names? Any and all files, or txt.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Thufir
  • 8,216
  • 28
  • 125
  • 273

1 Answers1

1

Write-Output is rarely needed, because you can rely on PowerShell's implicit output behavior:

# By neither redirecting nor piping nor capturing the output from 
# this call, what it returns is *implicitly* output.
# Note the absence of parentheses and the separation of arguments with whitespace.
Get-FilesByDate "txt" 1 1 "/home/thufir/"

Note how the arguments must be passed without parentheses around the argument list and separated by whitespace, not with the pseudo method syntax you've attempted.
In other words: PowerShell commands (cmdlets, function, scripts, aliases) are invoked like shell commands, not like methods in C#.


In order to pass the output from a command as an argument to another command:

  • enclose the command in (...) or
  • to ensure that the output is treated as an array, enclose it in @(...) or
  • to pass the output from multiple statements, enclose them in $(...) (or @(...))

Thus, in order to use Write-Output explicitly (which, as stated, isn't necessary), you'd have to write:

Write-Output (Get-FilesByDate "txt" 1 1 "/home/thufir/")

To populate an array with the output from Get-FilesByDate:

$files = @(Get-FilesByDate "txt" 1 1 "/home/thufir/")

The @(...) ensures that $files receives an array even if the function happens to return only a single file; alternatively, you could type-constrain the variable and thereby ensure that it is an array:

[array] $files = Get-FilesByDate "txt" 1 1 "/home/thufir/"

Note, however, that explicit use of arrays is often not necessary in PowerShell (since version 3), because even scalars (single values) implicitly act like arrays - see this answer.


Further reading:

mklement0
  • 382,024
  • 64
  • 607
  • 775