How can I include each PDF’s filename in the Markdown file created by PowerShell?

September 27, 2026 3 answers
Asked by MistyCedar42
I'm writing a PowerShell script that scans `E:DIY` for PDF files and creates a Markdown file with the same base name for each one. The Markdown content should be an Obsidian wikilink such as `![[filename.pdf]]`, using the actual PDF filename for each file. My current script sets `$textContent` before the loop, so every file gets the literal placeholder text instead of its own name. I also tried properties such as `FullName`, `Name`, and `BaseName`, but received empty output or literal text like `[[_.fullname]]`. How should I build the link inside the loop?

Answers

CopperLark7
Use the current `$file` object inside the loop. Its `Name` property includes the `.pdf` extension, while `BaseName` does not. Since you want the extension in the Obsidian link, set the content like this: ```powershell foreach ($file in $pdfFiles) { $textFilePath = $file.FullName -replace '.pdf$', '.md' $textContent = "![[{0}]]" -f $file.Name Set-Content -Path $textFilePath -Value $textContent } ``` The important details are the `$` before `file`, placing the assignment inside the loop, and using `-f` or an expandable string to insert the property value.

MistyCedar42: That makes sense—the filename has to be generated for each iteration rather than assigned once before the loop. Using `$file.Name` also keeps the PDF extension.

Reply to this answer
QuietMaple19
You can also use PowerShell’s subexpression syntax inside the string: ```powershell $textContent = "![[${file.Name}]]" ``` For the filename without the extension, use `$file.BaseName` instead: ```powershell $textContent = "![[${file.BaseName}.pdf]]" ``` `BaseName` is a property, not a standalone command, so expressions such as `.BaseName` or `$.BaseName` won’t work. The variable must be the file object, in this case `$file.BaseName`.
Reply to this answer
AmberQuill58
A complete version would be: ```powershell $folderPath = 'E:DIY' Get-ChildItem -Path $folderPath -Filter '*.pdf' -File | ForEach-Object { $textFilePath = Join-Path $_.DirectoryName ($_.BaseName + '.md') $textContent = "![[{0}]]" -f $_.Name Set-Content -Path $textFilePath -Value $textContent } ``` `$_` refers to the current PDF inside `ForEach-Object`, while `$file` refers to the current item when using a regular `foreach` loop. Either style works; just use the matching variable consistently.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions