简体   繁体   中英

Add smtp Proxy Addresses from users listed in a text file using PowerShell

I am trying to create a simple script to add Proxy Addresses to the AD field using PowerShell.

I was able to get it working using this, but now I am at a roadblock on how I can do this importing the usernames from a text file.

$Username = Read-Host -Prompt "Enter the username'
Set-AdUser $Username -add @{ProxyAddresses = "smtp:$Username@example.com,smtp:$Username@marketing.example.com" -split ","}

What I want to do now is instead of prompting for a username to be entered I just want to have a text file with username like this.

Text File Of Usernames: These will all be on a separate line. I am not sure how to format that way on here.

jallen
sdiggs
gdavis
mhyde
twhite

I am confused how to go forward with this. To my understanding I want to use Get-Content to create the username array and then for each line in the text file add the proxy addresses.

$Username = Read-Host -Prompt "Enter the username'
Set-AdUser $Username -add @{ProxyAddresses = "smtp:$Username@example.com,smtp:$Username@marketing.example.com" -split ","}

I want to remove the need for user input and import the username variables from a text file.

Assuming you have the txt file with each user in a new line as shown in your question, you're right, you can use Get-Content to read your file then you need to loop over each line:

(Get-Content path\to\yourfile.txt).Trim() | ForEach-Object {
    try {
        Set-AdUser $_ -Add @{ ProxyAddresses = "smtp:$_@example.com,smtp:$_@marketing.example.com".Split(",") }
    }
    catch {
        # can do error handling here
        Write-Error $_
    }
}

The use of Trim() in this example is so it removes any excess of white space from the beginning and end of all lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM