Aaron Newman
Aaron Newman

Reputation: 626

Powershell file and directory names as strings, sans decorations

Frequently I want to do something like:

 $foo=ls foo.txt|select FullName
 $bar=$foo.split("\\");  #  or replace or some such

But if I now look at the strings in bar they look like this:

 @{FullName=C:\path\to\foo.txt}

Since I know how long the decorations are I can manually get the substring. But that seems hacky - is there a way to just get the path part as a string?

Edit: to illustrate another similar issue, based on some questions, if I do:

 $foo -replace("\\","/")

I get:

 @{FullName=C:/src/tss/THSS-Deployment-Config/foo.txt}

I am doing lots of manipulations of these file names for a migration between different CM repositories. I was thinking 'if I could just get the whole path as a string'...

This is my first serious outing into PS. So maybe my mindset is just wrong.

Upvotes: 1

Views: 1505

Answers (2)

Aaron Newman
Aaron Newman

Reputation: 626

@arco444 gave me the missing piece. To get the full path with the filename as a string, the easiest thing I could come up with was:

 $bar=(Split-Path $foo.FullName) +"\"+ (Split-Path $foo -leaf)

I'm not sure if there's an easier way to combine get the whole path as a string.

Upvotes: 0

arco444
arco444

Reputation: 22821

A few quick ways, all using the Split-Path cmdlet which is perfect for this:

$foo= ls foo.txt | select FullName
$bar = Split-Path $foo.fullname

Or:

$foo= ls foo.txt | select -ExpandProperty FullName
$bar = Split-Path $foo

Or even shorter:

$bar = Split-Path (gci foo.txt).fullname

Upvotes: 4

Related Questions