How to find email adress of AzureAD user with ps1 script - powershell

here is the script i use to export the data from AzureAD to csv.
Connect-AzureAD
Connect-MsolService
$date = Get-Date -UFormat "%d%m%Y"
$dateInfo = Get-Date
$Results = #()
$Roles = Get-AzureADDirectoryRole
foreach ($Role in $Roles) {
$MemberRole = Get-AzureADDirectoryRoleMember -ObjectId $Role.ObjectId
foreach ($Membre in $MemberRole ) {
$InfosUsers = Get-MsolUser -ObjectId $Membre.ObjectId
$List = New-Object System.Object
$List | Add-Member -type NoteProperty -name Compte -Value $Membre.DisplayName
$List | Add-Member -type NoteProperty -name Active -Value $Membre.AccountEnabled
$List | Add-Member -type NoteProperty -name Role -Value $Role.DisplayName
$List | Add-Member -type NoteProperty -name NumeroTel -Value $InfosUsers.StrongAuthenticationUserDetails.PhoneNumber
$Results += $List
}
}
$Results | Export-Csv path/to/the/file/ -NoTypeInformation
Disconnect-AzureAD
The things is that i would like to get mail adresse from user and i dont know how to do ?

Happy to see you already got your answer, here is one alternative way you can approach to get the email address of Azure AD user.
I did Few changes in your code (ie I have removed Connect-MsolService and replace Get-MsolUser with Get-AzADUser.) and I am able to perform the operation you are trying to do .
Connect-AzureAD
$date = Get-Date -UFormat "%d%m%Y"
$dateInfo = Get-Date
$Results = #()
$Roles = Get-AzureADDirectoryRole
foreach ($Role in $Roles) {
$MemberRole = Get-AzureADDirectoryRoleMember -ObjectId $Role.ObjectId
foreach ($Membre in $MemberRole ) {
$InfosUsers = Get-AzADUser -ObjectId $Membre.ObjectId
$List = New-Object System.Object
$List | Add-Member -type NoteProperty -name Compte -Value $Membre.DisplayName
$List | Add-Member -type NoteProperty -name Active -Value $Membre.AccountEnabled
$List | Add-Member -type NoteProperty -name Role -Value $Role.DisplayName
$List | Add-Member -type NoteProperty -name NumeroTel -Value $InfosUsers.StrongAuthenticationUserDetails.PhoneNumber
$List | Add-Member -type NoteProperty -name Email -Value $Membre.Mail
$List | Add-Member -type NoteProperty -name UPName -Value $Membre.UserPrincipalName
$Results += $List
}
}
$Results | Export-Csv /RahulS -NoTypeInformation
Output---

Related

"Unable to obtain permission for "name of the share" | win2008r2 File Server

So a friend and i wrote a script so we could get some info about the share on our file server but i keep getting an error about the shares, I am a Domain Admin so i dont think the problem is with my permissions.
Here is the script:
$MyPath = "C:\File Share Info\Shares"
$shares = gwmi -Class win32_share -ComputerName $computer #| select -ExpandProperty Name
$AllObjects = #()
foreach ($share in $shares) {
$acl = $null
$ShareName = $share.Name
$ShareCaption = $Share.Caption
if ($ShareName -notlike "*$*"){
$objShareSec = Get-WMIObject -Class Win32_LogicalShareSecuritySetting -Filter "name='$ShareName'"
#-ComputerName $computer
try {
$SD = $objShareSec.GetSecurityDescriptor().Descriptor
foreach($ace in $SD.DACL){
$UserName = $ace.Trustee.Name
If ($ace.Trustee.Domain -ne $Null) {$UserName = "$($ace.Trustee.Domain)\$UserName"}
If ($ace.Trustee.Name -eq $Null) {$UserName = $ace.Trustee.SIDString }
[Array]$ACL = New-Object Security.AccessControl.FileSystemAccessRule($UserName, $ace.AccessMask, $ace.AceType)
$Identity = $ACL[0].IdentityReference.Value
$myObject = New-Object System.Object
$myObject | Add-Member -type NoteProperty -name ShareAccessType -Value $ACL[0].AccessControlType
$myObject | Add-Member -type NoteProperty -name Identity -Value $Identity
$myObject | Add-Member -type NoteProperty -name ShareRights -Value $ACL[0].FileSystemRights
$myObject | Add-Member -type NoteProperty -name SharePath -Value $Share.Path
$myObject | Add-Member -type NoteProperty -name ShareName -Value $Share.Name
$myObject | select ShareName, Identity, ShareRights, SharePath, ShareAccessType | Export-Csv "$MyPath\permissions.csv" -Append -Encoding Unicode #-NoTypeInformation -Delimiter "`t"
}
}
catch
{ Write-Host "Unable to obtain permissions for `"$ShareName`""; $share.Name | Out-File "$MyPath\Failed.txt" -Append}
}
}

powershell script to return all forwarding rules in org

I need to pull all forwarding rules for an exchange online environment, and output them to a csv. this sounds simple, but I have an additional caveat. there are 23,000 mailboxes in the org.
I was able to write the script I needed, it outputted the data, but it timed out.
then I was able to break out only certain mailboxes that were critical (11,000) but I was still timing out in powershell.
so finally, I found an article that detailed breaking up a script into blocks of 1,000, and running numerous sessions. and runs! it runs without timing out.
but it doesn't output to the csv anymore.
since my script has gone through several iterations, I'm pretty sure that my problem is the way I'm storing, or outputting the array, but for all my staring at this, I cant figure it out. short of asking the doc for a prescription of Adderall, I figured id ask here. below is the offending script.
the aliaslist.csv that it mentions is just a csv with a list of aliases for 11,000 mailboxes. if you would like to run your own tests, you can adjust $pagesize down and paste a few mailboxes into a csv called aliaslist, stored in c:\temp
Function New-O365ExchangeSession()
{
param(
[parameter(mandatory=$true)]
$365master)
#close any old remote session
Get-PSSession | Remove-PSSession -Confirm:$false
#start a new office 365 remote session
$365session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $365master -Authentication Basic -AllowRedirection
$office365 = Import-PSSession $365session
}
#set input variables
$path = "C:\temp"
$InputFile = aliaslist.csv"
$UserEmail = "admin#domain.com"
#set variables for csv usage
$Offset = 0;
$PageSize = 1000;
$MbxMax = (Import-Csv "$path/$InputFile").count
#Loop in the list and retrieve the device’s information
$file = “c:\temp\office365-$((get-date).tostring(“yyyy-MM-dd”)).csv”
$365master = get-credential $UserEmail
New-O365ExchangeSession $365master
# call the office365 remote connection function
do{
$mbxlist=#(import-csv "$path/$InputFile"|select-object -skip $Offset -First $PageSize)
"Process entry $($Offset) to $($Offset+$PageSize)"
#end csv input count reference
ForEach($mbx in $MbxList)
{
#Write to Host
"start Processing $($mbx.alias)"
#end Write to host,
#Check rules
$rules = Get-InboxRule -mailbox $_.alias | ? {$_.RedirectTo -ne $null -or $_.ForwardTo -ne $null -or $_.ForwardAsAttachmentTo -ne $null}
If ($rules -ne $null)
{
$rules | % {
#check for forwardAsAttachments
If ($_.ForwardAsAttachmentTo -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Forward As Attachment Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.forwardAsAttachmentTo -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $f -MemberType NoteProperty
If (Test-Path $file)
{
$mbx.alias + ”,” + ($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
#check for redirects
If ($_.redirectto -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Redirct Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.redirectto -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $c -MemberType NoteProperty
If (Test-Path $file)
{
$mbx.alias + ”,” + ($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
#check for forwards
If ($_.ForwardTo -ne $null)
{
$obj = New-Object system.object
$obj | Add-Member -name "NetID" -Value $_.alias -MemberType NoteProperty
$obj | Add-Member -name "ForwardType" -Value "Forward Rule" -MemberType NoteProperty
$obj | Add-Member -name "ForwardAddress" -Value $_.forwardto -MemberType NoteProperty
$obj | Add-Member -name "Enabled" -Value $_.Enabled -MemberType NoteProperty
$obj | Add-Member -name "Description" -Value $f -MemberType NoteProperty
If (Test-Path $file)
{
($obj | ConvertTo-Csv)[2] | Out-File $file –Append
}
Else
{
$obj | Export-Csv $file -Encoding ASCII -notypeinformation
}
}
$obj = $null
}
}
}
#increment the start point for the next chunk
$Offset+=$PageSize
#Call the office365 remote session function to close the current one and open a new session
New-O365ExchangeSession $365master
} while($Offset -lt $MbxMax)

esxi detailed Information

I want to get all the information from ESXi. I extracted the information in different CSV files, but once I want to merge them, it does not show all. But I would rather to create foreach to gather same information.
Add-PsSnapin VMware.VimAutomation.Core -ErrorAction "SilentlyContinue"
Import-Module ‚C:\Program Files\Microsoft Virtual Machine Converter\MvmcCmdlet.psd1‘
$datetime = Get-Date -Format "ddMMyyyy";
# Configuration Block
$User =
$Password =
$ESXiServer = "172.17.1.171"
# Connect to ESXi
$PWD = ConvertTo-SecureString -AsPlainText -Force -String $Password;
$SourceCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$PWD;
$sourceConnection = New-MvmcSourceConnection -Server $ESXiServer -SourceCredential $sourceCredential
$SourceVMName = (Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection).Name
$Datacenter = Get-Datacenter
$Datastore = Get-Datastore
$DataStoreLocation = $Datastore.ExtensionData.info.url
$Datastore = Get-Datastore
# Get-VMHostNetworkAdapter | fl *
Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, DHCPEnabled, DeviceName | Export-Csv C:\VMHostNetworkDetails_$datetime.csv -Delimiter ";"
Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection | select MemorySizeBytes, OperatingSystem, UsedSpacebytes | Export-Csv C:\VMRAmDetails_$datetime.csv -Delimiter ";"
$Global:DefaultVIServers | Select ProductLine,Version,Build, Port | Export-Csv C:\GlobalDetails_$datetime.csv -Delimiter ";"
#(Import-Csv C:\VMHostNetworkDetails_$datetime.csv) + #(Import-Csv C:\VMRAmDetails_$datetime.csv) + #(Import-Csv C:\GlobalDetails_$datetime.csv) | Export-Csv C:\ESxiDetails_$datetime.csv -Delimiter ";"
Note: get-vm does not work for me.
EDIT:
I tried to get the info by using foreach loop, but cannot get IP, SubnetMask, Mac, DHCPEnabled.$VMSysInfo.IPAddressdoes not give me any IP, but Get-VMHostNetworkAdapter | select VMhost, Name, IP, SubnetMask, Mac, DHCPEnabled, DeviceName gives me IP.
$VmInfo = vmware.vimautomation.core\Get-VM
$VMS = ($VmInfo).Name
$VCenter = #()
foreach ($VM in $VMS)
{
$HostServer = (($VmInfo | ? {$_.Name -eq $VM}).Host).Name
$VMSysInfo = Get-VMGuest -VM $VM
$MyObject = New-Object PSObject -Property #{
VMName = $VM
#VMHostName = $VMSysInfo.HostName
VMIP = $VMSysInfo.IPAddress
VMInstalledOS = $VMSysInfo.OSFullName
PowerState = ($VmInfo | ? {$_.Name -eq $VM}).PowerState
NumberOfCPU = ($VmInfo | ? {$_.Name -eq $VM}).NumCpu
MemoryGB = (($VmInfo | ? {$_.Name -eq $VM}).MemoryMB/1024)
VMDataS = (Get-Datastore -VM $VM).Name
#HostServer = (($VmInfo | ? {$_.Name -eq $VM}).Host).Name
#HostCluster = (Get-Cluster -VMHost $HostServer).Name
Datacenter = (Get-Datacenter -VM $vm).Name
#Notes = $vm | Select -ExpandProperty Description
Portgroup = (Get-VirtualPortGroup -VM $vm).Name
}
$VCenter += $MyObject
}
$VCenter | Select VMName,
#{N='VMIPAddress';E={$_.VMIP -join '; '}},
VMInstalledOS, PowerState, NumberOfCPU, MemoryGB,
#{N='VMDataStore';E={$_.VMDataS -join '; '}},
HostServer, HostCluster,Datacenter, Notes, Portgroup |
Export-Csv C:\test.csv -NoTypeInformation -Delimiter ";"
I changed the foreach loop and it works:
$VmInfo = vmware.vimautomation.core\Get-VM
#$VmInfo = (Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection).Name
$VMS = ($VmInfo).Name
$Data = #()
foreach ($VM in $VMS)
{
$Datacenter = Get-Datacenter
$Datastore = Get-Datastore
$SourceIP = ($global:DefaultVIServer).name
$DataStoreLocation = $Datastore.ExtensionData.info.url
$VMNetwork = Get-VMHostNetworkAdapter
$PortalGroup = Get-VirtualPortGroup -VM $vm
$MvmcSourceVirtualMachine = Get-MvmcSourceVirtualMachine -SourceConnection $sourceconnection
$VMCustom = New-Object System.Object
$VMCustom | Add-Member -Type NoteProperty -Name DataCenter -Value $Datacenter.Name
$VMCustom | Add-Member -Type NoteProperty -Name DataStoreName -Value $Datastore.Name
$VMCustom | Add-Member -Type NoteProperty -Name DataStoreLocation -Value $DataStoreLocation
$VMCustom | Add-Member -Type NoteProperty -Name NumberOfCPU -Value $VmInfo.NumCpu
$VMCustom | Add-Member -Type NoteProperty -Name PowerState -Value $VmInfo.PowerState
$VMCustom | Add-Member -Type NoteProperty -Name MemoryGB -Value $VmInfo.MemoryGB
$VMCustom | Add-Member -Type NoteProperty -Name VMHost -Value $VMNetwork.VMhost
$VMCustom | Add-Member -Type NoteProperty -Name DHCP -Value $VMNetwork.DHCPEnabled
$VMCustom | Add-Member -Type NoteProperty -Name SubnetMask -Value $VMNetwork.SubnetMask
$VMCustom | Add-Member -Type NoteProperty -Name Client -Value $VMNetwork.Client
$VMCustom | Add-Member -Type NoteProperty -Name IP -Value $SourceIP
$VMCustom | Add-Member -Type NoteProperty -Name MacAddress -Value $VMNetwork.Mac
$VMCustom | Add-Member -Type NoteProperty -Name PortalGroupName -Value $PortalGroup.Name
$VMCustom | Add-Member -Type NoteProperty -Name OperatingSystem -Value $MvmcSourceVirtualMachine.OperatingSystem
$Data += $VMCustom
}
$Data | Export-CSV "C:\ESXiInfo.csv" -Delimiter ";" -NoTypeInformation

No way to export tables in PowerShell?

OK, everything about PowerShell has been fantastic so far, but for something that is so great they sure made exporting results to files complicated as hell. Anyway, how can I get the Export $Results variable to a deliminated file so it can be imported to Excel?
Final script
[cmdletbinding()]
[cmdletbinding()]
param(
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName = "HellBombs-PC"
)
begin {
$UninstallRegKey="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
}
process {
foreach($Computer in $ComputerName) {
Write-Verbose "Working on $Computer"
if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
$HKLM = [microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$computer)
$UninstallRef = $HKLM.OpenSubKey($UninstallRegKey)
$Applications = $UninstallRef.GetSubKeyNames()
foreach ($App in $Applications) {
$AppRegistryKey = $UninstallRegKey + "\\" + $App
$AppDetails = $HKLM.OpenSubKey($AppRegistryKey)
$AppGUID = $App
$AppDisplayName = $($AppDetails.GetValue("DisplayName"))
$AppVersion = $($AppDetails.GetValue("DisplayVersion"))
$AppPublisher = $($AppDetails.GetValue("Publisher"))
$AppInstalledDate = $($AppDetails.GetValue("InstallDate"))
$AppUninstall = $($AppDetails.GetValue("UninstallString"))
if(!$AppDisplayName) {
continue
}
$OutputObj = New-Object -TypeName PSobject
$OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
$OutputObj | Add-Member -MemberType NoteProperty -Name AppName -Value $AppDisplayName
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVersion -Value $AppVersion
$OutputObj | Add-Member -MemberType NoteProperty -Name AppVendor -Value $AppPublisher
$OutputObj | Add-Member -MemberType NoteProperty -Name InstalledDate -Value $AppInstalledDate
$OutputObj | Add-Member -MemberType NoteProperty -Name UninstallKey -Value $AppUninstall
$OutputObj | Add-Member -MemberType NoteProperty -Name AppGUID -Value $AppGUID
$Result += #($OutputObj)
}
}
}
$Result | select -Property * | export-csv -notypeinformation -path Info.txt
}
end {}
Use export-csv.
Try:
$Result | select -Property * | export-csv -notypeinformation -append -path .\test.txt

powershell exchange 2003 : query ActiveDirectory for activesync, office, and description?

I'm using powershell to pull a list of exchange 2003 users and based on the user's mailbox "LegacyDN", I was hoping to use an LDAP query to pull their activesyncenabled property (msExchOmaAdminWirelessEnable), description, and office; however, it doesn't seem to be coming up for me. any ideas?
here is how i'm querying for the AD attributes:
$allusers = get-wmiobject -class exchange_mailbox -namespace root\microsoftexchangev2 -computername srv02 | select mailboxdisplayname, legacyDN
foreach ($user in $allusers)
{
$obj = new-object psobject
$exchangever = "2003"
$tmp = [adsi]("LDAP://" + $user.legacydn)
$obj | add-member -membertype noteproperty -name "Display Name" -value $user.mailboxdisplayname
$obj | add-member -membertype noteproperty -name "Office" -value $tmp.physicaldeliveryofficename
$obj | add-member -membertype noteproperty -name "Description" -value $tmp.description
$obj | add-member -membertype noteproperty -name "Activesync" -value $tmp.msExchOmaAdminWirelessEnable
$allusersemail += $obj
}
$alluseremail | export-csv \\srv02\logs\test.csv
Here's one way:
$search = System.DirectoryServices.DirectorySearcher
$search.filter = "(&(homeMDB=*)(objectcategory=user)(objectclass=user))"
$props = "mailNickName","displayName","physicaldeliveryofficename","description","msExchOmaAdminWirelessEnable"
$props | foreach { [void]$search.PropertiesToLoad.Add($_) }
$users = $search.findAll()
foreach($u in $users)
{
$DisplayName = #{name="DisplayName";expression={$u.properties.item("DisplayName")}}
$Office = #{name="Office";expression={$u.properties.item("physicaldeliveryofficename")}}
$Description = #{name="Description";expression={$u.properties.item("Description")}}
$Activesync = #{name="Activesync";expression={$u.properties.item("msExchOmaAdminWirelessEnable")}}
$u | select $DisplayName,$Office,$Description,$Activesync
}