0

我有一个 PowerShell 脚本,它调用 Microsoft Graph 的 POST REST API 调用。在脚本的开头,我使用Start-Transcript -Append "$($MyInvocation.MyCommand.Name).log"cmdlet,在脚本的结尾,我使用Stop-Transcriptcmdlet,所以输出到控制台的所有内容都(嗯,应该)记录到文件中。

一切都记录到文件中,直到到达使用 cmdlet 的脚本部分Invoke-RestMethod并输出响应。

这是控制台输出:

Transcript started, output file is DisableInactivePendingInviteAccounts.ps1.log
[20/12/2021 12:27:26] Getting API token...
[20/12/2021 12:27:26] Got API token!
[20/12/2021 12:27:26] Getting all user data...
[20/12/2021 12:27:37] Got all user data!
[20/12/2021 12:27:37] Determining which user accounts to disable...
[20/12/2021 12:27:37] User accounts to disable determined!
[20/12/2021 12:27:37] Building JSON batch request(s)...
[20/12/2021 12:27:37] Built JSON batch request #1, size: 4
[20/12/2021 12:27:37] Built JSON batch request(s)!
[20/12/2021 12:27:37] Making API request(s)...

responses
---------
{@{id=2; status=204; headers=; body=}, @{id=3; status=204; headers=; body=}, @{id=1; status=204; headers=; body=}, @...
[20/12/2021 12:27:38] API requests made!
[20/12/2021 12:27:38] User accounts disabled (4)
Transcript stopped, output file is <path>\DisableInactivePendingInviteAccounts.ps1.log

以下是日志文件内容:

**********************
Transcript started, output file is DisableInactivePendingInviteAccounts.ps1.log
[20/12/2021 12:27:26] Getting API token...
[20/12/2021 12:27:26] Got API token!
[20/12/2021 12:27:26] Getting all user data...
[20/12/2021 12:27:37] Got all user data!
[20/12/2021 12:27:37] Determining which user accounts to disable...
[20/12/2021 12:27:37] User accounts to disable determined!
[20/12/2021 12:27:37] Building JSON batch request(s)...
[20/12/2021 12:27:37] Built JSON batch request #1, size: 4
[20/12/2021 12:27:37] Built JSON batch request(s)!
[20/12/2021 12:27:37] Making API request(s)...

**********************
Windows PowerShell transcript end
End time: 20211220122738
**********************

如您所见,尽管控制台这样做了,但日志文件不包含“Making API request(s)...”输出之外的任何内容。为什么是这样?

编辑:

完整代码:

# Starts transcript so that outputs are logged to a file
Start-Transcript -Append "$($MyInvocation.MyCommand.Name).log"

# Causes the script to stop if an error occurs
$ErrorActionPreference = "Stop"

#######################################
# Connects to Graph and authenticates #
#######################################

Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Getting API token..."

$openid = Invoke-RestMethod -Uri <uri>
$bodyTokenRequest = @{
    client_id = <id>
    client_secret = <secret>
    redirect_uri = "https://localhost"
    grant_type = "client_credentials"
    resource = "https://graph.microsoft.com"
}
$request = Invoke-RestMethod -Method Post -Uri $openid.token_endpoint -Body $bodyTokenRequest

Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Got API token!"

#######################################
#   Retrieves all users from Graph    #
#######################################

# The initial URI to use
$uri = 'https://graph.microsoft.com/beta/users?$select=signInActivity'

# Empty array to be populated with users
$users = @()

# Populates $users with entries from every page from Graph
Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Getting all user data..."

do
{
    # API call to retrieve page of users and URI to next page
    $api = Invoke-RestMethod -Method Get -Headers @{Authorization = "Bearer $($request.access_token)"} -Uri $uri
    
    # Adds users from the page to $users
    $users += $api.value
    
    # New URI for next page
    $uri = $api."@odata.nextLink"
}
until ([string]::IsNullOrWhiteSpace($uri))

Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Got all user data!"

#######################################
#      Does stuff with the data       #
#######################################

# Gets all guest users who have not signed in within a year ago from now or since their account creation
Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Determining which user accounts to disable..."

$usersToDisable = @()
$aYearAgo = (Get-Date).AddYears(-1)
foreach ($user in $users)
{
    # The current user's last sign-in date
    $lastSignInDateTime = $user.signInActivity.lastSignInDateTime
    
    # Whether or not the current user has ever signed in before
    $hasSignedInBefore = ![string]::IsNullOrWhiteSpace($lastSignInDateTime)
    
    if ($user.accountEnabled -and $user.userType -eq "Guest" -and (($hasSignedInBefore -and [DateTime]$lastSignInDateTime -lt $aYearAgo) -or (!$hasSignedInBefore -and [DateTime]$user.createdDateTime -lt $aYearAgo)))
    {
        $usersToDisable += $user
    }
}

if ($usersToDisable.Count -gt 0)
{
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] User accounts to disable determined!"
    
    # Creates and populates $batchRequests with JSON batch requests, each containing 20 requests (or less) due to Graph limitations
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Building JSON batch request(s)..."
    
    $batchRequests = @()
    $batchRequest = @{}
    $requestsList = New-Object System.Collections.ArrayList
    for ($i = 0; $i -lt $usersToDisable.Count; $i++)
    {
        # Adds request to the current JSON batch request
        $requestsList.Add(@{
            "id" = $i + 1;
            "url" = "/users/{$($usersToDisable[$i].id)}";
            "method" = "PATCH";
            "body" = @{
                "accountEnabled" = "false"
            };
            "headers" = @{
                "Content-Type" = "application/json"
            }
        }) | Out-Null
        
        # Appends JSON batch request to $batchRequests if a multiple of 20, or if the end of $usersToDisable has been reached
        if (($i + 1) % 20 -eq 0 -or $i -ge $usersToDisable.Count - 1)
        {
            $batchRequest.Add("requests", $requestsList)
            $batchRequests += $batchRequest | ConvertTo-Json -Depth 3
            
            Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Built JSON batch request #$($batchRequests.Count), size: $($requestsList.Count)"
            
            $batchRequest = @{}
            $requestsList = New-Object System.Collections.ArrayList
        }
    }
    
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Built JSON batch request(s)!"
    
    # Calls API for each batch request
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] Making API request(s)..."
    
    foreach ($jsonBatchRequest in $batchRequests)
    {
        Invoke-RestMethod -Method Post -Headers @{Authorization = "Bearer $($request.access_token)"} -Uri 'https://graph.microsoft.com/v1.0/$batch' -ContentType "application/json" -Body $jsonBatchRequest
    }
    
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] API requests made!"
    
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] User accounts disabled ($($usersToDisable.Count)):"
    foreach ($user in $usersToDisable)
    {
        Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] $($user.id) ($($user.displayName))"
    }
}
else
{
    Write-Output "[$(Get-Date -Format 'dd/MM/yyyy HH:mm:ss')] There are currently no users that fit the criteria, so no accounts have been disabled."
}

# Stops transcript
Stop-Transcript

编辑 2:我不确定我可以在此处包含哪些更多信息来帮助回答这个问题。我真的很感谢在这方面有经验的人的一些建议,干杯。

编辑 3:这个问题仍然可以由对 PowerShell 有一半体面的人回答。干杯。

4

0 回答 0