0

I'm trying to check if a directory exists, and if it does replace all files in that directory with updated files from another directory.

$path = "C:\mypath\config"
if([System.IO.Directory]::Exists($path)){
    $files = Get-ChildItem -Path $path | Select-Object "Name"
    ForEach ($File in $files)
    {
        Copy-Item -Path "C:\tmp\$File" -Destination "$path\$File.txt"
    }
}

I keep getting an error with the Copy-Item command because the $File is returning @{Name=filename} instead of just the name of the file. I've tried using $File.name, $File.basename, etc. but none of those appear to work. How do I get Powershell to not wrap the filename in "@{Name=}"?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Gary Henning
  • 80
  • 1
  • 2
  • 10

2 Answers2

2

You've got it almost right, you just need to use the -ExpandProperty parameter for Select-Object.

$files = Get-ChildItem -Path $path | Select-Object -ExpandProperty "Name"

This will get you an array of strings that are the names of the files.

What you had previously is an array of custom objects with the Name property copied from the file-info objects.

mklement0
  • 382,024
  • 64
  • 607
  • 775
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
1

An alternative way to access the name is to reference the name property directly:

$files = (Get-ChildItem -Path $path).name
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27