Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Foreach and outputting to a file, again

Status
Not open for further replies.

billieT

MIS
Dec 11, 2001
107
NZ
I'm trying to get a listing of files and their sizes, if their creation date was greater than 3 years ago. This is fine, up until the point I try to output to a CSV file - it seems the part where I'm trying to append to a list is not working correctly. I get the "Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null." error.

Any illumination about what I'm missing in this script would be helpful. It's the first PS script I've written that isn't a one-liner. The one-liner where I output all the files in a directory on screen with the specified fields works fine!

Code:
$list = @()
foreach ($i in Get-ChildItem T:\ad* -recurse)
{
	if ($i.CreationTime -gt ($(Get-Date).AddYears(-3)))
	{
	$list += select fullname, CreationTime, LastWriteTime,  @{Name="Mbytes";Expression={$_.Length / 1Mb}}
    }
}

$list | export-csv c:\scripts\gdrive-a.csv
 
There are a few things going on here:
1. Your -gt actually needs to be -lt. I made the same mistake when first working with dates. Dates Before means Less Than
2. The Select-Object statement expects an object as input. The way your assignment statement is set, it has no object to pull the data from

$list doesn't get assigned anything and is therefore null when you try to export it. That's why export-csv complains.

2 ways to do this
Use the inputObject parameter of Select-Object, so it has data to pull
Code:
$list = @()

foreach ($i in Get-ChildItem T:\ad* -recurse)
{
   if ($i.CreationTime -lt (get-date).AddYears(-3))
      {
         $list += select FullName, CreationTime, LastWriteTime, @{Name="Mbytes"; Expression={$_.Length / 1MB}} -inputObject $i
      }
}

$list | export-csv c:\scripts\gdrive-a.csv -NoTypeInformation
One-liner (though long)
Code:
gci T:\ad* -recurse | where {$_.CreationTime -lt (get-date).AddYears(-3)} | select FullName, CreationTime, LastWriteTime, @{Name="Mbytes"; Expression={$_.Length / 1MB}} | export-csv c:\scripts\gdrive-a.csv -NoTypeInformation
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top