Search code examples
powershelldirectoryfilepathevent-viewer

Finding The Correct File Path For a Powershell Script


So i have been working on this script at home

    Copy-Item "$env:SystemRoot\System32\Winevt\Logs\Security.evtx" "C:\CommFiles\LogFile_$(get-date -uformat %d-%m-%Y-%H.%M.%S).evtx"
if(-not $?) { 
Write-Warning "Copy Failed" 
} else {
Remove-Item "$env:SystemRoot\System32\Winevt\Logs\Security.evtx"
}

and i know it works because i used it at home and it has the same file path that i use in office but i keep getting this warning

Copy-Item : Could not find a part of the path 'C:\windows\System32\Winevt\Logs\Security.evtx'.
At line:1 char:1
+ Copy-Item "$env:SystemRoot\System32\Winevt\Logs\Security.evtx" "C:\Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : 
System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand

i suspect that im not in the right directory but because of my limited knowledge on powershell im uncertain of what the right one might be for my case. im using this script to copy my event viewer log to a new file path for organised


Solution

  • The file path can be found with the following steps:

    1. Open Event Viewer as an administrator or a user with permission to view the security log.
    2. Right-click the security log object on the left and open Properties.

    SecurityLog

    Or you can get the full path with powershell by checking the registry - note that this also requires running powershell as an admin user:

    PS C:\> (Get-ItemProperty HKLM:\system\CurrentControlSet\Services\EventLog\Security\).file
    
    C:\WINDOWS\System32\winevt\Logs\Security.evtx
    

    Since your error specifically says DirectoryNotFound, try and find which directory it fails to open:

    gci C:\
    gci C:\windows\
    gci C:\windows\System32\
    gci C:\windows\System32\Winevt\
    gci C:\windows\System32\Winevt\Logs\
    

    And investigate the permissions on it:

    (get-acl C:\Windows\System32\winevt\).Access | select IdentityReference,FileSystemRights
    
    IdentityReference                FileSystemRights
    -----------------                ----------------
    NT AUTHORITY\Authenticated Users Read, Synchronize
    NT AUTHORITY\SYSTEM              FullControl
    BUILTIN\Administrators           FullControl
    NT SERVICE\EventLog              DeleteSubdirectoriesAndFiles, Write, ReadAndExecute, Synchronize
    

    If everything seems fine there, consider trying the same thing on a different PC? I've had filesystem/harddrive issues that behaved like this, but it's not very likely