I am using Get-ChildItem to navigate through a directory with the intention of recording file paths to a text file. However, I want to create the text files dynamically based on whether I'm in a specific folder or not. For example, let's say this is my file structure:
+--Root
+--LaunchFromHere
+--File1
+--file_I_want1.doc
+--File2
+--file_I_want2.doc
If my script starts in LaunchFromHere, I want to traverse File1 and File2 recursively, eventually arriving at the file_I_want.doc
's. However, I want to record their file paths in different .txt files, each with the name of the file that I found it in. Thus when I find file_I_want1.doc
, it's file path will be recorded in a text file called File1.txt.
Here's my problem: I can't find out how to get the filename of the file I'm currently inside in the script.
Based on similar questions on the site, this is my code:
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$file_title = $directorypath.split('\')[-1]
Get-ChildItem -include *.doc, -recurse | Select -Expand FullName |
ForEach-Object {
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$file_title = $directorypath.split('\')[-1]
"-----
"Directory path: `t" + $directorypath
"Current file: `t`t" + $file_title
"----"
}
My output only ever displays the file path where I ran the script, hence in this case:
PS C:\Root\LaunchFromHere
----
Directory path: C:\Root\LaunchFromHere
Current file: LaunchFromHere
---
And the title of my .txt is always LaunchFromHere.txt
Edit: I have removed Out-File
, but I do want my results to save to a text file.
So, how do I get the current name of the file that I'm traversing during the execution of the script?