【问题标题】:Extracting email addresses from user account in PowerShell从 PowerShell 中的用户帐户中提取电子邮件地址
【发布时间】:2021-08-15 19:22:19
【问题描述】:

我需要将在文件共享中的文件上找到的用户帐户映射到电子邮件地址(以便在后续步骤中迁移它们)。

我快到了,但我收到的电子邮件地址格式很奇怪,如下所示:

@{EmailAddress=first.last@xx.xxxxx.com}

我怎样才能把它当作一个普通的字符串变量呢?喜欢: "first.last@xx.xxxxx.com"

$Files = Get-ChildItem -Path $SourceFilesPath -Force -Recurse

ForEach ($File in $Files)
{

    $createdDate = (Get-Item "$($File.Directory)\$($File.Name)").CreationTime
    $modifiedDate =  (Get-Item "$($File.Directory)\$($File.Name)").LastWriteTime

    $createdBy = ((Get-Acl -Path "$($File.Directory)\$($File.Name)").Owner).Split("\")[-1]

    $email = (Get-ADUser $createdBy -Properties EmailAddress) | select EmailAddress
    
   Write-host $email
}

【问题讨论】:

    标签: string powershell data-structures


    【解决方案1】:

    我会使用(Get-ADUser $createdBy -Properties EmailAddress).EmailAddressGet-ADUser $createdBy -Properties EmailAddress | Select-Object -ExpandProperty EmailAddress。这些是等价的。

    Select-Object 将显示一个属性,但即使您只选择一个,它仍会将其保留为对象的属性。要仅提取属性值,您需要指定 -ExpandProperty 参数。但是,当您这样做时,您只能指定一个要扩展的属性。

    您还可以真正简化您的代码。当您已经掌握了所需的大部分信息时,您就是在重复自己。

    $Files = Get-ChildItem -Path $SourceFilesPath -Force -Recurse
    
    ForEach ($File in $Files)
    {
    
        $createdDate = $File.CreationTime
        $modifiedDate =  $File.LastWriteTime
    
        $createdBy = $File.GetAccessControl().Owner.Split("\")[-1]
    
        $email = (Get-ADUser $createdBy -Properties EmailAddress).EmailAddress
        
        Write-host $email
    }
    

    另外,您不需要指定"$($File.Directory)\$($File.Name)"。你可以指定$File.FullName

    了解 Powershell 的第一件事是一些语言自省。

    $Files[0] | Format-List -Properties *$Files[0] | fl * 将列出对象的所有属性。

    $Files[0] | Get-Member$Files[0] | gm 将列出对象的成员函数。

    $Files[0].GetType().FullName 将列出对象的类型。您可以 Google 搜索并查看对象类的 .Net 参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多