Howto delete powershell transcript files with intune

Shorty 0 Reputation points
2023-02-08T15:35:55.9+00:00

Hi there,

we have several powershell scripts that are using the command start-transcript to do a kind of debug logging when running via the Intune Management Engine. Those files are stored in the default Intune Folder in C:\ProgramData\Microsoft\IntuneManagementExtension\Logs and every filename has a timestamp at the end. Our Goal is to keep at least 5 newest logs files.

How can we now delete existing log files with powershell scripts that runs "with" Intune? Currently we are receiving the following error message:

    + FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand

Is there a way to achive this with Powershell? Does start-transcript has some kind of Log-Rotation?

Microsoft Intune
Microsoft Intune
A Microsoft cloud-based management solution that offers mobile device management, mobile application management, and PC management capabilities.
4,332 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,052 questions
0 comments No comments
{count} votes

7 answers

Sort by: Most helpful
  1. Crystal-MSFT 42,961 Reputation points Microsoft Vendor
    2023-02-09T01:36:13.22+00:00

    @Shorty,Thanks for posting in Q&A.

    In General, the _IntuneManagementExtension.log is the rollover log file. In total we have 4 MB log file storage to store processing information.

    To control the log file size and the amount of log files, we can configure the registry key LogMaxHistory and LogMaxSize under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\IntuneWindowsAgent\Logging

    Intune Agent, Intune Management Extension (IME) log file parameters LogMaxHistory and LogMaxSize

    For example, if you want to keep 5 file logs, you can set the LogMaxHistory registry key with value 5.

    We can test on one device, restart and see if it works. If it works, we can consider deploying PowerShell script to add it via Intune PowerShell script. Here is a link with the script:

    https://github.com/okieselbach/Intune/blob/master/EnhanceIntuneAgentLogging.ps1

    Note: Non-Microsoft link, just for the reference. Also needs to change the value to the one you want.

    To know more details, you can refer to the following link:

    https://oliverkieselbach.com/2020/09/22/enhance-intune-management-extension-ime-logging/

    Note: Non Microsoft link, just for your reference.

    Hope it can help.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Shorty 0 Reputation points
    2023-02-09T07:16:11.2633333+00:00

    Hi @Crystal-MSFT ,

    thanks for those links but I'm not talking about the normal intune service and its logging files. Its about a self-created powershell script that uses the command start-transcript for logging into the folder C:\ProgramData\Microsoft\IntuneManagementExtension\Logs.

    Our Code looks like

    $transscript_file_name = $env:programdata + "\Microsoft\IntuneManagementExtension\logs\INTUNE-ps-debug_" + $filename + "-" + $timestamp + ".log"
    
    Start-Transcript -Path $transscript_file_name -Force
    

    And this might cause the problem, because we are not able to delete files that were created in this way - normal (single) transcript-files can be overwritten but in this case we are not able to delete old files that.

    User's image

    We only wan to keep three of them.

    P.S. code exists and is working perfect with other directories and files but not in this case


  3. Shorty 0 Reputation points
    2023-02-09T08:00:42.44+00:00

    @Crystal-MSFT correct.

    The user has full access to those files but the transcript command can't delete it.

    User's image

    User's image

    How can I send the script to you?

    0 comments No comments

  4. Shorty 0 Reputation points
    2023-02-09T15:16:26.81+00:00

    @Crystal-MSFT below you will find a part of the script. I removed the unnecessary part in the middle of the script because it is not related to the problem mentioned here.

    function writetotranscript ($message) {
        if ($debug_enabled -eq "1"){
        write-output ""
        write-output "--------------------------------------------------------------------"
        write-output "$message"
        write-output "--------------------------------------------------------------------"
        write-output ""
        }
    }
    
    $args_count=$Args.Count
    $i=0
    $args_array=@()
    do{
    $args_array += $args[$i]
    $i++
    }until ($i -eq $args_count )
    $argsString= [string]$args_array
    
    
    
    If ($ENV:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
        Try {
            foreach($k in $MyInvocation.BoundParameters.keys)
            {
                switch($MyInvocation.BoundParameters[$k].GetType().Name)
                {
                    "SwitchParameter" {if($MyInvocation.BoundParameters[$k].IsPresent) { $argsString += "-$k " } }
                    "String"          { $argsString += "-$k `"$($MyInvocation.BoundParameters[$k])`" " }
                    "Int32"           { $argsString += "-$k $($MyInvocation.BoundParameters[$k]) " }
                    "Boolean"         { $argsString += "-$k `$$($MyInvocation.BoundParameters[$k]) " }
                }
            }
            Start-Process -FilePath "$ENV:WINDIR\SysNative\WindowsPowershell\v1.0\PowerShell.exe" -ArgumentList "-File $PSCOMMANDPATH $($argsString)" -Wait -NoNewWindow
        }
        Catch {
            Throw "Failed to start 64-bit PowerShell"
        }
        Exit
    }
    
    
    $filename=$($MyInvocation.MyCommand.Definition)
    $filename = $filename.split("\")
    $value= $filename.count
    $value= $value - 1
    $filename = $filename[$value]
    $filename=$filename.split(".")
    $filename=$filename[0]
    
    
    $debug_enabled = 0
    $args_array = $args_array.split(" ")
    foreach ($argument in $args_array){
    if ($argument -like "*debug*"){
    $debug_enabled = 1
    # remove debug setting from the array of arguments
    $args_array = $args_array | Where-Object { $_ –ne "debug" }
    }
    }
    
    
    function execute_command ($command) {
    
        try
            { 
              $command
            }
        catch [System.IO.IOException] {
            Write-output "$($_.Exception.Message)" | out-file -FilePath $logfile
            exit 1
        }
        catch {
            Write-output "$($_.Exception.Message)" | out-file -FilePath $logfile
            exit 1
        }
    
    }
    
    
    if ($debug_enabled -eq 1) {
        $timestamp = (get-date -f yyyyMMdd-hhmmss)
        $transscript_file_name = $env:programdata + "\Microsoft\IntuneManagementExtension\logs\INTUNE-ps-debug_" + $filename + "-" + $timestamp + ".log"
        Start-Transcript -Path $transscript_file_name -Force
    
        $transscript_filter_file_name = $env:programdata + "\Microsoft\IntuneManagementExtension\logs\INTUNE-ps-debug_" + $filename + "-*.log"
        $LastFiveFiles = (Get-ChildItem -Force -Recurse -File -Path $transscript_filter_file_name -ErrorAction SilentlyContinue | Sort-Object CreationTime -Descending | Select-Object -First 5 )
        $FilesInFolder = (Get-ChildItem -Force -Recurse -File -Path $transscript_filter_file_name)
    
        $FilesToKeep=@{}
        $LastFiveFiles| ForEach-Object {
                $FilesToKeep.Add("$($_.FullName)","$($_.CreationTime)")
            }
    
        foreach ($file in $FilesInFolder){
            if ($FilesToKeep.ContainsKey($file.FullName)){
                write-output "continue"
                continue
            }
            else {
                write-output "delete file"
                remove-item -force -Confirm:$false -path $file.FullName
            }
        }
    
    }
    
    #----------------------------------------------
    # script - begin 
    #----------------------------------------------
    
    # here the script is doing some commands that doesn't relate to the problem
    
    #----------------------------------------------
    # script - part END
    #----------------------------------------------
    if ($debug_enabled -eq 1) {
        Stop-Transcript
    }
     
    
    
    

    This script is uploaded as intunewin-file to intune and will be executed once a day (as an application in user context).

    Cheers Shorty


  5. MotoX80 31,571 Reputation points
    2023-02-09T22:59:11.9133333+00:00

    The user has full access to those files but the transcript command can't delete it.

    Your image shows that the user is the owner but the ACL's do not grant access. On the logs folder grant Everyone full control. That should fix it.

    0 comments No comments