Question:
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?
Answer:
You need to use the Get-ChildItem
cmdlet.
1 2 |
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
:
1 2 3 4 5 6 7 8 |
> 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.