Powershell Get-Children

jstevens
GoldLounger
Posts: 2618
Joined: 26 Jan 2010, 16:31
Location: Southern California

Powershell Get-Children

Post by jstevens »

I can use this script to list the folders and files in a directory. What I would like to do is add another column with today's date. I can create a variable for the date but do no know how to incorporate into the script.

Example: $a = Get-Date

Code: Select all

Get-ChildItem -Path C:\Test -Name

Logs
anotherfile.txt
Command.txt
CreateTestFile.ps1
ReadOnlyFile.txt
Your suggestions are appreciated.
Regards,
John

jstevens
GoldLounger
Posts: 2618
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: Powershell Get-Children

Post by jstevens »

Here is the solution I came up with.

Code: Select all

$a=Get-Date -Format U
$obj = Get-ChildItem -Path "C:\Test" -Name

Foreach ($i in $obj)
{
    $a + "|" + $i
}
Results:
Friday, July 30, 2021 2:56:11 PM|Logs
Friday, July 30, 2021 2:56:11 PM|anotherfile.txt
Friday, July 30, 2021 2:56:11 PM|Command.txt
Friday, July 30, 2021 2:56:11 PM|CreateTestFile.ps1
Friday, July 30, 2021 2:56:11 PM|ReadOnlyFile..txt
Regards,
John

jstevens
GoldLounger
Posts: 2618
Joined: 26 Jan 2010, 16:31
Location: Southern California

Re: Powershell Get-Children

Post by jstevens »

A minor tweak to write to a text file.

Code: Select all

$a=Get-Date -Format U
$obj = Get-ChildItem -Path "C:\Test" -Name
$File   = 'C:\Test\testfileOutput.txt'
$Stream = [System.IO.StreamWriter]::new($File)

Foreach ($i in $obj)
{
  $Stream.WriteLine($a + "|" + $i)
}

$Stream.Close()
Regards,
John