Using PowerShell to get a file name in a directory


I have a directory that contains a file called Bruce.txt. I need to copy the file name to a flat file. I tried using the copy-item command but that copies the contents not the name.

Is there a command to copy Bruce.txt (the name not the contents) to a flat file? So after it completes there will be a file called process.txt and its contents will be Bruce.txt. I tried using

Copy-Item -Path "C:\Users\Bruce\deploy\*.txt" -Destination "C:\Users\Bruce\process.txt".

Inside of deploy is a text file called Bruce.txt with the contents of select count() from EMP_NR.

I need Bruce.txt the name copied to process.txt not the Select count() etc.

For Shell script I use the ls command and it works wonderful what can I use for Powershell?


You need to use the Get-ChildItem cmdlet.

However, as you’re using PowerShell, ls would actually work for you here, as would gci and dir as they’re all aliases for Get-ChildItem:

You can also use > or >> instead of piping to Out-File if you so wish.

Because the Get-Childitem cmdlet returns a list of objects, you then need to also select which information you want to extract from the object. If you do a ls in a directory with some content, you will see the contents are formatted into a table.

By using the Select-Object cmdlet, you can extract the object properties you want to write to your file, in this case the Name property.


Using PowerShell to get a file name in a directory by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply