Click here to Skip to main content
16,022,223 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I'd like to process several directories enumerating their files, passing the file name to Split-Path and the output from Split-Path to a non-cmdlet program.

I can get the directories and enumerate them passing to Split-Path to just display the fine name minus extension and path.

Question is how do I reference the output on a command line?

For the first part I use the following and it works as expected:

PowerShell
$source = @('Dir 1', 'Dir 2', 'Dir 3')

foreach($x in $source) {get-childitem -Path $x | split-path -leafbase}


Now I'd like to pass the output to a command line, as an example:

Write-Output "File Name: " ?output here?

Cannot figure it out.
Many thanks.

What I have tried:

<pre lang="PowerShell">$source = @('Dir 1', 'Dir 2', 'Dir 3')

foreach($x in $source) {get-childitem -Path $x | split-path -leafbase}
Posted

Something like this perhaps?
PowerShell
$source = @('Dir 1', 'Dir 2', 'Dir 3')

foreach ($x in $source) {
    $files = Get-ChildItem -Path $x -ErrorAction SilentlyContinue | Split-Path -LeafBase
    foreach ($file in $files) {
        Write-Output "File Name: $file"
    }
}
 
Share this answer
 
Oopps. I left the Split-Path off of my test code. That's goign to give you the filepath and, ultimately, the string that contains the filename.

So, to figure out what you're getting back from a command, you can see what the object is using something like this:
PowerShell
$x = ...whatever command...
Write-Output $x.GetType()


That Get-Child|Split-Path command isn't going to return a single filename. It'll return an array of FileInfo or DirectoryInfo objects, one array for each source directory. You can see that with the following modifications :
PowerShell
$source = @('Dir 1', 'Dir 2', 'Dir 3')
foreach ($x in $source)
{
    $items = Get-ChildItem -Path $x | Split-Path -Leaf
    Write-Output "ITEMS TYPE: " $items.GetType()
    Write-Output $items
    Write-Output 
    foreach ($item in $items)
    {
        Write-Output "ITEM TYPE: " $item.GetType()
        Write-Output $item
    }
}

So, to get the actual name of the directory, you would have to get its Name property. Replace the above inner foreach with this:
PowerShell
foreach ($item in $items)
{
    Write-Output $item.Name
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900