Translate

Tuesday, January 19, 2016

Powershell log all commands

If you want to log every single powershell command, run on your machine , including the ones run through C# code, one way to do it is to upgrade to powershell 5.

Once you install powershell 5 all you need to do is to update a registry key to turn it on

HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription








































Here is the powershell script to do this

function Enable-PSTranscription 
{  
    [CmdletBinding()]  
    param(  
        $OutputDirectory,  
        [Switch] $IncludeInvocationHeader  
    )  

    ## Ensure the base path exists  
    $basePath = "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription"  

    if(-not (Test-Path $basePath))  
    {  
        $null = New-Item $basePath –Force  
    }

    ## Enable transcription  
    Set-ItemProperty $basePath -Name EnableTranscripting -Value 1

    ## Set the output directory  
    if($PSCmdlet.MyInvocation.BoundParameters.ContainsKey("OutputDirectory"))  
    {  
        Set-ItemProperty $basePath -Name OutputDirectory -Value $OutputDirectory  
    }

    ## Set the invocation header  
    if($IncludeInvocationHeader)  
    {  
        Set-ItemProperty $basePath -Name EnableInvocationHeader -Value 1  
    } 
}

Enable-PSTranscription  -OutputDirectory 'C:\PowershellLogs'



To enable more detailed logging run this powershell command below after you performed the above steps

function Enable-PSScriptBlockLogging 
{  
    $basePath = "HKLM:\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"  

    if(-not (Test-Path $basePath))  
    {  
        $null = New-Item $basePath –Force  
    }
   
    Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1" 
}


Enable-PSScriptBlockLogging 


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator