Powershell - foreach clarification

I am learning powershell and I need someone to give me an initial push to get me through the learning curve. I'm familiar with programming and dos, but not powershell.

What I would like to do is list all the files from my designated directory and push the filenames into an array. I am not very good at syntax and when I tried to run my test I was asked a question about entering parameters.

Can someone please enlighten me and show me the correct way to get what I want?

This is what the force was asking me:

PS D:\ABC> Test.ps1
cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters:
Process[0]:

      

This is my test:

[string]$filePath = "D:\ABC\*.*";

Get-ChildItem $filePath | foreach
{
 $myFileList = $_.BaseName;
 write-host $_.BaseName
}

      

Why did ps ask about Process [0]?

I would like ps to list all the files from a directory and process the results for a foreach where I put each file in the $ myFileList array and print the filename as well.

+3


source to share


1 answer


Don't confuse foreach

(assertion) with ForEach-Object

(cmdlet). Microsoft does a terrible job with this because there is an alias foreach

that points to ForEach-Object

, so when you use foreach

you need to know which version you are using based on how you are using it. Documenting them makes it worse, making them even more difficult.

The one you are trying to use in your code, ForEach-Object

so you must use its fully qualified name to distinguish it. From there, the problem is that the block {

starts on the next line.

{}

used in PowerShell for statement-related code blocks (like while

loops), but also used to denote an object [ScriptBlock]

.

When you use ForEach-Object

it expects a scriptblock, which can be done positionally, but it must be on the same line.

Conversely, since it foreach

is an operator, he can use it {}

on the next line.



Your code with ForEach-Object

:

Get-ChildItem $filePath | ForEach-Object {
 $myFileList = $_.BaseName;
 write-host $_.BaseName
}

      

Your code with foreach

:

$files = Get-ChildItem $filePath
foreach ($file in $Files)
{
 $myFileList = $file.BaseName;
 write-host $file.BaseName
}

      

+4


source







All Articles