1

I was attempting to use powershell to run a program on all files of a given type within a folder.

I first did a test to see if I could loop through all file types in a folder, and wrote this up:

$files = ls *.inp
foreach ($file in $files) {echo $file.basename}

which output:

myfile1.inp
myfile2.inp
myfile3.inp

So far, so good. Now, when I put this next bit in a for loop, it didn't work:

$files = ls *.inp
foreach ($file in $files) {myProgram arg1=$file.basename}

Note that the path to myProgram is already part of my path variable, so I don't have to write the full path to myProgram.exe, I can just write myProgram. Also, arg1 = the file I want processed.

I wanted to see what was going on, so I echoed the above commands in the loop:

foreach ($file in $files) {echo myProgram arg1=$file.basename}

...which output:

myProgram arg1=myfile.inp.basename

So for some reason, the basename method isn't doing what I want it to in the second scenario.

I changed my script to the following, which works fine:

foreach ($file in $files) {echo myProgram arg1=$file}

My question is, why does $file.basename output different things in the two scenarios? If I only want to use the basename in the second situation, how would I do that?

Thanks!

1 Answer 1

1

The powershell parser see $file in this context (a tring argument) as a complete expression. So it executes $file and then appends ".basename" to that. To tell it to execute the entire string as a single expression you need to wrap it in $():

foreach ($file in $files) {myProgram arg1=$($file.basename)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.