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

0
4
Asked By MistyCedar42 On

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?

3 Answers

Answered By AmberQuill58 On

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.

Answered By QuietMaple19 On

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`.

Answered By CopperLark7 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.