How to import a ConvertFrom-String TemplateContent from file with PowerShell? - string

Creating the file from the console:
PS /home/nicholas/powershell>
PS /home/nicholas/powershell> #'
>> UserPrincipalName : {UserPrincipalName*:LeeG#lazydev.com}
>> DisplayName : {DisplayName:Lee Gu}
>> Title : {Title:jr engineer}
>> UserType : {UserType:Member}
>> IsLicensed : {IsLicensed:True}
>>
>> UserPrincipalName : {UserPrincipalName*:MeganB#lazydev.com}
>> '# | Out-File full_template.psd1
PS /home/nicholas/powershell>
PS /home/nicholas/powershell> cat ./full_template.psd1
UserPrincipalName : {UserPrincipalName*:LeeG#lazydev.com}
DisplayName : {DisplayName:Lee Gu}
Title : {Title:jr engineer}
UserType : {UserType:Member}
IsLicensed : {IsLicensed:True}
UserPrincipalName : {UserPrincipalName*:MeganB#lazydev.com}
PS /home/nicholas/powershell>
but how is that file data imported?
This looks to be a "here string" but the usage, in particular, of the colon isn't clear from the documention I've referenced on data files for PowerShell.

I used a string as input with code below for testing
$properties = #"
UserPrincipalName : {UserPrincipalName*:LeeG#lazydev.com}
DisplayName : {DisplayName:Lee Gu}
Title : {Title:jr engineer}
UserType : {UserType:Member}
IsLicensed : {IsLicensed:True}
"#
$reader = [System.IO.StringReader]::new($properties)
$table = [System.Collections.ArrayList]::new()
$pattern = "\{(?<name>[^:]+):(?<value>[^}]+)"
while(($line = $reader.ReadLine()) -ne $null)
{
$match = $line | Select-String -Pattern $pattern
$name = $match.Matches.groups['name'].value
$value = $match.Matches.groups['value'].value
$newRow = New-Object -TypeName psobject
$newRow | Add-Member -NotePropertyName Name -NotePropertyValue $name
$newRow | Add-Member -NotePropertyName Value -NotePropertyValue $value
$table.Add($newRow) | Out-Null
}
$table
From a file
$input_filename = "c:\temp\test.txt"
$pattern = '\{(?<name>[^:]+):(?<value>[^}]+)'
$match = Select-String -Path $input_filename -Pattern $pattern
$table = [System.Collections.ArrayList]::new()
$newRow = New-Object -TypeName psobject
foreach($row in $match.Matches)
{
$name = $row.groups[1].value
$value = $row.groups[2].value
Write-Host "name = " $name "value = " $value
$newRow | Add-Member -NotePropertyName $name -NotePropertyValue $value
}
$table.Add($newRow) | Out-Null
$table | Format-Table

Related

Get-MsolServicePrincipalCredential with the right propertys

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.

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 all Azure AD Groups and their owner to a csv file

I need a way to export all Azure Ad groups with their corresponding owner to a csv file. The below code works, but the formatting of the csv file is horrendous. Everything is in one column and hard to read. How would I get all groups in one Column and the corresponding owner in a separate column in the corresponding row. Any help would be appreciated
$groups=Get-AzureADGroup -All $true
ForEach ($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
ForEach ($Owner in $Owners){
Write-output $group.DisplayName "," $Owner.ObjectId "," $Owner.ObjectType $Owner.UserType "," $Owner.UserPrincipalName >> C:\scripts\Owner.csv
}
}
Updated Script
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$groups = Get-AzureADGroup -All $true
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $id -All $true
$Properties.GroupDisplayName=$group.DisplayName
if($Owners -ne $null){
# group has owner
Foreach($Owner in $Owners){
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
else{
#group has no owner
$Properties.OwnerObjectId=$null
$Properties.OwnerObjectType=$null
$Properties.OwnerUserType=$null
$Properties.OwnerUserPrincipalName=$null
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path C:\test1234.csv -NoTypeInformation -Encoding UTF8
According to your need, you can refer to the following script:
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$groups = Get-AzureADGroup -All $true
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
ForEach ($Owner in $Owners){
$Properties.GroupDisplayName=$group.DisplayName
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path E:\test123.csv -NoTypeInformation -Encoding UTF8
Update
According to your need, I update my PowerShell script
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$groups = Get-AzureADGroup -All $true
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
$Properties.GroupDisplayName=$group.DisplayName
if($Owners -ne $null){
# group has owner
Foreach($Owner in $Owners){
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
else{
#group has no owner
$Properties.OwnerObjectId=$null
$Properties.OwnerObjectType=$null
$Properties.OwnerUserType=$null
$Properties.OwnerUserPrincipalName=$null
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path E:\test123.csv -NoTypeInformation -Encoding UTF8
In order to create a proper CSV file with headers and rows of data, you need to collect an array of Objects and send that to the Export-Csv cmdlet.
$groups = Get-AzureADGroup -All $true
$result = foreach ($group in $groups) {
Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true | ForEach-Object {
# output an object with the properties and headernames you need
# the $_ automatic variable contains 1 owner object in each iteration
[PsCustomObject]#{
'Group' = $group.DisplayName
'OwnerId' = $_.ObjectId
'OwnerType' = $_.ObjectType
'OwnerUPN' = $_.UserPrincipalName
}
}
}
# output on screen
$result | Format-Table -AutoSize
# output to CSV
$result | Export-Csv -Path 'C:\scripts\AZGroupOwners.csv' -NoTypeInformation
Hope that helps

Switching Lastname, Firstname in Powershell AD script

I try to export AD groups and users from a OU by Firstname, Lastname but I only get it to work with Lastname, Firstname.
Everything else I try gives me an empty string for members.I tried changing the line under Select-Object to:
#{Name='Member';Expression={$_.FirstName = GetFirstName $_.Name $_.LastName = GetLastName $_.Name}},
$firt = $_.firstname
$last = $_.lastname
#{Name='Member';Expression={$_.name = "$first,$last"}},
This is the working code, but the names should be switched around.
$OU = 'OU=Groups,OU=City,OU=Continent,DC=DomainControler, DC=Domain, DC=net' #Change this to get different groups
$DateTime = Get-Date -f "dd-MM-yyyy"
$MyFileName = "CompanyName-Groups_"+$DateTime+".csv"
$Path = Join-Path $PSScriptRoot $MyFileName
$Groups = get-adobject -Filter 'ObjectClass -eq "group"' -SearchBase $OU
$i=0
$tot = $Groups.count
$Data = foreach ($Group in $Groups) {
$i++
$status = "{0:N0}" -f ($i / $tot * 100)
Write-Progress -Activity "Exporting AD Groups" -status "Processing Group $i of $tot : $status% Completed" -PercentComplete ($i / $tot * 100)
Get-ADGroupMember -Identity $Group |
Select-Object #{Name='Group';Expression={$Group.Name}},
#{Name='Member';Expression={$_.Name}},
#{Name='Enabled';Expression={if ($_.ObjectClass -eq 'user') {Get-ADUser $_ | Select-Object -Expand Enabled} else {'NA/Group'}}}
}
$Data | Export-Csv -Path $Path -NoTypeInformation
This is an example output:
Group, "member", enabled
Admin, "Mario, Speedwagon", True
Admin, "Petey, Cruiser", True
Admin, "Anna, Sthesia", False
HR, "Paul, Molive", True
HR, "Phaedra, Lugt", True
IT, "Paul, Molive", False
IT, "Cliff, Hanger", True
This is what it should become:
Group, "member", enabled
Admin, "Speedwagon, Mario", True
Admin, "Cruiser, Petey", True
Admin, "Sthesia, Anna", False
HR, "Molive, Paul", True
HR, "Lugt, Phaedra", True
IT, "Molive, Paul", False
IT, "Hanger, Cliff", True
I think this might clear things up for you:
$OU = 'OU=Groups,OU=City,OU=Continent,DC=DomainControler, DC=Domain, DC=net'
$PathParams = #{
Path = $PSScriptRoot
ChildPath = "PA-AD-Groups_{0}.csv" -f (Get-Date -f "dd-MM-yyyy")
}
$FilePath = Join-Path #PathParams
$Groups = Get-ADObject -Filter 'ObjectClass -eq "group"' -SearchBase $OU
$i = 0
$tot = $Groups.count
$Data = foreach ($Group in $Groups) {
$i++
$ProgressParams = #{
Activity = 'Exporting AD Groups'
PercentComplete = ($i / $tot * 100)
status = "Processing Group $i of $tot : {0:N0} Completed" -f
($i / $tot * 100)
}
Write-Progress #ProgressParams
Get-ADGroupMember -Identity $Group |
Select-Object #{Name = 'Group'; Expression = {$Group.Name}},
#{Name = 'Member'; Expression = {$_.Name}},
#{Name = 'Enabled'; Expression = {
$Script:User = $false
if ($_.ObjectClass -eq 'user') {
$Script:User = Get-ADUser $_
if ($User.Enabled) {$true} else {$false}
}
else {
'NA/Group'
}
}
},
#{Name = 'FirstName'; Expression = {
if ($User) {
$User.GivenName
}
}
},
#{Name = 'LastName'; Expression = {
if ($User) {
$User.Surname
}
}
},
#{Name = 'CombinedName'; Expression = {
if ($User) {
"{0}, {1}" -f $User.GivenName, $User.Surname
}
}
}
}
$Data | Export-Csv -Path $FilePath -NoTypeInformation
The issue you have is that you can't use the properties from $User outside of the Expression within the Select-Object. This is simply fixed by creating a variable that is available throughout the script and as such is called Script scope, used as $Script:User.
More info can be found in Get-Help about_Scopes or here.
On a side note I would advice you to use proper indentation, it makes things more readable. The splatted parameter hashtable helps in this regard too. As a last tip: don't create a variable if you only use it once. Otherwise it just confuses you later on.

Excel report Formatting in PowerShell

Need help to create a script to get a HPOA server blade Health report
The problem is that when I get query Health it outputs in a PSO object with fields (IP,Health,Blades(#{Blade1 Health}{Blade2 Health}{3} . . .) )
I want a report like below
IP Bay Power Health
-- --- ----- -----
10.3.131.2 1 On OK
2 On OK
3 On OK
4 On OK
5 On Degraded
The variables are derived as below .
$sstaInfo = {} | Select IP, Bay, Power, Health, DeviceFailure
$sstaInfo.IP=$ssta.IP (Gives a single IP output)
$sstaInfo.Bay=$sstaBlades.Bay $sstaInfo.Power=$sstaBlades.Power
$sstaInfo.Health=$sstaBlades.Health
How can I get this working ?
$ssta variable has the below output :
#{Power=On; CurrentWattageUsed=480; Health=OK; UnitIdentificationLED=Off; VirtualFan=33%; DiagnosticStatus=; Bay=1} #{Power=On; CurrentWattageUsed=576; Health=OK; UnitIdentificationLED=Off; VirtualFan=47%; DiagnosticStatus=; Bay=2}
#------------------------------------------------------------ Input Variable Definations
$HPOAServers =#(
[pscustomobject]#{Name='10.11.12.13'},
[pscustomobject]#{Name='10.11.12.14'}
)
$Username ="admin"
$Password ="admin"
#------------------------------------------------------------ Main Script Starts Here
# Function for connecting to OA and returning connection object on success
foreach ($HPOAServer in $HPOAServers) {
$con = Connect-HPOA $HPOAServer.Name -username $Username -password $Password
$report = #()
$ssta = Get-HPOAServerStatus -Bay All $con
$sstaBlade=$ssta.Blade
Write-Host $sstaBlade
Foreach ($sstaBlades in $sstaBlade) {
$i++
$sstaInfo = {} | Select IP, Bay, Power, Health, DeviceFailure
$sstaInfo.IP=$ssta.IP
$sstaInfo.Bay=$sstaBlades.Bay
$sstaInfo.Power=$sstaBlades.Power
$sstaInfo.Health=$sstaBlades.Health
$sstaInfo.DeviceFailure=$ssta.Blade.DiagnosticStatus.DeviceFailure
}
$report += $ssta | Select-Object -Property IP
$report += $ssta.Blade | Select-Object -Property Bay, Power, Health | Format-Table *
$report | out-file "HPOA_Health_Report.txt" -Append
}
Disconnect-HPOA $con
I suggest you use Export-CSV instead, so below line
$report | Out-File "HPOA_Health_Report.txt" -Append
will be replaced by:
$report | Export-Csv "HPOA_Health_Report.csv" -Append -NoTypeInformation
Function HPOA () {
try
{
Remove-Item -Path $outputfile -Force
foreach ($HPOAServer in $HPOAServers)
{
$con = Connect-HPOA $HPOAServer.Name -username $Username -password $Password -ErrorAction 'Stop'
$ssta = Get-HPOAServerStatus -Bay All $con
$ssta.Blade | Foreach-Object {
$sstaInfo = $_
$sstaInfo | Select-Object -Property #{Name="Chassis_IP_Address";Expression={$ssta.IP}},
#{Name="Blade_Power_Status";Expression={$_.Power}},
#{Name="Blade_Bay_Number";Expression={$_.Bay}},
#{Name="Blade_Health_Status";Expression={$_.Health}},
#{Name="Blade_Diagnostic_DeviceFailure_Status";Expression={$ssta.Blade.DiagnosticStatus.DeviceFailure}}
} | ConvertTo-Html -Title " $HPOARegionName HPOA Health Report " -Head $Header -Body "<H2> $HPOARegionName HPOA Health Report </H2>" -As Table | Out-File -Append $outputfile
Disconnect-HPOA $con
}
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Write-Host $ErrorMessage
Write-Host $FailedItem
}
}
HPOA

Resources