如何加快 PowerShell 脚本的处理速度?
目前运行1K+使用记录大约需要1-2小时,确实需要加快速度。
# Must be run in Powershell 5.1 or else you can't get account creation date
# Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
$maximumfunctioncount = 8192
Install-Module Microsoft.Graph -Scope CurrentUser -Force -AllowClobber
Connect-MgGraph -Scopes "Directory.Read.All","User.Read.All","AuditLog.Read.All"
Select-MgProfile -Name "Beta"
# Add a line from the variable name onwards to uncomment the license SKU
$LicenseSku = 'ENTERPRISEPACK'
# Use this to check for the license SKU
# Get-MgSubscribedSku -All -Select SkuPartNumber, SkuId, SkuPartNumber, ConsumedUnits | Format-List
# Get the assigned users details & exports as a CSV file
$licenseDetails = Get-MgSubscribedSku -All | Where SkuPartNumber -eq $LicenseSku
Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($licenseDetails.SkuId) )" -ConsistencyLevel eventual -All | Export-Csv -Path "C:\temp\LiceneUsers.csv"
# Imports the above CSV file
$UserCSVExtract = Import-Csv -Path "C:\temp\LiceneUsers.csv"
# This is the final CSV file that is created with the user UPN + last sign-in date + account creation date
$FinalCSVName = 'c:\temp\License CSV '+$LicenseSku + '.csv'
$Result=@()
foreach($user in $UserCSVExtract)
{
$usersignindate = Get-MgUser -UserId $user.ID -Select SignInActivity | Select -ExpandProperty SignInActivity
$userprops = [ordered]@{
UserPrincipalName = $user.UserPrincipalName
LastSignInDateTime = $usersignindate.LastSignInDateTime
AccountCreationDate = $user.CreatedDateTime
}
$userObj = new-object -Type PSObject -Property $userprops
$Result += $userObj | Export-csv -Path $FinalCSVName -Append
}
$Result
编辑2:
#Connect to Microsoft Graph
Connect-MgGraph -scope User.Read.All, AuditLog.read.All
#Select the beta profile
Select-MgProfile -name beta
#Gather all users in tenant
$AllUsers = Get-MgUser -All
#Create a new empty array list object
$Report = [System.Collections.Generic.List[Object]]::new()
Foreach ($user in $AllUsers)
{
#Null variables
$SignInActivity = $null
$Licenses = $null
#Display progress output
Write-host "Gathering sign-in information for $($user.DisplayName)" -ForegroundColor Cyan
#Get current user information
$SignInActivitiy = Get-MgUser -UserId $user.id -Property signinactivity | Select-Object -ExpandProperty signinactivity
$licenses = (Get-MgUserLicenseDetail -UserId $User.id).SkuPartNumber -join ", "
#Create informational object to add to report
$obj = [pscustomobject][ordered]@{
DisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
Licenses = $licenses
LastInteractiveSignIn = $SignInActivitiy.LastSignInDateTime
LastNonInteractiveSignin = $SignInActivitiy.LastNonInteractiveSignInDateTime
}
#Add current user info to report
$report.Add($obj)
}
$report | Export-CSV -path C:\temp\Microsoft365_User_Activity-Report.csv -NoTypeInformation
您实际上并不需要使用 Beta 端点,因为 signInActivity 位于 v1.0 端点中,并且除非您有其他需要,否则不需要将第一个 Get-MgUser 的结果导出到 CSV。脚本中最慢的部分是 CSV 中每个用户的单独 Get-MgUser,它将为每个用户创建一个不需要的请求,因为您可以从第一个请求中获取所有信息。 (即使您打算执行此操作,您也会想要批处理 Get-MgUser)。
例如,您尝试做的事情的精简版本可以使用 oneliner 来完成
Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($licenseDetails.SkuId) )" -ConsistencyLevel eventual -All -Property UserPrincipalName,CreatedDateTime,signInActivity | select UserPrincipalName,CreatedDateTime,@{name="LastSignInDateTime";expression={$_.signInActivity.lastSignInDateTime}} | export-csv -NoTypeInformation "c:\temp\urep.csv"
[编辑]
#Connect to Microsoft Graph
Connect-MgGraph -scope User.Read.All, AuditLog.read.All
$skuList = @{}
Get-MgSubscribedSku -All -Select SkuPartNumber, SkuId, SkuPartNumber | ForEach-Object {$skuList.add($_.SkuId,$_.SkuPartNumber)}
#Gather all users in tenant
$AllUsers = Get-MgUser -All -Property DisplayName,UserPrincipalName,SigninActivity,AssignedLicenses
#Create a new empty array list object
$Report = [System.Collections.Generic.List[Object]]::new()
Foreach ($user in $AllUsers)
{
#Null variables
$Licenses = @()
#Display progress output
Write-host "Gathering sign-in information for $($user.DisplayName)" -ForegroundColor Cyan
foreach($license in $user.AssignedLicenses){
if($skuList.ContainsKey($license.SkuId)){
$Licenses += $skuList[$license.SkuId]
}else{
$Licenses += $license.SkuId
}
}
#Create informational object to add to report
$obj = [pscustomobject][ordered]@{
DisplayName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
Licenses = ($Licenses -join ',')
LastInteractiveSignIn = $user.SigninActivity.LastSignInDateTime
LastNonInteractiveSignin = $user.SigninActivity.LastNonInteractiveSignInDateTime
}
#Add current user info to report
$report.Add($obj)
}
$report | Export-CSV -path C:\temp\Microsoft365_User_Activity-Report.csv -NoTypeInformation
该代码现在可能无法运行,因为微软为测试版引入了单独的模块。 您需要使用单独安装模块 安装模块-名称 Microsoft.Graph.Beta