0

I am dabbling with Powershell and attempting to replace the old console 'for' command. For instance, to encode a folder of *.WAV files using "FLAC.EXE" which is located on the path:

(Get-ChildItem)|Where-Object{$_.extension -eq ".wav"}|flac "$_.Name"

However I get a result where clearly Flac is not receiving the file name and only the literal string "$_.Name".

This is a very obvious problem I am sure, but I am still feeling my way along at this stage.

1 Answer 1

1

Try it like this:

Get-ChildItem *.wav | Foreach-Object {flac $_.FullName}

The automatic variable $_ is typically only valid inside the context of a scriptblock that is part of a pipeline e.g. {...}.

Sign up to request clarification or add additional context in comments.

4 Comments

Excellent! I am only just starting to get into PS. However it seems there is a clear dichotomy between scripts and immediate usage. For multi-step processes entered as a script you will use conventional, vaguely VB control structures like for/foreach/if/elsif etc. However if you are working at the prompt for immediate execution you use the appropriate 'cmdlet' analogue to these structures such as "Foreach-Object". Not very intuitive, but I suppose it was a reasonable approach for MS to rationalize those execution modes. First and foremost I think I need to learn the most useful 'cmdlets'.
@Gemman, I don't see a dichotomy. Personally I try to use the pipeline where I can because that seems more natural. I use Foreach-Object in scripts. The body of Foreach-Object can be spread over multiple lines of code.
I wish the console had been a multi-line scripting environment. That way you could enter 'variables', 'if's and 'for's naturally over multiple lines and then execute when you were finished with a control-return or some such combinations. In comparison the cmdlet model seems quite... inscrutable - at least to someone used to normal C++ or VB. At least at first.
Have a look at PSReadLine on GitHub. Not only does it improve basic console line editing functionality but it gives a decent multiline editing capability.

Your Answer

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