Forum Discussion
Ameerm2023
Apr 27, 2023Copper Contributor
Not getting the values in CSV
I have the PowerShell scripts which is giving output saved as CSV file if i run the scripts manually but If create the windows scheduler to run it automatically i am not getting any result saved in t...
AndySvints
May 01, 2023Iron Contributor
Hello Ameerm2023,
Just my two cents on how to make your script more efficient. You are calling Get-MgUser 4 times, although 2 would be more than enough (Actually it can be achieved with just one but we have to start somewhere). Basically you can cut the execution time in half:
Write-Host "Script started at $(Get-Date)"
$Disabled = ".\UserUsage\DisabledUsers.csv"
$enabled = ".\UserUsage\EnabledUsers.csv"
Connect-MgGraph -ClientId "123" -TenantId "123" -CertificateThumbprint "123"
Sleep -Seconds 10
$allEnabledUsers = Get-MgUser -All -Filter 'accountEnabled eq true' -Property id, FirstName, LastName, Jobtitle, displayName, CompanyName, State, OfficeLocation, department, signInActivity, userPrincipalName,userType, createdDateTime, accountEnabled, passwordPolicies, mail, lastPasswordChangeDateTime, Phone | select id, displayName, FirstName, LastName, Jobtitle, CompanyName, State, OfficeLocation, Phone, department, userPrincipalName, userType, createdDateTime, accountEnabled, mail, lastPasswordChangeDateTime, passwordPolicies, @{N='LastSignInDateTime';E={$_.signInActivity.LastSignInDateTime}}, @{N='LastNonInteractiveSignInDateTime';E={$_.signInActivity.LastNonInteractiveSignInDateTime}}
Write-Host "Enabled Users: $($allEnabledUsers.Count)"
Sleep -Seconds 10
$allDisabledUsers = Get-MgUser -Filter 'accountEnabled eq false' -All -Property id, FirstName, LastName, Jobtitle, displayName, CompanyName, State, OfficeLocation, department, signInActivity, userPrincipalName, userType, createdDateTime, accountEnabled, passwordPolicies, mail, lastPasswordChangeDateTime, Phone | select id, displayName, FirstName, LastName, Jobtitle, CompanyName, State, OfficeLocation, Phone, department, userPrincipalName, userType, createdDateTime, accountEnabled, mail, lastPasswordChangeDateTime, passwordPolicies, @{N='LastSignInDateTime';E={$_.signInActivity.LastSignInDateTime}}, @{N='LastNonInteractiveSignInDateTime';E={$_.signInActivity.LastNonInteractiveSignInDateTime}}
Write-Host "Disabled Users: $($allDisabledUsers.Count)"
$allEnabledUsers | Export-CSV -NoTypeInformation $enabled
Write-Host "CSV file for Enabled Users exported at $(Get-Date)"
$allDisabledUsers | Export-Csv -NoTypeInformation $Disabled
Write-Host "CSV file for Disabled Users exported at $(Get-Date)"
Disconnect-MgGraph
Write-Host "Script finished at $(Get-Date)"Hope that helps.
- Ameerm2023May 01, 2023Copper ContributorThanks for update and i have changed the scripts but still i am getting any value of i run the task scheduler but if i run it manually its getting saved.please help