output to file

I have written a script that works as expected, however the log file is not populated and need to have the changes made create a log file, and keep appending the file anytime the scrip has run. Still pretty new to powershell so I dont completely understand piping yet. Can I get some help how I would actually show changes made please?




Get-ChildItem -path $Path -filter $Old -Recurse | rename-Item -NewName $New -Verbose -confirm |select-Object $Path, $Old, $New | Out-File C:\log.txt

Select-object is normally for properties output by the previous command. I think you want to save 3 variables as a string to a text file:

"$Path, $Old, $New" | Out-File C:\log.txt

Or skip the select-object altogether.

A few things:

  1. Default values can't be used with mandatory parameters.
  2. By default Rename-Item does not produce any output so you'll need to use the -PassThru parameter with it.
  3. You'll need to use the property names instead of the variables with Select-Object.
  4. Use SupportsShouldProcess instead of hard coding -Confirm into the script.


[string]$Old = "*.txt",
$New = "Test01.txt"
Get-ChildItem -Path $Path -Filter $Old -Recurse -PipelineVariable info |
Rename-Item -NewName $New -PassThru |
Select-Object -Property @{label='Path';expression={$_.Directory}}, @{label='OldName';expression={$info.Name}}, @{label='NewName';expression={$_.Name}} |
Out-File -FilePath C:\log.txt -Confirm:$false [/pre]

[quote quote=118332][/quote]

When I do a get help on rename-item, it indicates -passThru is not an accepted pipeline input, however -path and -newName are pipeline capable. I just dont know how I would display them if select-object does not work in this scenario.

Correct. That means it doesn’t accept “input” on the -PassThru parameter from the previous command in the pipeline (which is not what Passthru is designed for).

The -PassThru parameter exists on a number of commands that don’t normally produce output. Adding -PassThru makes them produce “output”. For example, Stop-Service doesn’t normally produce any output, but add the -PassThru parameter and it produces output as if you had run Get-Service after running Stop-Service.

What does -PassThru really accomplish? If a command doesn’t produce output, it has no results so there’s nothing to pipe to another command in the pipeline. By making it produce output (via the -PassThru parameter), it can then be piped to another command.

Thanks for the clarification, I’ll do some follow up with your comments to better understand this concept.