BadDogTitan
BadDogTitan

Reputation: 103

Powershell Script to Create TXT Files from folders

I received some excellent advice on how to create txt files based on the files in a folder using this PowerShell script.

Get-ChildItem -Path "C:\Users\temp\" -Recurse -File |
Where-Object {$_.Extension -notin '.txt'} |
    ForEach-Object {
        [System.IO.File]::WriteAllText("C:\Users\temp\" + $_.BaseName + ".txt", $_.FullName)
}

How would I modify this script to create txt files based on folders only, and ignoring the files contained in those folders?

Thanks!

Upvotes: 1

Views: 1031

Answers (2)

Theo
Theo

Reputation: 61028

Using a bit more PowerShell style and cmdlets would be:

$path = 'C:\Users\temp'
Get-ChildItem -Path $path -Recurse -Directory |
    Where-Object {$_.Extension -ne '.txt'} |
    ForEach-Object {
        Add-Content -Path (Join-Path -Path $path -ChildPath ($_.BaseName + ".txt")) -Value $_.FullName
    }

p.s. I changed the -notin into -ne because that is more appropriate here since you are only comparing to a single string, not an array.

Upvotes: 1

Peter Hahndorf
Peter Hahndorf

Reputation: 11222

In old PowerShell versions you would have to do a | Where-Object {$_.PSIsContainer -re $true}

but nowadays just replace your -file with -directory

Upvotes: 0

Related Questions