Functions/UserManagement/New-BCUserStateJsonFile.ps1

<#
.Synopsis
    Writes the UserSecurityID, UserName and State from all Business Central users to a .json file.
.Description
    This cmdlet executes the following actions:
     - Creates the destination folder if not exists.
     - Receives all users from the supplied BC ServerInstance
       (please note that the BC modules should already be imported)
     - Writes the users to a json file to the LogFilePath location.
     - Cleanup older json files (keep max 10 logfiles per ServerInstance)
 
    Default the .json file will be written to ProgramData\4ps\BcUsers. The file contains the UserSecurityID, UserName and State of all BC users.
     
    This cmdlet is often used together with Set-AllUsersDisabled and Set-InitialUserStatusUsingLogFile.
.Example
    New-BcUserStateJsonFile -ServerInstance 'BC170'
.Example
    'BC170' | New-BcUserStateJsonFile
#>


function New-BcUserStateJsonFile{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)]
        [string] $ServerInstance,
        [parameter(Mandatory=$false)]
        [string] $LogFilePath = (Join-Path -Path $env:ProgramData -ChildPath '4ps\BcUsers')
    )

    # Create destination folder if not exists
    if((Test-Path $LogFilePath) -eq $false){
        New-Item -Path $LogFilePath -ItemType Directory | Out-Null
    }
    
    # Set logfile filepath
    $logFileName = '{0}_{1}.json' -f (Get-Date).ToString('yyyy-MM-dd_HH.mm.ss'), $ServerInstance
    $logFile = Join-Path -Path $LogFilePath -ChildPath $logFileName

    # Get users from Business Central
    $AllUsers = Get-NAVServerUser -ServerInstance $ServerInstance

    Write-Host ('Writing json log file with Business Central User status to: {0}' -f $LogFile )

    # Write users to json file
    $AllUsers | Select-Object -Property UserSecurityID, UserName, State | ConvertTo-Json | Out-File ($LogFile)

    # Cleanup older json files (keep max 10 logfiles per ServerInstance)
    $Regex = '.*_{0}\.json' -f $ServerInstance
    $LogFiles = Get-ChildItem $LogFilePath -File | Where-Object -Property Name -Match $Regex
    if($LogFiles.Count -gt 10){
        $LogFiles | Sort-Object -Property CreationTime -Descending | Select-Object -Skip 10 | Remove-Item -Force -ErrorAction SilentlyContinue
    }

    return $logFile
}

Export-ModuleMember -Function New-BcUserStateJsonFile