Powershell - Save filename to variable

CES
CES used Ask the Experts™
on
Does anyone know how to save/pipe the name of a file to a variable  using Powershell?

For example, say I have a file c:\temp\test.txt

Is there a way to get "text" (<ideally) or "text.txt" to be stored into a variable that I can use later

I have not had any luck with Get-ChildItem or Get-Content.  Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chris DentPowerShell Developer
Top Expert 2010
Commented:
There are a number of ways depending on what you're looking to get. The first is to use the Split-Path command.
Split-Path c:\temp\test.txt -Leaf    # test.txt

Open in new window

If that isn't sufficient, we can do things with .NET.
([System.IO.FileInfo]"c:\temp\test.txt").Name    # test.txt
([System.IO.FileInfo]"c:\temp\test.txt").BaseName    # test

Open in new window

CESNetwork Administrator

Author

Commented:
([System.IO.FileInfo]"c:\temp\test.txt").BaseName    # test

this is doing exactly what I need.  Is there a way to adapt it to and unknown file name, (i.e. the file name could be test.txt, testtwo.txt etc...) and still grab the BaseName?
PowerShell Developer
Top Expert 2010
Commented:
If the file exists, Get-Item / Get-ChildItem:
$name = Get-Item $thePath | Select-Object -ExpandProperty BaseName

Open in new window

$thePath can contain wildcards, but if you get more than one match you'll have more than one value in $name.

If it does not exist, where does it come from?
CESNetwork Administrator

Author

Commented:
This should do the trick.

I'm basically trying to create a dynamic report...

The files are being produced by a separate process, so depending on options, the name of the file that I want to get into a variable (to be used later in my reporting) can be different.
CESNetwork Administrator

Author

Commented:
Thanks for the help.  These commands got me to where I needed to be

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial