Search code examples
powershellquest

Output custom value into PS table when value returned is $null or similar


I am generating a report out of AD of users with contract expiry dates listed. So far I have been able to come up with this, which outputs to a CSV file with custom headings and the date shortened.

Get-QADUser -SizeLimit 0 -IncludedProperties AccountExpires,Domain,Name -DontUseDefaultIncludedProperties | Where { $_.Title -ne "Resource" } | Select @{Label="Domain";Expression={(($_.Domain).Name)}},@{Label="Employee Name";Expression={($_.Name)}},@{Label="Contract Expiry Date";Expression={(($_.AccountExpires).ToShortDateString())}},title,department,Office | Export-Csv C:\ExportForHR.csv -NoTypeInformation

What I'm wanting to do is put a custom value in column "Contract Expiry Date", if they have no value.

I.e. if I don't have a contract, the default value is null, therefore nothing shows in the spreadsheet. But what if I wanted to put "No contract expiry" or "Full time expiry" in the field instead?

Couldn't find anything that would be suitable using the command above. I could probably write a full powershell script to output to a CSV file by not using things like Select and export-csv, but I'd rather not, unless I really have to.


Solution

  • You're about 95% of the way there. The script block in the Expression section of Select-Object is a full script block, so you can perform the test right in there:

    Get-QADUser -SizeLimit 0 -IncludedProperties AccountExpires,Domain,Name -DontUseDefaultIncludedProperties | 
    Where { $_.Title -ne "Resource" } | 
    Select-Object 
      @{Label="Domain";Expression={(($_.Domain).Name)}},
      @{Label="Employee Name";Expression={($_.Name)}},
      @{Label="Contract Expiry Date";Expression={
        if ($_.AccountExpires -ne $null) { 
          $_.AccountExpires).ToShortDateString()
        } else { 
          $CustomValue 
        }
      },
      title,
      department,
      Office 
    | Export-Csv C:\ExportForHR.csv -NoTypeInformation