Get-MsolServicePrincipalCredential with the right propertys - azure

With the code below I can get a list of client secrets listed, but trying to use propertys as in the example here as you could do for example if you want to list certificates on your server won't work. I tried to google on but can't find any examples.
With -property no matter which one you pick in this example the return would be nothing.
Connect-MsolService
$applist = Get-MsolServicePrincipal -all | Where-Object -FilterScript { ($_.DisplayName -notlike "*Microsoft*") -and ($_.DisplayName -notlike "autohost*") -and ($_.ServicePrincipalNames -notlike "*localhost*") }
foreach ($appentry in $applist) {
$principalId = $appentry.AppPrincipalId
$principalName = $appentry.DisplayName
Get-MsolServicePrincipalCredential -AppPrincipalId $principalId -ReturnKeyValues $false | ? { $_.Type -eq "Password" } | Select-Object -Property DisplayName
If we skip the property, it would look like:
Type :
Password Value :
KeyId : 642ee910-9b17-4d17-93d4-0192f3c1f855
StartDate : 2018-05-25 08:22:37
EndDate : 2019-05-25 08:22:37
Usage : Verify
I want in the same list format just with more propertys so I can recyle another script to upload the data to a sharepoint list.

I solved it this way:
$clientsecrets = #()
$applist = Get-MsolServicePrincipal -all | Where-Object -FilterScript { ($_.DisplayName -like "*SI*") -or ($_.DisplayName -like "*FD*") -or ($_.DisplayName -like "*AP*") -and ($_.DisplayName -notlike "*Microsoft*") -and ($_.DisplayName -notlike "autohost*") -and ($_.ServicePrincipalNames -notlike "*localhost*") }
foreach ($appentry in $applist) {
$principalId = $appentry.AppPrincipalId
$principalName = $appentry.DisplayName
$clientsecret = Get-MsolServicePrincipalCredential -AppPrincipalId $principalId -ReturnKeyValues $false | ? { $_.Type -eq "Password" } | % { $principalName, $principalId;, ($enddate = $_.EndDate.ToString()) } | select {$principalName}, {$principalId}, {$enddate}
$clientsecret | Add-Member -MemberType NoteProperty -Name 'principalId' -Value $principalId
$clientsecret | Add-Member -MemberType NoteProperty -Name 'principalName' -Value $principalName
$clientsecrets+=$clientsecret
}
Using an array and using add-member did put it in a format where I could use and read and add it to the sharepoint list.

Related

Export Azure Subscriptions and owners (need PowerShell script)

I need help to create a script.
The task is to in Azure to export Subscriptions and owners of these subscriptions to CSV file. I assume I will be using powershell for this task
Please help!
You can use the below PowerShell script to pull the list of users which has the owner access to the subscription.
Connect-AzAccount
$sublist= Get-AzSubscription
foreach ($item in $sublist){
$scopeappend= "/subscriptions/"+$item.Id
$export=(Get-AzRoleAssignment -RoleDefinitionId "8e3af657-a8ff-443c-a75c-2fe8c4bcb635" -Scope $tdt | where {($_.ObjectType -EQ "user") -and ($_.Scope -EQ $scopeappend) } ) | select DisplayName,SignInName
}
$export|Export-Csv -Path C:\test.csv
I have tested the above PowerShell script and it is working fine for me.
You can refer to this documentation for For-each loop syntax as well.
I figure out the solution. Please see below.
$subs = Get-AzSubscription
$filename = "Subs_CoAdmins"+(Get-Date -UFormat "%Y-%m-%d_%H-%m-%S")+".xlsx"
$allRBACs = #()
foreach ($sub in $subs) {
if (Select-AzSubscription -SubscriptionName $sub.Name) {
if ($rbacs = Get-AzRoleAssignment -IncludeClassicAdministrators) {
foreach ($rbac in $rbacs) {
if (($rbac.Scope -like "/subscriptions/*") -and ($rbac.ObjectType -eq "Microsoft.Authorization/classicAdministrators") -and ($sub.SubscriptionPolicies.QuotaId -like "*MSDN*")) {
$rbacObj = New-Object -TypeName psobject
$rbacObj | Add-Member -MemberType NoteProperty -Name Subscription -Value $sub.Name
$rbacObj | Add-Member -MemberType NoteProperty -Name SubscriptionId -Value $sub.Id
$rbacObj | Add-Member -MemberType NoteProperty -Name Scope -Value $rbac.Scope
$rbacObj | Add-Member -MemberType NoteProperty -Name RoleDefinitionName -Value $rbac.RoleDefinitionName
$rbacObj | Add-Member -MemberType NoteProperty -Name RoleDefinitionId -Value $rbac.RoleDefinitionId
$rbacObj | Add-Member -MemberType NoteProperty -Name DisplayName -Value $rbac.DisplayName
$rbacObj | Add-Member -MemberType NoteProperty -Name SignInName -Value $rbac.SignInName
$rbacObj | Add-Member -MemberType NoteProperty -Name ObjectType -Value $rbac.ObjectType
$rbacObj | Add-Member -MemberType NoteProperty -Name SubQuotaId -Value $sub.SubscriptionPolicies.QuotaId
$allRBACs += $rbacObj
}
}
}
}
}
$allRBACs | Export-Excel ./$filename -AutoSize -AutoFilter

Powershell - Get-AzureADAuditSignInLogs multiple filters

I'm trying to Get last signin date for Global Admins
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Global Administrator'}
$admins = #(Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | select DisplayName, UserPrincipalName)
Foreach ($admin in $admins){
$upn = $admin.UserPrincipalName
$signons = Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq '$upn' " -Top 1 | select UserDisplayName, #{Name = 'LastSignIn'; Expression = {$_.CreatedDateTime}}
}
And above code works as expected for users who have entry in AuditSignInLogs, but i want to return users who never logged in too, so modified above filter
(all users in for loop)
$signons = Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq '$upn' or CreatedDateTime eq '$null'" -Top 1 | select UserDisplayName, #{Name = 'LastSignIn'; Expression = {$_.CreatedDateTime}}
But getting error "Message: Invalid filter clause"
also tried or CreatedDateTime eq '' but same error
Please check below powershell commands.
I have initially checked the same for users .
Then checked the same for admin role i.e;admins and could get the lastlogon for all the admins including who has no recored yet in signins.
$AllSiginLogs = Get-AzureADAuditSignInLogs -All $true
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Global Administrator'}
$admins = #(Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | select DisplayName, UserPrincipalName)
$results = #()
Foreach ($admin in $admins){
$LoginRecord = $AllSiginLogs | Where-Object{ $_.UserId -eq $admin.ObjectId } | Sort-Object CreatedDateTime -Descending
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord[0].CreatedDateTime
}else{
$lastLogin = 'no login record'
}
$item = #{
userUPN=$admin.UserPrincipalName
userDisplayName = $admin.DisplayName
lastLogin = $lastLogin
accountEnabled = $admin.AccountEnabled
}
$results += New-Object PSObject -Property $item
Write-Output $results
}
#$results | export-csv -Path d:\result.csv -NoTypeInformation
Result:
Reference:
userlastlogon-export
thanks #kavyasaraboju-MT
Your hint helped me a lot, based on it, i modified my code which gets what i want
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Global Administrator'}
$admins = #(Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | select DisplayName, UserPrincipalName)
$results = #()
Foreach ($admin in $admins){
$upn = $admin.UserPrincipalName
$LoginRecord = Get-AzureADAuditSignInLogs -Filter "UserPrincipalName eq '$upn'" -Top 1
Start-Sleep -Seconds 2
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord.CreatedDateTime
}
else{
$lastLogin = 'no login record'
}
$item = #{
userUPN=$admin.UserPrincipalName
userDisplayName = $admin.DisplayName
lastLogin = $lastLogin
}
$results += New-Object PSObject -Property $item
}
$results | export-csv -Path c:\result.csv -NoTypeInformation -Encoding UTF8

Export Multiple Azure AD group members

I am using below code snippet, Instead of -ALL I am trying to pass specific ObjectId or filter group name but getting below error. pls help to fix this.
$groups=Get-AzureADGroup -ObjectId "Group1" - Works fine with one but not with multiple ObjectId
$groups=Get-AzureADGroup -filter{Name -like "ABC*"} - Get-AzureADGroup : Cannot evaluate parameter 'Filter'
Connect-AzureAD
$groups=Get-AzureADGroup -All $true
$resultsarray =#()
ForEach ($group in $groups){
$members = Get-AzureADGroupMember -ObjectId $group.ObjectId -All $true
ForEach ($member in $members){
$UserObject = new-object PSObject
$UserObject | add-member -membertype NoteProperty -name "Group Name" -Value $group.DisplayName
$UserObject | add-member -membertype NoteProperty -name "Member Name" -Value $member.DisplayName
$UserObject | add-member -membertype NoteProperty -name "ObjType" -Value $member.ObjectType
$UserObject | add-member -membertype NoteProperty -name "UserType" -Value $member.UserType
$UserObject | add-member -membertype NoteProperty -name "UserPrinicpalName" -Value $member.UserPrincipalName
$resultsarray += $UserObject
}
}
$resultsarray | Export-Csv -Encoding UTF8 -Delimiter ";" -Path "C:\scripts\output.csv" -NoTypeInformation
$groups=Get-AzureADGroup -All
$result=new-object system.colletions.arraylist
foreach($group in $groups)
{
$members=$group.members
foreach($member in $members)
{
$result.add(
[PSCustomObject]#{
"Group Name"=$group.DisplayName
"Member Name"=$member.DisplayName
"ObjType"=$member.ObjectType
"UserType"=$member.UserType
"UserPrinicpalName"=$member.UserPrincipalName
}) > $null
}
}
If you wanna search for a specific group you can use -SearchString 'groupName' or a list of groups:
$groups='group1,group2,group3'.split(',')|%{
Get-AzureADGroup -SearchString $_
}

Azure VM OS Build - Powershell

I am trying to create a powershell command to loop through all my Azure subscriptions and get the OS build number of the VMs
param(
# Specify the location of the audit file
$csvFilePath = "C:\agentAudit.csv"
)
cls
$ErrorActionPreference = 'Stop'
Write-Host "Validating Azure Accounts..."
try{
$subscriptionList = Get-AzureRmSubscription | Sort SubscriptionName
}
catch {
Write-Host "Reauthenticating..."
Login-AzureRmAccount | Out-Null
$subscriptionList = Get-AzureRmSubscription | Sort SubscriptionName
}
if (Test-Path $csvFilePath) {
Remove-Item -Path $csvFilePath
}
foreach($subscription in $subscriptionList) {
Select-AzureRmSubscription -SubscriptionId $subscription.SubscriptionId | Out-Null
Write-Output "`n Working on subscription: $($subscription.SubscriptionName) `n"
$vms = Get-AzureRmVM -WarningAction Ignore
foreach ($vm in $vms) {
$VMs = Get-AzureRmVM
$vmlist = #()
$VMs | ForEach-Object {
$VMObj = New-Object -TypeName PSObject
$VMObj | Add-Member -MemberType Noteproperty -Name "VM Name" -Value $_.Name
$VMObj | Add-Member -MemberType Noteproperty -Name "OS type" -Value $_.StorageProfile.ImageReference.Sku
$VMObj | Add-Member -MemberType Noteproperty -Name "OS Offer" -Value $_.StorageProfile.ImageReference.Offer
$VMObj | Add-Member -MemberType Noteproperty -Name "OS Publisher" -Value $_.StorageProfile.ImageReference.Publisher
$VMObj | Add-Member -MemberType Noteproperty -Name "OS Version" -Value $_.StorageProfile.ImageReference.Version
$vmlist += $VMObj
}
$vmlist
}
}
I am pretty new to to Powershell and still learning to understand and write PS
Long time back i created a script for generating the Azure inventory. May be this can help you. You just need to tweak it a bit
Add-AzureRmAccount
$SubscriptionNames = "Prototypes","Development"
foreach($SubscriptionName in $SubscriptionNames)
{
try
{
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
$VMinventory = Get-AzurermVM -ErrorAction Stop
$OutputPath = "C:\VMInventoryRM-" + $SubscriptionName + ".csv"
$report=#()
foreach ($vm in $VMinventory)
{
$VMinfo = " " | select Powerstate, Location, VMSize
# Display
write-host($vm.Name)
$vmStatus = $null
$Location = $null
$VMSize = $null
$vmStatus = (get-azurermvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Status).Statuses[1].Code
$Location = $vm.Location
$VMSize = $vm.HardwareProfile.VmSize
$VMinfo.Powerstate = $vmStatus
$VMinfo.Location = $Location
$VMinfo.VMSize = $VMSize
$Report += $VMinfo
$i++
}
$Report | export-csv $OutputPath -NoTypeInformation
}
catch
{}
}
I found the answer in the below technet article
function Get-WindowsVersion {
<#
.SYNOPSIS
List Windows Version from computer. Compatible with PSVersion 3 or higher.
.DESCRIPTION
List Windows Version from computer. Compatible with PSVersion 3 or higher.
.PARAMETER ComputerName
Name of server to list Windows Version from remote computer.
.PARAMETER SearchBase
AD-SearchBase of server to list Windows Version from remote computer.
.PARAMETER History
List History Windows Version from computer.
.PARAMETER Force
Disable the built-in Format-Table and Sort-Object.
.NOTES
Name: Get-WindowsVersion.psm1
Author: Johannes Sebald
Version: 1.2.5
DateCreated: 2016-09-13
DateEdit: 2018-07-11
.LINK
https://www.dertechblog.de
.EXAMPLE
Get-WindowsVersion
List Windows Version on local computer with built-in Format-Table and Sort-Object.
.EXAMPLE
Get-WindowsVersion -ComputerName pc1
List Windows Version on remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
Get-WindowsVersion -ComputerName pc1,pc2
List Windows Version on multiple remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
Get-WindowsVersion -SearchBase "OU=Computers,DC=comodo,DC=com" with built-in Format-Table and Sort-Object.
List Windows Version on Active Directory SearchBase computer.
.EXAMPLE
Get-WindowsVersion -ComputerName pc1,pc2 -Force
List Windows Version on multiple remote computer and disable the built-in Format-Table and Sort-Object.
.EXAMPLE
Get-WindowsVersion -History with built-in Format-Table and Sort-Object.
List History Windows Version on local computer.
.EXAMPLE
Get-WindowsVersion -ComputerName pc1,pc2 -History
List History Windows Version on multiple remote computer with built-in Format-Table and Sort-Object.
.EXAMPLE
Get-WindowsVersion -ComputerName pc1,pc2 -History -Force
List History Windows Version on multiple remote computer and disable built-in Format-Table and Sort-Object.
#>
[cmdletbinding()]
param (
[parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]$ComputerName = "localhost",
[string]$SearchBase,
[switch]$History,
[switch]$Force
)
if ($($PsVersionTable.PSVersion.Major) -gt "2") {
# SearchBase
if ($SearchBase) {
if (Get-Command Get-AD* -ErrorAction SilentlyContinue) {
if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$SearchBase'" -ErrorAction SilentlyContinue) {
$Table = Get-ADComputer -SearchBase $SearchBase -Filter *
$ComputerName = $Table.Name
}
else {Write-Warning "No SearchBase found"}
}
else {Write-Warning "No AD Cmdlet found"}
}
# Loop 1
$Tmp = New-TemporaryFile
foreach ($Computer in $ComputerName) {
if (Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue) {
try {
$WmiObj = Get-WmiObject Win32_OperatingSystem -ComputerName $Computer
}
catch {
Write-Warning "$Computer no wmi access"
}
if ($WmiObj) {
# Variables
$WmiClass = [WmiClass]"\\$Computer\root\default:stdRegProv"
$HKLM = 2147483650
$Reg1 = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
$Reg2 = "SYSTEM\Setup"
if ($History) {$KeyArr = ($WmiClass.EnumKey($HKLM, $Reg2)).snames -like "Source*"} else {$KeyArr = $Reg1}
# Loop 2
foreach ($Key in $KeyArr) {
if ($History) {$Reg = "$Reg2\$Key"} else {$Reg = $Key}
$Major = $WmiClass.GetDWordValue($HKLM, $Reg, "CurrentMajorVersionNumber").UValue
$Minor = $WmiClass.GetDWordValue($HKLM, $Reg, "CurrentMinorVersionNumber").UValue
$Build = $WmiClass.GetStringValue($HKLM, $Reg, "CurrentBuildNumber").sValue
$UBR = $WmiClass.GetDWordValue($HKLM, $Reg, "UBR").UValue
$ReleaseId = $WmiClass.GetStringValue($HKLM, $Reg, "ReleaseId").sValue
$ProductName = $WmiClass.GetStringValue($HKLM, $Reg, "ProductName").sValue
$ProductId = $WmiClass.GetStringValue($HKLM, $Reg, "ProductId").sValue
$InstallTime1 = $WmiClass.GetQWordValue($HKLM, $Reg, "InstallTime").UValue
$InstallTime2 = ([datetime]::FromFileTime($InstallTime1))
# Variables Windows 6.x
if ($Major.Length -le 0) {$Major = $WmiClass.GetStringValue($HKLM, $Reg, "CurrentVersion").sValue}
if ($ReleaseId.Length -le 0) {$ReleaseId = $WmiClass.GetStringValue($HKLM, $Reg, "CSDVersion").sValue}
if ($InstallTime1.Length -le 0) {$InstallTime2 = ([WMI]"").ConvertToDateTime($WmiObj.InstallDate)}
# Add Points
if (-not($Major.Length -le 0)) {$Major = "$Major."}
if (-not($Minor.Length -le 0)) {$Minor = "$Minor."}
if (-not($UBR.Length -le 0)) {$UBR = ".$UBR"}
# Output
$Output = New-Object -TypeName PSobject
$Output | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.toUpper()
$Output | Add-Member -MemberType NoteProperty -Name ProductName -Value $ProductName
$Output | Add-Member -MemberType NoteProperty -Name WindowsVersion -Value $ReleaseId
$Output | Add-Member -MemberType NoteProperty -Name WindowsBuild -Value "$Major$Minor$Build$UBR"
$Output | Add-Member -MemberType NoteProperty -Name ProductId -Value $ProductId
$Output | Add-Member -MemberType NoteProperty -Name InstallTime -Value $InstallTime2
$Output | Export-Csv -Path $Tmp -Append
}
}
}
else {Write-Warning "$Computer not reachable"}
}
# Output
if ($Force) {Import-Csv -Path $Tmp} else {Import-Csv -Path $Tmp | Sort-Object -Property ComputerName, WindowsVersion | Format-Table -AutoSize}
}
else {Write-Warning "PSVersion to low"}
}
https://gallery.technet.microsoft.com/scriptcenter/Get-WindowsVersion-can-0726c5d4#
Thank You Johannes Sebald

Active Directory Export via PowerShell (Displayname & EmployeeID) Using Get-ADUser

I want to export list all AD User Accounts with just employeeid attribute form my domain where I want to exclude a particular OU -- want to exclude all of them.
Here is the script I ran, but did not work no luck
BTW must be non-null Employee IDattribute
$OUDN = "OU=Service Accounts,OU=Accounts,DC=domain,DC=tld"
Get-ADUser -Properties mail |select name,samaccountname,mail,manager,department,employeeid -Filter {Enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike "*,$OUDN" }
Other Code:
$OUDN = "OU=Service Accounts,OU=Accounts,DC=domain,DC=tld"
Get-ADUser -properties CN,Title,samaccountname,mail,displayname,manager,department,distinguishedname,employeeid | select-object CN,Title,employeeid,mail,#{n=”PRODID”;e=”samaccountname”},DisplayName,#{n=”Manager Name”;e={(Get-ADuser -identity $_.Manager -properties displayname).DisplayName}},#{n=”ManagerID”;e={(Get-ADuser -identity $_.Manager –properties samaccountname).samaccountname}},Department -Filter {Enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike "*,$OUDN" }
Your Filter parameter is in the wrong place (Select-Object), it should be used with Get-ADUser.
Get-ADUser -properties CN,Title,samaccountname,mail,displayname,manager,department,distinguishedname,employeeid -Filter {Enabled -eq $true -and employeeID -like '*' } |
select-object CN,Title,employeeid,mail,
#{n=”PRODID”;e=”samaccountname”},DisplayName,
#{n=”Manager Name”;e={(Get-ADuser -identity $_.Manager -properties displayname).DisplayName}},
#{n=”ManagerID”;e={(Get-ADuser -identity $_.Manager –properties samaccountname).samaccountname}},
Department |
Where-Object { $_.DistinguishedName -notlike "*,$OUDN" }

Resources