Tags

, , ,


I recently needed to generate a list of files accessed on a remote machine and where they had been opened from. I was a bit surprised that I couldn’t find a better way of resolving shortcut targets than using a COM object…!
I’ve split the code into two functions – one to generate objects and one to output them to a file in the way I required.

function Get-RecentFiles {
    [CmdletBinding()]
    param(
        [string]$computerName = "localhost",
        [string]$userName = (Get-ChildItem -Path "ENV:Username" | Select-Object -ExpandProperty Value)
    )
    $wshShell = New-Object -ComObject "WScript.Shell"
    $remoteOS = Get-WmiObject -ComputerName $computerName -Class Win32_Operatingsystem | Select-Object -ExpandProperty Version
    if ($remoteOS.Substring(0,1) -eq "5") {
        $remotePath = "\\$computerName\c$\Documents and Settings\$userName\Recent"
    } else {
        $remotePath = "\\$computerName\c$\Users\$userName\AppData\Roaming\Microsoft\Windows\Recent"
    }
    if ((Test-Path -Path $remotePath) -eq $true) {
        $files = Get-ChildItem -Path $remotePath | Sort-Object -Property LastWriteTime -Descending
        $files | ForEach-Object {
            $file = $_
            $validTarget = $true
            try {
                $target = $wshShell.CreateShortcut($file.FullName).TargetPath
            } catch {
                $validTarget = $false
            }
            if ($validTarget) {
                $props = @{
                    Name = $file.Name
                    LastWriteTime = $file.LastWriteTime
                    ShortcutTarget = $target -replace ([Regex]::Escape(($env:USERPROFILE)), "USERPROFILE")
                }
                $obj = New-Object -TypeName PSObject -Property $props
                Write-Output $obj
            } # if
        } # foreach
    } # if
}

function Write-RecentFiles {
    param(
        [string]$computerName = "localhost",
        [string]$userName = (Get-ChildItem -Path "ENV:Username" | Select-Object -ExpandProperty Value),
        [Parameter()]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$outputFolderPath = "C:"
    )
    $outputFolderPath = $outputFolderPath -replace "\\$", ""
    $formattedDate = (Get-Date).ToShortDateString().ToString().Replace("/", "-")
    $undottedUser = $userName.Replace(".", "")
    Get-RecentFiles -computerName $computerName -userName $userName | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath "$($outputFolderPath)\RecentFiles_$($undottedUser)_$($computerName.ToUpper())_$($formattedDate).csv" -Encoding ASCII
}

Write-RecentFiles -computerName "TargetMachine" -userName "TargetUserName" -outputFolderPath "c:\"
Advertisements