0
$path = "c:\folder a"
$destFolder = "C:\" 
$subFolder = "\folder c\folder d\" 
$file = "file.txt" 

$dir = Get-ChildItem $path | select -first 10 | Sort-Object -Property CreationTime 

[array]::Reverse($dir) 

$dir | format-table FullName  

$fullPath = @() 

ForEach ($i in $dir) { 
    $fullPath += $i + $subFolder + $file 
} 

$i = 0 

while ($i -lt $fullPath.Count) { 

    $exists = Test-Path $fullPath[$i] 

    if ($exists){ 
        Copy-Item -Path $fullPath[$i] -Destination $destFolder 
        break 
    } 
    $i++ 
}

having trouble getting &fullpath to work

edit:

&fullpath displays all the folder in the directory then adds the subfolder+file at the end.

I want it to take the 1 file path at a time from &dir and add the subfolder+file

sorry if I haven't explained it very well.

Im a total beginner at this kind of stuff

2
  • What, exactly, is wrong? What do you expect to happen and what really happens? Commented Apr 24, 2015 at 8:08
  • A generic hint, review the logic behind your code. For example you sort your array by a property then you reverse it. Isn't simpler sorting descending? dir = xxx | Sort-Object -Property CreationTime -Descending. Then you use foreach to compute a path and instead of doing the other actions there you save the path and cycle through it using a while. Does it make sense? ForEach ($i in $dir) { $fullPath += $i + $subFolder + $file; $exists = Test-Path $fullPath; if ($exists){ ... } } Commented Apr 24, 2015 at 8:17

1 Answer 1

2

I think what you need is this:

$path = "c:\temp"
$destFolder = "C:\" 
$subFolder = "\folder c\folder d\" 
$file = "file.txt" 

$childItems = Get-ChildItem $path | select -first 10 | Sort-Object -Property CreationTime -Descending

forEach ($item in $childItems) 
{
    $fullPath = Join-Path -Path $item.FullName -ChildPath "$subFolder$file" 
    if (Test-Path -Path $fullPath)
    {
        Copy-Item -Path $fullPath -Destination $destFolder
    }
} 
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.