Search code examples
powershellactive-directorytrim

Trim PowerShell Output File


I'm new to PowerShell as my posts can attest, but I'm trying to learn it and update our Organization from the mid 1950's to 2018 as far as Automation goes. What I'm doing is cleaning up Active Directory (AD) of old machines. I have a script I run identify them and output them to a TXT file. I then have various scripts I run against that TXT file to move bitlocker keys and move the machines out of AD and Delete them.

However my output file is adding spaces at the end of the computer names, thus subsiquent scripts can't identify files because its looking for 'computername .txt' or 'computername * instead of 'computername.txt' and 'computername' I know there is Trim function, I just can't figure out for the life of me, where to put the trim command to clean up the output. The script is below with obvious information omitted for security reasons.

## Script will pull all systems with Computer account password over 90 days old.  
##____________________________________________________________________________________

$d = [DateTime]::Today.AddDays(-90)
Get-ADComputer -Filter 'PasswordLastSet -le $d' -Properties PasswordLastSet -SearchBase "OU=WIN10,OU=,OU=,DC=,DC=,DC=,DC=" | FT Name | Out-File \\SERVER\Software\1Scripts\Over_90_Day\Computer_over_90.txt

Solution

  • Format-Table (ft) or Format-List (fl) only works if it is the last element in the Pipeline and only to format data within the console. It's not meant to format data to save in a file.

    Select-Object -ExpandProperty is what you are looking for:

    Get-ADComputer -Filter 'PasswordLastSet -le $d' -Properties PasswordLastSet -SearchBase "OU=WIN10,OU=,OU=,DC=,DC=,DC=,DC=" | Select-Object -ExpandProperty Name | Out-File \\SERVER\Software\1Scripts\Over_90_Day\Computer_over_90.txt