Private/Csv.ps1

# CSV round trip. Export is a superset of the existing Intune-ScopeTag-UpdateTemplate.csv, so files made by the old scripts still import,
# and files exported here still work with the old Update-IntuneScopeTags-Bulk script.

$script:STMCsvColumns = 'ObjectType', 'ObjectId', 'DisplayName', 'Category', 'Platform', 'CurrentScopeTagIds', 'CurrentScopeTags', 'ScopeTags', 'Mode', 'Notes', 'SerialNumber', 'UserPrincipalName'

function ConvertTo-STMSafeCsvText {
    # Spreadsheet formula injection guard: text that Excel would run as a formula is prefixed with ' so it stays text.
    param([string]$Value)
    if ($Value -match '^[=+\-@\t\r]') { return "'$Value" }
    return $Value
}

function ConvertTo-STMCsvRow {
    param([Parameter(Mandatory)]$Row)
    $extra = $Row.Extra
    [pscustomobject][ordered]@{
        ObjectType = $Row.Type; ObjectId = $Row.Id; DisplayName = (ConvertTo-STMSafeCsvText $Row.Name); Category = $Row.Category; Platform = $Row.Platform
        CurrentScopeTagIds = (@($Row.TagIds) -join ';'); CurrentScopeTags = (ConvertTo-STMSafeCsvText ((@($Row.TagIds) | ForEach-Object { Get-STMTagName $_ }) -join ';'))
        ScopeTags = ''; Mode = ''; Notes = ''
        SerialNumber = if ($extra) { ConvertTo-STMSafeCsvText $extra.serial } else { '' }
        UserPrincipalName = if ($extra) { ConvertTo-STMSafeCsvText $extra.upn } else { '' }
    }
}

function Export-STMInventoryCsv {
    <#
    .SYNOPSIS
      Writes loaded objects to a CSV that people can edit in Excel and import again.
    .DESCRIPTION
      Fill ScopeTags (names or ids, separated by ;) and Mode (Add, Remove or Replace) on the rows you want to change.
      Rows with an empty Mode are ignored on import.
    #>

    param([Parameter(Mandatory)][string]$Path, [string[]]$Type, [switch]$IncludeDevices)
    $rows = @($script:STM.Inventory.Values | Where-Object {
        ($IncludeDevices -or $_.Type -ne 'ManagedDevice') -and (-not $Type -or $Type -contains $_.Type)
    } | Sort-Object Category, TypeLabel, Name)
    $rows | ForEach-Object { ConvertTo-STMCsvRow -Row $_ } | Export-Csv -LiteralPath $Path -NoTypeInformation -Encoding utf8
    Write-STMAudit -Event 'InventoryExported' -Data @{ path = $Path; rows = $rows.Count }
    return Get-Item -LiteralPath $Path
}

function Split-STMTagList {
    param([string]$Value)
    if ([string]::IsNullOrWhiteSpace($Value)) { return @() }
    return @($Value -split '[;,|]' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
}

function Find-STMDevice {
    # Device rows can name a device by serial number or device name; resolve to exactly one managed device.
    param([string]$SerialNumber, [string]$DeviceName)
    $field = if ($SerialNumber) { 'serialNumber' } else { 'deviceName' }
    $value = if ($SerialNumber) { $SerialNumber } else { $DeviceName }
    $local = @($script:STM.Inventory.Values | Where-Object {
        $_.Type -eq 'ManagedDevice' -and (($SerialNumber -and $_.Extra.serial -ieq $SerialNumber) -or ($DeviceName -and $_.Name -ieq $DeviceName))
    })
    if ($local.Count -eq 1) { return @{ Id = $local[0].Id; Error = $null } }
    if ($local.Count -gt 1) { return @{ Id = $null; Error = "$($local.Count) devices have $field '$value'; use the device id (ObjectId)" } }
    $def = Get-STMTypeDef -Key 'ManagedDevice'
    $filter = [uri]::EscapeDataString("$field eq '$($value.Replace("'", "''"))'")
    try { $r = Invoke-STMGraph -Method GET -Uri "$($def.path)?`$filter=$filter&`$select=$($def.select)&`$top=5" }
    catch { return @{ Id = $null; Error = "Device lookup failed: $($_.Exception.Message)" } }
    $found = @($r.value)
    if ($found.Count -eq 1) {
        $row = ConvertTo-STMRow -TypeDef $def -Object $found[0]
        $script:STM.Inventory[$row.Key] = $row
        return @{ Id = $row.Id; Error = $null }
    }
    if ($found.Count -gt 1) { return @{ Id = $null; Error = "Several devices have $field '$value'; use the device id (ObjectId)" } }
    return @{ Id = $null; Error = "No managed device with $field '$value'" }
}

function ConvertFrom-STMCsvRows {
    <#
      Accepts three layouts:
        1. This tool's export, or the older Intune-ScopeTag-UpdateTemplate.csv: ObjectType, ObjectId, ScopeTags, Mode[, Notes]
        2. The older bulk import file: ObjectType, ObjectId, ScopeTags, Mode
        3. Devices by serial or name (older Set-IntuneScopeTags input): SerialNumber or DeviceName, ScopeTags (or ScopeTagIds), Mode (Add, Remove, Set)
      Returns @{ Operations; Errors; Skipped; Rows }
    #>

    param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$Rows, [string]$SourceName = 'CSV')
    $ops = [System.Collections.Generic.List[object]]::new()
    $errors = [System.Collections.Generic.List[object]]::new()
    $skipped = 0; $n = 1
    $known = @((Get-STMTypeRegistry).key)
    foreach ($r in $Rows) {
        $n++  # row 1 is the header, so data starts at 2 (matches Excel)
        $type = "$(Get-STMProp $r 'ObjectType')".Trim()
        $id = "$(Get-STMProp $r 'ObjectId')".Trim()
        $modeRaw = "$(Get-STMProp $r 'Mode')".Trim()
        if (-not $modeRaw) { $modeRaw = "$(Get-STMProp $r 'Action')".Trim() }
        $tagsRaw = Get-STMProp $r 'ScopeTags'
        if ($null -eq $tagsRaw) { $tagsRaw = Get-STMProp $r 'ScopeTagIds' }
        $note = "$(Get-STMProp $r 'Notes')".Trim()
        if (-not $modeRaw) { $skipped++; continue }
        $mode = ConvertTo-STMMode -Mode $modeRaw
        if (-not $mode) { $errors.Add([pscustomobject]@{ Row = $n; Object = "$type $id"; Message = "Mode '$modeRaw' is not Add, Remove or Replace" }); continue }
        if (-not $id) {
            $serial = "$(Get-STMProp $r 'SerialNumber')".Trim(); $dname = "$(Get-STMProp $r 'DeviceName')".Trim()
            if ($serial -or $dname) {
                $d = Find-STMDevice -SerialNumber $serial -DeviceName $dname
                if ($d.Error) { $errors.Add([pscustomobject]@{ Row = $n; Object = if ($serial) { "Serial $serial" } else { "Device $dname" }; Message = $d.Error }); continue }
                $type = 'ManagedDevice'; $id = $d.Id
            }
            else { $errors.Add([pscustomobject]@{ Row = $n; Object = $type; Message = 'ObjectId is empty (or give SerialNumber or DeviceName for devices)' }); continue }
        }
        if (-not $type) { $errors.Add([pscustomobject]@{ Row = $n; Object = $id; Message = 'ObjectType is empty' }); continue }
        if ($known -notcontains $type) { $errors.Add([pscustomobject]@{ Row = $n; Object = "$type $id"; Message = "Unknown ObjectType '$type'" }); continue }
        $tags = Split-STMTagList -Value "$tagsRaw"
        if ($mode -ne 'Replace' -and -not $tags.Count) { $errors.Add([pscustomobject]@{ Row = $n; Object = "$type $id"; Message = "$mode needs at least one scope tag in ScopeTags" }); continue }
        $res = Resolve-STMTagTokens -Tokens $tags
        if ($res.Errors.Count) { foreach ($e in $res.Errors) { $errors.Add([pscustomobject]@{ Row = $n; Object = "$type $id"; Message = $e }) }; continue }
        $ops.Add([pscustomobject]@{ Type = $type; Id = $id; Mode = $mode; Tags = @($res.Ids); Note = $note; Source = "${SourceName}:row $n" })
    }
    return @{ Operations = @($ops); Errors = @($errors); Skipped = $skipped; Rows = @($Rows).Count }
}

function Import-STMCsv {
    param([Parameter(Mandatory)][string]$Path)
    if (-not $script:STM.Tags) { [void](Update-STMScopeTags) }
    $rows = @(Import-Csv -LiteralPath $Path)
    return ConvertFrom-STMCsvRows -Rows $rows -SourceName (Split-Path -Leaf $Path)
}