Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell to get a file name in a directory

Tags:

powershell

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?

like image 982
user3749620 Avatar asked Oct 27 '25 15:10

user3749620


1 Answers

You need to use the Get-ChildItem cmdlet.

Get-ChildItem C:\Users\Bruce\deploy\*.txt | Select-Object -ExpandProperty Name | Out-File C:\Users\Bruce\process.txt -Force -Append

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:

>  get-alias | ? {$_.DisplayName -ilike "*get-childitem*" }

CommandType     Name
-----------     ----
Alias           dir -> Get-ChildItem
Alias           gci -> Get-ChildItem
Alias           ls -> 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.

like image 194
arco444 Avatar answered Oct 29 '25 05:10

arco444



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!