• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Looping through each file in a directory: Powershell noob question

F

fr0man

#1
I've been using Powershell for a few months now as my command line interface
and I'm loving it. But I haven't actually scripted anything yet and don't
even know where to begin.
I need a simple powershell script to loop through each file in a directory
and execute a command with that filename as one parameter, and with the
filename with a new extension as a different parameter. Like:
foreach filename.yxdb in dir
RunThisCommand.exe "<filename.yxdb SomeOtherStuff filename.csv>"
next

My google searches aren't really turning anything up for this. It seems
pretty basic.
Thanks in advance.
 

My Computer

M

Marco Shaw [MVP]

#2
fr0man wrote:

> I've been using Powershell for a few months now as my command line interface
> and I'm loving it. But I haven't actually scripted anything yet and don't
> even know where to begin.
> I need a simple powershell script to loop through each file in a directory
> and execute a command with that filename as one parameter, and with the
> filename with a new extension as a different parameter. Like:
> foreach filename.yxdb in dir
> RunThisCommand.exe "<filename.yxdb SomeOtherStuff filename.csv>"
> next
>
> My google searches aren't really turning anything up for this. It seems
> pretty basic.
> Thanks in advance.
Interactively, this would look something like:

PSH>$files=get-childitem .
PSH>foreach ($file in $files) {

>> write-host "run.exe `"<$file something filename.csv>`""
>> }
>>
There's some problems with the above though, depending on what you have
in the current directory or whether you want to do this recursively.
Most the changes are just relating to the first line where you get your
files.

# Get me just *.yxdb files
$files=get-childitem . *.yxdb|where-object {!($_.psiscontainer)}

# Do the above recursively
$files=get-childitem . *.yxdb -rec|where-object {!($_.psiscontainer)}

So I've used write-host to demonstrate.

Also, if you start going through directories recursively, you may need
to use "$file.fullname" versus just "$file".

Now as for creating scripts, you just put the above commands into a .ps1
file and you're off...

Good luck!

Marco



--
Microsoft MVP - Windows PowerShell
http://www.microsoft.com/mvp

PowerGadgets MVP
http://www.powergadgets.com/mvp

Blog:
http://marcoshaw.blogspot.com
 

My Computer