How to skip empty cells in a csv when using PowerShell to import Email Addresses?

家住魔仙堡 提交于 2019-12-25 08:34:21

问题


I am trying to run the following script to import email addresses in powershell:

Import-CSV "C:\AliasesTest.csv" | foreach-object {
    Set-Mailbox -Display Name $_.Name -EmailAddresses @{add=$_.Alias1,$_.Alias2,$_Alias3}}

It works fine, unless the csv has an empty cell under one of the Alias columns, at which point the following error is produced:

"The address '' is invalid: "" isn't a valid SMTP address..:

How can I construct my script to just ignore empty cells when it comes across them?


回答1:


Use a Where-Object filter prior to ForEach-Object like this:

Import-CSV "C:\AliasesTest.csv" | Where-Object {
        $_.Alias1 -and $_.Alias2 -and $_Alias3 
    } | foreach-object { $_ }

If the alias' are empty strings they will be skipped. You don't have to use -and for all of them, if just one value is fine change to use -or.




回答2:


Filter the aliases to take out the empty ones:

Import-CSV "C:\AliasesTest.csv" | foreach-object {
    $aliases = @($_.Alias1,$_.Alias2,$_Alias3) | where-object{$_};
    Set-Mailbox -Display Name $_.Name -EmailAddresses @{add=$aliases}}



回答3:


Check each property (alias) to see if it is empty, and only add the ones with values to the array inside your hash table:

Import-CSV "c:\AliasesTest.csv" | ForEach-Object {
    #Save the CSV row for use in another loop later
    $CSV = $_

    Set-Mailbox -DisplayName $_.Name -EmailAddresses @{add = ("Alias1","Alias2","Alias3" | ForEach-Object { $Csv.$_ } | Where-Object{$_}) }
}

What that craziness does is, create a new hashtable with a key "add" that has a value of a sub expression. The sub expression has an array of property names that you want to check that it iterates over, converting each name to the value of that property, then filters out the empty ones.



来源:https://stackoverflow.com/questions/10559486/how-to-skip-empty-cells-in-a-csv-when-using-powershell-to-import-email-addresses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!