Remove white space from PowerShell output - powershell

I'm returning the mail property of a distribution group within Active Directory using the command below in PowerShell.
Get-ADGroup $GroupName -Properties Mail | Select-Object Mail | Format-Wide
The output looks like (asterisks used to represent white space):
*
*
mygroup#mycompany.com
*
*
Is there any way that I can remove the white space added at the beginning and end of the output?

I think this should work (V2):
(Get-ADGroup $GroupName -Properties Mail | Select-Object Mail | Format-Wide | out-string).split("`n") -match '\S'
Edit: that's way more complicated than it needs to be.
(Get-ADGroup $GroupName -Properties Mail | Select-Object Mail | Format-Wide | Out-String).trim()

That is how PowerShell formats output. I have complained on several occasions about the excess blank lines before and after output. If you want to avoid that, then you format the output yourself. You can do that like so:
$res = #(Get-ADGroup $GroupName -Properties Mail | Select-Object Mail)
for ($i = 0; $i -lt $res.Length - 1 + 4; $i += 4) {
"{0,-28} {1,-28} {2,-28} {3,-28}" -f $res[$i].Mail,$res[$i+1].Mail,$res[$i+2].Mail,$res[$i+3].Mail
}
This assumes your current console is 120 chars wide. If it is 80, change the -28 above to -18.
BTW the key point here is that PowerShell deals in objects and when it renders those objects to the screen it has a formatting engine that determines things like blank lines before and after the output. If you don't like PowerShell's default formatting, you're free to format objects (displaying whichever properties you want) as you please but it is a bit more work.
All that said, if the command returns only one object, why not just do this:
(Get-ADGroup $GroupName -Properties Mail).Mail
The Select-Object Mail, Format-Wide and Out-String are not necessary. Heck, with PowerShell V3 this will work even if the command returns multiple objects.

A combination of the examples in the checked answer worked for me in a similar situation:
... Format-Table | Out-String).split("`n").trim()
After re-reading the original question it seems I had a different problem to solve. I was looking for a way to trim white space from the end of output lines. The checked answer led me to try the above code which did what I was looking for.

Related

Simple PowerShell, Variable inside bracket no working

I'm missing formatting or something simple having to do with the variable. When I enter the variable data, no output. If I enter the SMTP: address manually script works fine.
$EmailAddressAlias=Read-Host "Enter the FULL Email Address to find the associated Mailbox "
Get-Mailbox -Identity * |
Where-Object {$_.EmailAddresses -like 'SMTP:$EmailAddressAlias'} |
Format-List Identity, EmailAddresses
I see two issues here, and a suggestion. You've got a variable inside single quotes, and you have no wildcards in your -like comparison. In order for the variable to expand into its value you need to use double quotes like this:
$_.EmailAddresses -like "SMTP:$EmailAddressAlias"
Also, when you use -like with no wildcards you may as well be using -eq. Lastly, you should really filter at the Get-Mailbox level rather than getting all mailboxes, and then filtering for just the one you want. You may want to try this instead:
Get-Mailbox -Filter "EmailAddresses -like '*$EmailAddressAlias*'" | Format-List Identity, EmailAddresses

Fax number update script, how to reverse?

I have created a script that would allow for the addition of the values "1-" to the beginning of our current AD fax numbers. I am running this in a test environment and the script runs exactly as I want it. I am looking for a failback and I can't seem to get that script to remove the "1-" it instead removes the 1 from the beginning and the final number from the end of the fax so the output looks like this: "-(###)-###-###" instead of looking like the correct number format "(###)-###-####"
Get-ADUser -Filter {facsimileTelephoneNumber -like "*"} -Properties facsimileTelephoneNumber| foreach {Set-ADUser -Identity $_ –replace #{facsimileTelephoneNumber="1-$($_.facsimileTelephoneNumber)"}}
Get-ADUser -Filter {facsimileTelephoneNumber -like "*"} -Properties facsimileTelephoneNumber| foreach {Set-ADUser -Identity $_ –replace #{facsimileTelephoneNumber="$(($_.facsimileTelephoneNumber).Substring(1,($_.facsimileTelephoneNumber.length) -2 ))"}}
Following my answer to your previous question where the 1- is added to the fax number, this is how you can reverse that.
I see in your question you are trying to do it all as one-liners, thereby skipping all possibility to check your code step-by-step. Using the first oneliner in your question also prepends 1- to simply every faxnumber found, regardless if it is needed or not.
Especially when just starting PowerShell, writing things out is a good thing.
Having said that, here's the code to remove the leading 1- from faxnumbers
# Remove leading '1-' from ADUsers faxnumbers
Import-Module ActiveDirectory
# get all users in the specified OU that have a fax number starting with '1-'
Get-ADUser -LdapFilter '(facsimileTelephoneNumber=1-*)' -SearchBase 'OU=UserAccounts,DC=YourDomain,DC=com' -Properties 'Fax' | ForEach-Object {
# using Substring() to remove the first two characters. See: https://ss64.com/ps/substring.html
$newFax = ($_.Fax).Substring(2)
Write-Host "Setting Faxnumber to '$newFax' for user $($_.Name)"
# remove the '-WhatIf' if you are sure the number may be changed
$_ | Set-ADUser -Fax $newFax -WhatIf
}
Hope this helps

I have a .csv with thousands of emails, and I need to use Active Directory to find the state of a particular, custom variable, using powershell

I'm new and don't know enough about powershell.
I've got a .csv that is nothing but "EMAILS" for the header and some 6000 emails under it. (email1#company, email2#company, etc.)
I need to find the state of a particular, custom property for each one.
Individually, I know that I can run
Get-ADUser -Filter {mail -eq 'email#company'} -properties customproperty
in order to find one particular user's state.
I have been hitting my head against a wall trying to make it work with import-csv and export-csv, but I keep getting red all over my console.
Can someone point me an to example where import-csv and export-csv are used properly, with a command run against the contents?
Here's what I would do.
First, fetch all users that have email addresses in AD, and save them into a hashtable. This will make lookups absurdly faster and place less overall load on your domain controller. If you've got 100,000 user accounts it may not be the best option, but I expect that it will be in general.
$ADUsers = #{};
Get-ADUser -Filter "mail -like '*'" -Properties mail, customproperty | ForEach-Object {
$ADUsers.Add($_.mail, $_.customproperty);
}
Now you import the CSV and do lookup using a calculated property with Select-Object, and export it back out.
Import-Csv -Path $InputFile | Select-Object -Property emails, #{n='customproperty';e={$ADUsers[$_.emails]}} | Export-Csv -Path $OutputFile -NoTypeInformation;
So without seeing the code of what you posted, where I think you will run problems is with how interaction of two things.
The first will be that when you use the Import-CSV cmdlet. You will receive an array of objects with a property for each column and not an array of strings.
This is ties into the second part of the issue which is the sensitivity of the AD module filter. But the short answer is don't use {} inside the filter because it will break if you use {mail -eq $ImportedCSV.EMAILS}.
mklement0 has a wonderful answer that goes into the details. But a simple rule of thumb is "double quote outer, single quote" inner.
So you could expand the EMAILS property either with Select-Object -ExpandProperty EMAILS to have an array which works inside {} or you could use "mail -eq '$ImportedCSV.EMAILS'".
Here is an example with both the expansion and using the "property -eq '$variable'" style filter:
Import-CSV C:\Example\Path.csv |
Select-Object -ExpandProperty EMAILS |
ForEach-Object {
Get-ADUser -Filter "mail -eq '$_'" -Properties customproperty
} |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
Please use below code
$csvInput = Import-CSV C:\Example\test.csv
Foreach ($line in $csvinput) {
Get-ADUser -Filter {mail -eq $line.mail} -Properties mail, customproperty |
Select-Object mail,customproperty |
Export-CSV C:\Example\OutputPath.csv -NoTypeInformation
}

Powershell pipe variables into get-user command

I am trying to pipe a list of email addresses into a get-user command in powershell
$email = get-content -path "c:\temp\file.csv" get-user -indentity $email | select-object userprincipalname,department,phone,name | format-table | out-file c:\temp\file.txt
Welcome to SO.
Lets see... where to start
Email Address is not one of the value recognized for Identity
It is spelled -identity
Don't use Format-table for object output.
Department is not one of the default values returned.
There is no AD attribute just called phone
It's Get-Aduser not get-user
Don't know if it was just a copy paste accident but you have multiple lines as one.
-Identity expects one value. Not an array of names.
Knowing that lets see if we can take a stab at what you were trying to do. Assuming that your file "c:\temp\file.csv" only contained addresses with no header (since that is how you were treating it.)
Get-Content c:\temp\file.csv | ForEach-Object{
Get-ADUser -Filter "emailaddress -eq '$_'" -Properties department,OfficePhone
} | Select-Object UserPrincipalName,Department,OfficePhone,Name | Export-CSV C:\temp\outputfile.csv -NoTypeInformation
There is no error correction here so you might need to look into an -ErrorAction try/catch combination. I encourage you to look that up on your own.

Get-ADUser filter by property length

I can't seem to figure this out to save my life.
I want to grab all AD users where their SAMAccountName length is equal to 6.
I'm hoping for something like this
Get-ADuser -filter "samaccountname.length -eq 6" | out-file $outputFile -append
I'm writing a massive script to first dump all AD users, then loop through each dumped user and update some attributes. This script will be run often, so I want to make it as efficient as possible. One area that I thought could be improved is the dump process.
We have about 15 thousand users in AD, but I'm only interested in 4 thousand, specifically, the ones for which their SamAccountName is 6 characters. For this reason, I don't want to fill my ID output file with about 11 thousand unnecessary IDs.
I want to try and avoid an inline for-each if possible.
Any help would be greatly appreciated.
Try this:
Get-ADuser - filter * | ? { $_.samaccountname.length -eq 6} | out-file -$outputfile -append
I usually do it with Get-QADuser (from Quest module) but I think Get-ADUser is same.
If $_.samaccountname isn't a string maybe you have to use:
$_.samaccountname.tostring().length
EDIT:
Get-ADUser -Filter * -Properties samaccountname | ? {$_.samaccountname.length -eq 6}
Get-ADuser | where { $_.samaccountname.length -eq 6 } | out-file $outputFile -append