├── .github ├── release-drafter.yml └── workflows │ └── ci-master-pr.yml ├── .gitignore ├── .gitmodules ├── .vscode └── tasks.json ├── LICENSE ├── README.md ├── build └── definitions │ └── modulemanifest.ps1 ├── src └── Log-Rotate │ ├── Log-Rotate.Integration.Tests.ps1 │ ├── Log-Rotate.psd1 │ ├── Log-Rotate.psm1 │ ├── classes │ ├── New-BlockFactory.ps1 │ ├── New-LogFactory.ps1 │ └── New-LogObject.ps1 │ ├── helpers │ ├── Extend-Class.Tests.ps1 │ ├── Extend-Class.ps1 │ ├── Get-Exception-Message.Tests.ps1 │ ├── Get-Exception-Message.ps1 │ ├── Get-Size-Bytes.Tests.ps1 │ ├── Get-Size-Bytes.ps1 │ ├── Start-Script.Tests.ps1 │ ├── Start-Script.ps1 │ ├── likeIn.Tests.ps1 │ └── likeIn.ps1 │ ├── private │ ├── config │ │ ├── Compile-Full-Config.Tests.ps1 │ │ ├── Compile-Full-Config.ps1 │ │ ├── Validate-Full-Config.Tests.ps1 │ │ └── Validate-Full-Config.ps1 │ └── rotate │ │ ├── Process-Local-Block.Tests.ps1 │ │ └── Process-Local-Block.ps1 │ └── public │ ├── Log-Rotate.Tests.ps1 │ └── Log-Rotate.ps1 └── test └── test.ps1 /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: 'v$RESOLVED_VERSION 🌈' 2 | tag-template: 'v$RESOLVED_VERSION' 3 | categories: 4 | - title: '🚀 Features' 5 | labels: 6 | - 'feature' 7 | - title: '✨ Enhancements' 8 | labels: 9 | - 'enhancement' 10 | - title: '🎚 Change' 11 | labels: 12 | - 'change' 13 | - title: '🐛 Bug Fixes' 14 | labels: 15 | - 'fix' 16 | - 'bug' 17 | - title: '🖊️ Refactors' 18 | labels: 19 | - 'refactor' 20 | - title: '👗 Style' 21 | labels: 22 | - 'style' 23 | - title: '📝 Documentation' 24 | labels: 25 | - 'docs' 26 | - 'documentation' 27 | - title: '🧰 Maintenance' 28 | label: 'chore' 29 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)' 30 | version-resolver: 31 | major: 32 | labels: 33 | - 'breaking' 34 | minor: 35 | labels: 36 | - 'feature' 37 | - 'enhancement' 38 | - 'change' 39 | - 'refactor' 40 | patch: 41 | labels: 42 | - 'fix' 43 | - 'bug' 44 | - 'style' 45 | - 'docs' 46 | - 'documentation' 47 | - 'chore' 48 | default: patch 49 | sort-by: title 50 | template: | 51 | ## Changes 52 | 53 | $CHANGES 54 | -------------------------------------------------------------------------------- /.github/workflows/ci-master-pr.yml: -------------------------------------------------------------------------------- 1 | name: ci-master-pr 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | tags: 8 | - '**' 9 | pull_request: 10 | branches: 11 | - master 12 | 13 | jobs: 14 | test-powershell-5-1-windows-2019: 15 | runs-on: windows-2019 16 | steps: 17 | - uses: actions/checkout@v1 18 | - name: Powershell version 19 | run: | 20 | powershell -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 21 | - name: Test 22 | run: | 23 | powershell -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 24 | 25 | ########## 26 | # Docker # 27 | ########## 28 | # Get powershell tags: https://mcr.microsoft.com/v2/powershell/tags/list 29 | test-powershell-6-0: 30 | runs-on: ubuntu-latest 31 | container: 32 | image: theohbrothers/docker-powershell:6.0.4-ubuntu-16.04-git 33 | steps: 34 | - uses: actions/checkout@v1 35 | - name: Powershell version 36 | run: | 37 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 38 | - name: Test 39 | run: | 40 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 41 | 42 | test-powershell-6-1: 43 | runs-on: ubuntu-latest 44 | container: 45 | image: theohbrothers/docker-powershell:6.1.3-ubuntu-18.04-git 46 | steps: 47 | - uses: actions/checkout@v1 48 | - name: Powershell version 49 | run: | 50 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 51 | - name: Test 52 | run: | 53 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 54 | 55 | test-powershell-6-2: 56 | runs-on: ubuntu-latest 57 | container: 58 | image: theohbrothers/docker-powershell:6.2.4-ubuntu-18.04-git 59 | steps: 60 | - uses: actions/checkout@v1 61 | - name: Powershell version 62 | run: | 63 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 64 | - name: Test 65 | run: | 66 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 67 | 68 | test-powershell-7-0: 69 | runs-on: ubuntu-latest 70 | container: 71 | image: theohbrothers/docker-powershell:7.0.3-ubuntu-18.04-git 72 | steps: 73 | - uses: actions/checkout@v1 74 | - name: Powershell version 75 | run: | 76 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 77 | - name: Test 78 | run: | 79 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 80 | 81 | test-powershell-7-1: 82 | runs-on: ubuntu-latest 83 | container: 84 | image: theohbrothers/docker-powershell:7.1.5-ubuntu-20.04-git 85 | steps: 86 | - uses: actions/checkout@v1 87 | - name: Powershell version 88 | run: | 89 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 90 | - name: Test 91 | run: | 92 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 93 | 94 | test-powershell-7-2: 95 | runs-on: ubuntu-latest 96 | container: 97 | image: theohbrothers/docker-powershell:7.2-ubuntu-22.04-git 98 | steps: 99 | - uses: actions/checkout@v1 100 | - name: Powershell version 101 | run: | 102 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 103 | - name: Test 104 | run: | 105 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 106 | 107 | test-powershell-7-3: 108 | runs-on: ubuntu-latest 109 | container: 110 | image: theohbrothers/docker-powershell:7.3-ubuntu-22.04-git 111 | steps: 112 | - uses: actions/checkout@v1 113 | - name: Powershell version 114 | run: | 115 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 116 | - name: Test 117 | run: | 118 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 119 | 120 | test-powershell-7-4: 121 | runs-on: ubuntu-latest 122 | container: 123 | image: theohbrothers/docker-powershell:7.4-ubuntu-22.04-git 124 | steps: 125 | - uses: actions/checkout@v1 126 | - name: Powershell version 127 | run: | 128 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 129 | - name: Test 130 | run: | 131 | pwsh -NoLogo -NonInteractive -NoProfile -Command './test/test.ps1' 132 | 133 | update-draft-release: 134 | needs: 135 | - test-powershell-5-1-windows-2019 136 | - test-powershell-6-0 137 | - test-powershell-6-1 138 | - test-powershell-6-2 139 | - test-powershell-7-0 140 | - test-powershell-7-1 141 | - test-powershell-7-2 142 | - test-powershell-7-3 143 | - test-powershell-7-4 144 | - test-publish-to-psgallery 145 | if: github.ref == 'refs/heads/master' 146 | runs-on: ubuntu-latest 147 | steps: 148 | # Drafts your next Release notes as Pull Requests are merged into "master" 149 | - uses: release-drafter/release-drafter@v5 150 | with: 151 | config-name: release-drafter.yml 152 | publish: false 153 | env: 154 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 155 | 156 | test-publish-to-psgallery: 157 | runs-on: ubuntu-latest 158 | container: 159 | image: theohbrothers/docker-powershell:7.4-ubuntu-22.04-git 160 | steps: 161 | - uses: actions/checkout@v1 162 | with: 163 | submodules: true 164 | - name: Install wget 165 | run: | 166 | apt-get update && apt-get install -y wget 167 | - uses: actions/setup-dotnet@v4 168 | with: 169 | dotnet-version: '6' 170 | - name: Powershell version 171 | run: | 172 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 173 | - name: Ignore git permissions 174 | run: | 175 | git config --global --add safe.directory "$( pwd )" 176 | - name: Publish (dry run) 177 | shell: pwsh 178 | env: 179 | MODULE_VERSION: '999.0.0' 180 | NUGET_API_KEY: 'xxx' 181 | run: | 182 | $ErrorActionPreference = 'Stop' 183 | Import-Module ./build/PSModulePublisher/src/PSModulePublisher -Force 184 | $moduleManifest = Invoke-Build 185 | Invoke-Publish -ModuleManifestPath $moduleManifest -Repository PSGallery -DryRun 186 | 187 | publish-to-psgallery: 188 | needs: 189 | - test-powershell-5-1-windows-2019 190 | - test-powershell-6-0 191 | - test-powershell-6-1 192 | - test-powershell-6-2 193 | - test-powershell-7-0 194 | - test-powershell-7-1 195 | - test-powershell-7-2 196 | - test-powershell-7-3 197 | - test-powershell-7-4 198 | - test-publish-to-psgallery 199 | if: startsWith(github.ref, 'refs/tags/') 200 | runs-on: ubuntu-latest 201 | container: 202 | image: theohbrothers/docker-powershell:7.4-ubuntu-22.04-git 203 | steps: 204 | - uses: actions/checkout@v1 205 | with: 206 | submodules: true 207 | - name: Install wget 208 | run: | 209 | apt-get update && apt-get install -y wget 210 | - uses: actions/setup-dotnet@v4 211 | with: 212 | dotnet-version: '6' 213 | - name: Powershell version 214 | run: | 215 | pwsh -NoLogo -NonInteractive -NoProfile -Command '$PSVersionTable' 216 | - name: Ignore git permissions 217 | run: | 218 | git config --global --add safe.directory "$( pwd )" 219 | - name: Set MODULE_VERSION 220 | run: | 221 | echo "MODULE_VERSION=$( echo "$GITHUB_REF_NAME" | sed 's/v//g' )" >> $GITHUB_ENV 222 | - name: Publish 223 | shell: pwsh 224 | env: 225 | MODULE_VERSION: ${{ env.MODULE_VERSION }} 226 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} 227 | run: | 228 | $ErrorActionPreference = 'Stop' 229 | Import-Module ./build/PSModulePublisher/src/PSModulePublisher -Force 230 | $moduleManifest = Invoke-Build 231 | Invoke-Publish -ModuleManifestPath $moduleManifest -Repository PSGallery 232 | 233 | publish-draft-release: 234 | needs: [publish-to-psgallery] 235 | if: startsWith(github.ref, 'refs/tags/') 236 | runs-on: ubuntu-latest 237 | steps: 238 | # Drafts your next Release notes as Pull Requests are merged into "master" 239 | - uses: release-drafter/release-drafter@v5 240 | with: 241 | config-name: release-drafter.yml 242 | publish: true 243 | name: ${{ github.ref_name }} # E.g. 'master' or 'v1.2.3' 244 | tag: ${{ github.ref_name }} # E.g. 'master' or 'v1.2.3' 245 | env: 246 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 247 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.* 2 | !/.github 3 | !/.gitignore 4 | !/.gitmodules 5 | !/.vscode 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "build/PSModulePublisher"] 2 | path = build/PSModulePublisher 3 | url = https://github.com/theohbrothers/PSModulePublisher.git 4 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "inputs": [ 6 | { 7 | "id": "NUGET_API_KEY", 8 | "description": "NUGET_API_KEY?", 9 | "type": "promptString", 10 | "default": "xxx", 11 | }, 12 | { 13 | "id": "MODULE_VERSION", 14 | "description": "MODULE_VERSION?", 15 | "type": "promptString", 16 | "default": "0.0.0", 17 | }, 18 | ], 19 | "tasks": [ 20 | { 21 | "label": "Test (pwsh)", 22 | "type": "shell", 23 | "command": "pwsh -Command test/test.ps1", 24 | "group": "build" 25 | }, 26 | { 27 | "label": "Test (powershell)", 28 | "type": "shell", 29 | "command": "powershell -Command test/test.ps1", 30 | "group": "build" 31 | }, 32 | { 33 | "label": "Build: Generate module manifest", 34 | "type": "shell", 35 | "command": "MODULE_VERSION=${input:MODULE_VERSION} pwsh -Command '$ErrorActionPreference = \"Stop\"; Import-Module ./build/PSModulePublisher/src/PSModulePublisher -Force; $moduleManifest = Invoke-Build'", 36 | "group": "build" 37 | }, 38 | { 39 | "label": "Publish module (dry run)", 40 | "dependsOn":[ 41 | "Build: Generate module manifest" 42 | ], 43 | "type": "shell", 44 | "command": "NUGET_API_KEY=${input:NUGET_API_KEY} MODULE_VERSION=${input:MODULE_VERSION} pwsh -Command '$ErrorActionPreference = \"Stop\"; Import-Module ./build/PSModulePublisher/src/PSModulePublisher -Force; $moduleManifest = Invoke-Build; Invoke-Publish -ModuleManifestPath $moduleManifest -Repository PSGallery -DryRun'", 45 | "group": "build" 46 | }, 47 | { 48 | "label": "Publish module", 49 | "dependsOn":[ 50 | "Build: Generate module manifest" 51 | ], 52 | "type": "shell", 53 | "command": "NUGET_API_KEY=${input:NUGET_API_KEY} MODULE_VERSION=${input:MODULE_VERSION} pwsh -Command '$ErrorActionPreference = \"Stop\"; Import-Module ./build/PSModulePublisher/src/PSModulePublisher -Force; $moduleManifest = Invoke-Build; Invoke-Publish -ModuleManifestPath $moduleManifest -Repository PSGallery'", 54 | "group": "build" 55 | }, 56 | 57 | ] 58 | } 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Log-Rotate 2 | 3 | [![github-actions](https://github.com/theohbrothers/Log-Rotate/actions/workflows/ci-master-pr.yml/badge.svg?branch=master)](https://github.com/theohbrothers/Log-Rotate/actions/workflows/ci-master-pr.yml) 4 | [![github-release](https://img.shields.io/github/v/release/theohbrothers/Log-Rotate?style=flat-square)](https://github.com/theohbrothers/Log-Rotate/releases/) 5 | [![powershell-gallery-release](https://img.shields.io/powershellgallery/v/Log-Rotate?logo=powershell&logoColor=white&label=PSGallery&labelColor=&style=flat-square)](https://www.powershellgallery.com/packages/Log-Rotate/) 6 | 7 | A replica of the [logrotate utility](https://github.com/logrotate/logrotate "logrotate utility"), except this also runs on Windows systems. 8 | 9 | ## Install 10 | 11 | Open [`powershell`](https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-5.1) or [`pwsh`](https://github.com/powershell/powershell#-powershell) and type: 12 | 13 | ```powershell 14 | Install-Module -Name Log-Rotate -Repository PSGallery -Scope CurrentUser -Verbose 15 | ``` 16 | 17 | If prompted to trust the repository, hit `Y` and `enter`. 18 | 19 | ## Log-Rotate vs `logrotate` 20 | 21 | Log-Rotate is an independent port of `logrotate`. It's made to work exactly the same way as the original `logrotate`, except it works in Powershell and especially Windows. 22 | 23 | - Same command line 24 | - Same config file format, meaning you can re-use your `*nix` configs 25 | - Same rotation logic 26 | - Runs on Powershell or Powershell core. 27 | 28 | Who should use it? 29 | 30 | - Anyone with a `Windows` environment where `docker` is unavailable 31 | - Anyone who misses that `logrotate` on `*nix` 32 | - Anyone working with `Windows` and have trouble with managing tons of log files from various applications 33 | - Anyone who works a lot in `Powershell` automation, and love the fact you can pipe configs into a module. 34 | - Anyone who wants to perform a *one-time rotation*, but doesn't like that `logrotate` only accepts configs as a file and not just a string. 35 | 36 | ## Usage 37 | 38 | ### Windows 39 | 40 | ```powershell 41 | Import-Module Log-Rotate 42 | 43 | # Define your config 44 | # Double-quotes necessary only if there are spaces in the path 45 | $config = @' 46 | "C:\inetpub\logs\access.log" { 47 | rotate 365 48 | size 10M 49 | postrotate 50 | # My shell is powershell 51 | Write-Host "Rotated $( $Args[1] )" 52 | endscript 53 | } 54 | '@ 55 | 56 | # Decide on a Log-Rotate state file that will be created by Log-Rotate 57 | $state = 'C:\var\Log-Rotate\Log-Rotate.status' 58 | 59 | # To check rotation logic without rotating files, use the -WhatIf switch (implies -Verbose) 60 | $config | Log-Rotate -State $state -WhatIf 61 | 62 | # You can either Pipe the config 63 | $config | Log-Rotate -State $state -Verbose 64 | 65 | # Or use the full Command 66 | Log-Rotate -ConfigAsString $config -State $state -Verbose 67 | ``` 68 | 69 | ### *nix 70 | 71 | ```powershell 72 | Import-Module Log-Rotate 73 | 74 | # Define your config 75 | # Double-quotes necessary only if there are spaces in the path 76 | $config = @' 77 | "/var/log/httpd/access.log" { 78 | rotate 365 79 | size 10M 80 | postrotate 81 | # My shell is sh 82 | /usr/bin/killall -HUP httpd 83 | echo "Rotated ${1}" 84 | endscript 85 | } 86 | '@ 87 | 88 | # Decide on a Log-Rotate state file that will be created by Log-Rotate 89 | $state = '/var/lib/Log-Rotate/Log-Rotate.status' 90 | 91 | # To check rotation logic without rotating files, use the -WhatIf switch (implies -Verbose) 92 | $config | Log-Rotate -State $state -WhatIf 93 | 94 | # You can either Pipe the config 95 | $config | Log-Rotate -State $state -Verbose 96 | 97 | # Or use the full Command 98 | Log-Rotate -ConfigAsString $config -State $state -Verbose 99 | ``` 100 | 101 | ## Usage as a Scheduled Task or Cron job 102 | 103 | ### Windows Scheduled Task 104 | 105 | A main config `C:\configs\Log-Rotate\Log-Rotate.conf`: 106 | 107 | ```txt 108 | include C:\configs\Log-Rotate.d\ 109 | ``` 110 | 111 | Config files in `C:\configs\Log-Rotate.d\`: 112 | 113 | ```txt 114 | C:\configs\logrotate.d\ 115 | +-- iis.conf 116 | +-- apache.conf 117 | +-- minecraftserver.conf 118 | ``` 119 | 120 | Decide on a state file `C:\var\Log-Rotate\Log-Rotate.status`. 121 | 122 | Run the command with `-WhatIf` to simulate the rotation, making sure everything is working. 123 | 124 | ```powershell 125 | Import-Module Log-Rotate; Log-Rotate -Config C:\configs\Log-Rotate\Log-Rotate.conf -State C:\var\Log-Rotate\Log-Rotate.status -Verbose -WhatIf 126 | ``` 127 | 128 | Decide on a log file `C:\logs\Log-Rotate.log`. 129 | 130 | Scheduled Task Command line: 131 | 132 | ```powershell 133 | # Powershell 134 | powershell -Command 'Import-Module Log-Rotate; Log-Rotate -Config C:\configs\Log-Rotate\Log-Rotate.conf -State C:\var\Log-Rotate\Log-Rotate.status -Verbose' >> C:\logs\Log-Rotate.log 135 | # pwsh 136 | pwsh -Command 'Import-Module Log-Rotate; Log-Rotate -Config C:\configs\Log-Rotate\Log-Rotate.conf -State C:\var\Log-Rotate\Log-Rotate.status -Verbose' >> C:\logs\Log-Rotate.log 137 | ``` 138 | 139 | #### *nix cron 140 | 141 | A Main config `/etc/Log-Rotate.conf`, with a single `include` line : 142 | 143 | ```txt 144 | include /etc/Log-Rotate.d/ 145 | ``` 146 | 147 | Config files in `/etc/Log-Rotate.d/`: 148 | 149 | ```txt 150 | /etc/Log-Rotate.d/ 151 | +-- nginx.conf 152 | +-- apache.conf 153 | +-- syslog.conf 154 | ``` 155 | 156 | Decide on a state file `/var/lib/Log-Rotate/Log-Rotate.status`. 157 | 158 | Run the command with `-WhatIf` to simulate the rotation, making sure everything is working. 159 | 160 | ```powershell 161 | pwsh -Command 'Import-Module Log-Rotate; Log-Rotate -Config /etc/Log-Rotate.conf -State /var/lib/Log-Rotate/Log-Rotate.status -Verbose -WhatIf' 162 | ``` 163 | 164 | Decide on a log file `/var/log/Log-Rotate.log`. 165 | 166 | Cron command line: 167 | 168 | ```powershell 169 | pwsh -Command 'Import-Module Log-Rotate; Log-Rotate -Config /etc/Log-Rotate.conf -State /var/lib/Log-Rotate/Log-Rotate.status -Verbose' >> /var/log/Log-Rotate.log 170 | ``` 171 | 172 | ## Configuration 173 | 174 | ### State 175 | 176 | If `-State` is unspecified, by default a `Log-Rotate.status` state file is created in the working directory. 177 | 178 | ### Configuration Options 179 | 180 | The following discusses how to use certain config options. 181 | 182 | | Option | Examples | Explanation | 183 | |:--------:|----------|-------------| 184 | | `compresscmd` | `C:\Program Files\7-Zip\7z.exe`, `C:\Program Files\7-Zip\7z`, `7z.exe`, `7z`, `gzip` | Best to use a **full path**. If using aliases, ensure the binary is among the `PATH` environment variable | 185 | | `compressoptions` | `a -t7z`, ` ` | May be blank, in which case no parameters are sent along with`compresscmd` 186 | 187 | ### Missing options 188 | 189 | A few less crucial options are left out for `Log-Rotate v1`. The option and their reasons are stated below: 190 | 191 | | Option | Explanation | 192 | :-------:|------------- 193 | | `mail`, `nomail` | The `mail` option isn't used very much, because the same can be achieved with greater flexibility by adding scripts to any of the following options: `firstaction`, `lastaction`, `prerotate`, `postrotate`, `preremove` . | 194 | | `su` | The main reason for using `su` is to improve security and reduce chances of accidental renames, moves or deletions. Unlike *nix* systems, on Windows, SYSTEM and Adminitrator users cannot `runas` another user without entering their credentials. Unless those credentials are stored in `Credential Manager`, it is impossible for a high privileged daemon to perform rotation operations (E.g. creating, moving, copying, deleting) via an external shell. In the case that the `su` option is ever supported in the future because of the first reason, it would *only* work for `*nix` platforms. The other reason for using `su` is to preserve `ownership` and `Access Control Lists (ACLs)` on rotated files. This however, can easily be achieved by appying `ACLs` on *rotated files' container folders*, so that the any rotated files (E.g. created, moved, renamed) would immediately inherit those attributes. 195 | | `shred`, `noshred`, `shredcycles` | This option is not supported yet, because of external dependencies on Windows - `sdelete`. 196 | | `minage` | unknown reason. 197 | -------------------------------------------------------------------------------- /build/definitions/modulemanifest.ps1: -------------------------------------------------------------------------------- 1 | # - Initial setup: Fill in the GUID value. Generate one by running the command 'New-GUID'. Then fill in all relevant details. 2 | # - Ensure all relevant details are updated prior to publishing each version of the module. 3 | # - To simulate generation of the manifest based on this definition, run the included development entrypoint script Invoke-PSModulePublisher.ps1. 4 | # - To publish the module, tag the associated commit and push the tag. 5 | @{ 6 | RootModule = 'Log-Rotate.psm1' 7 | # ModuleVersion = '' # Value will be set for each publication based on the tag ref. Defaults to '0.0.0' in development environments and regular CI builds 8 | GUID = '44347384-7b42-439e-b835-f8bdcfe0c33c' 9 | Author = 'The Oh Brothers' 10 | CompanyName = 'The Oh Brothers' 11 | Copyright = '(c) 2017 The Oh Brothers' 12 | Description = 'A replica of the logrotate utility, except this also runs on Windows systems.' 13 | PowerShellVersion = '3.0' 14 | # PowerShellHostName = '' 15 | # PowerShellHostVersion = '' 16 | # DotNetFrameworkVersion = '' 17 | # CLRVersion = '' 18 | # ProcessorArchitecture = '' 19 | # RequiredModules = @() 20 | # RequiredAssemblies = @() 21 | # ScriptsToProcess = @() 22 | # TypesToProcess = @() 23 | # FormatsToProcess = @() 24 | # NestedModules = @() 25 | FunctionsToExport = @( 26 | Get-ChildItem $PSScriptRoot/../../src/Log-Rotate/public -Exclude *.Tests.ps1 | % { $_.BaseName } 27 | ) 28 | CmdletsToExport = @() 29 | VariablesToExport = @() 30 | AliasesToExport = @() 31 | # DscResourcesToExport = @() 32 | # ModuleList = @() 33 | # FileList = @() 34 | PrivateData = @{ 35 | # PSData = @{ # Properties within PSData will be correctly added to the manifest via Update-ModuleManifest without the PSData key. Leave the key commented out. 36 | Tags = @( 37 | 'pwsh', 38 | 'powershell', 39 | 'module' 40 | 'logrotate', 41 | 'log', 42 | 'log-administration', 43 | 'log-management', 44 | 'log-rotation', 45 | 'logs' 46 | ) 47 | LicenseUri = 'https://raw.githubusercontent.com/theohbrothers/Log-Rotate/master/LICENSE' 48 | ProjectUri = 'https://github.com/theohbrothers/Log-Rotate' 49 | # IconUri = '' 50 | # ReleaseNotes = '' 51 | # Prerelease = '' 52 | # RequireLicenseAcceptance = $false 53 | # ExternalModuleDependencies = @() 54 | # } 55 | # HelpInfoURI = '' 56 | # DefaultCommandPrefix = '' 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/Log-Rotate/Log-Rotate.Integration.Tests.ps1: -------------------------------------------------------------------------------- 1 | Describe 'Log-Rotate' -Tag 'Integration' { 2 | 3 | BeforeEach { 4 | $drive = Convert-Path 'TestDrive:\' 5 | 6 | $logDir = Join-Path $drive 'logs' 7 | $logOldDir = Join-Path $drive 'oldlogs' 8 | $logFile = Join-Path $logDir 'foo.log' 9 | $logFileContent = 'foo-bar' 10 | 11 | $logDir2 = Join-Path $drive 'logs2' 12 | $logOldDir2 = Join-Path $drive 'oldlogs2' 13 | $logFile2 = Join-Path $logDir2 'foo.log' 14 | $logFile2Content = 'foo-bar' 15 | 16 | $configDir = Join-Path $drive 'config' 17 | $configFile = Join-Path $configDir 'logrotate.conf' 18 | $configFileContent = @" 19 | "$logFile" { 20 | rotate 3 21 | } 22 | "@ 23 | 24 | $configDir2 = Join-Path $drive 'config2' 25 | $configFile2 = Join-Path $configDir2 'logrotate2.conf' 26 | $configFile2Content = @" 27 | "$logFile" { 28 | rotate 3 29 | } 30 | "@ 31 | 32 | $stateDir = Join-Path $drive 'state' 33 | $stateFile = Join-Path $stateDir 'Log-Rotate.status' 34 | 35 | $eaPreference = 'Continue' 36 | 37 | function Init { 38 | New-Item $configDir -ItemType Directory -Force > $null 39 | New-Item $configFile -ItemType File -Force > $null 40 | # Do not write an empty file with BOM in Powershell <= 5 41 | if ($configFileContent) { 42 | $configFileContent | Out-File $configFile -Encoding utf8 -Force -NoNewline 43 | } 44 | 45 | New-Item $configDir2 -ItemType Directory -Force > $null 46 | New-Item $configFile2 -ItemType File -Force > $null 47 | # Do not write an empty file with BOM in Powershell <= 5 48 | if ($configFile2Content) { 49 | $configFile2Content | Out-File $configFile2 -Encoding utf8 -Force -NoNewline 50 | } 51 | 52 | New-Item $logDir -ItemType Directory -Force > $null 53 | New-Item $logOldDir -ItemType Directory -Force > $null 54 | New-Item $logFile -ItemType File -Force > $null 55 | # Do not write an empty file with BOM in Powershell <= 5 56 | if ($logFileContent) { 57 | $logFileContent | Out-File $logFile -Encoding utf8 -Force -NoNewline 58 | } 59 | 60 | New-Item $logDir2 -ItemType Directory -Force > $null 61 | New-Item $logOldDir2 -ItemType Directory -Force > $null 62 | New-Item $logFile2 -ItemType File -Force > $null 63 | if ($logFile2Content) { 64 | $logFile2Content | Out-File $logFile2 -Encoding utf8 -Force -NoNewline 65 | } 66 | 67 | New-Item $stateDir -ItemType Directory -Force > $null 68 | } 69 | 70 | function Cleanup { 71 | Get-Item $logDir -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 72 | Get-Item $logDir2 -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 73 | Get-Item $logOldDir -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 74 | Get-Item $logOldDir2 -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 75 | Get-Item $configDir -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 76 | Get-Item $configDir2 -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 77 | Get-Item $stateDir -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force 78 | } 79 | } 80 | 81 | AfterEach { 82 | Cleanup 83 | } 84 | 85 | Context 'Behavior from flags' { 86 | 87 | BeforeEach { 88 | $eaPreference = 'Stop' 89 | } 90 | 91 | It 'rotates a log file' { 92 | Init 93 | 94 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference 95 | 96 | # Assert that the log file should be gone 97 | Get-Item $logFile -ErrorAction SilentlyContinue | Should -Be $null 98 | 99 | # Assert that the rotated log file should be there 100 | $rotatedLogItems = @( Get-Item $logDir/* ) 101 | $rotatedLogItems.Count | Should -Be 1 102 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 103 | 104 | # Assert that the rotated log file should be named 105 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 106 | } 107 | 108 | It 'rotates a log file when forced' { 109 | Init 110 | 111 | # Rotate once 112 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 113 | 114 | # Recreate the log file again 115 | Init 116 | 117 | # Force another rotation 118 | $force = $true 119 | Log-Rotate -config $configFile -State $stateFile -Force:$force -ErrorAction $eaPreference 3>$null 120 | 121 | # Assert that the log file should be gone 122 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 123 | $logItem | Should -Be $null 124 | 125 | # Assert that the rotated log file(s) should be there 126 | $rotatedLogItems = @( Get-Item $logDir/* ) 127 | $rotatedLogItems.Count | Should -Be 2 128 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 129 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 130 | 131 | # Assert that the newest rotated log file should be named 132 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 133 | # Assert that the oldest rotated log file should be named 134 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).2" 135 | } 136 | 137 | It 'does not rotate a log file in debug mode' { 138 | Init 139 | 140 | $whatif = $true 141 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference -WhatIf:$whatif 3>$null 4>$null 142 | 143 | # Assert that the log file should not be gone 144 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 145 | $logItem | Should -Not -Be $null 146 | } 147 | 148 | It 'does not rotate a log file when forced in debug mode ' { 149 | Init 150 | 151 | $whatif = $true 152 | $force = $true 153 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference -WhatIf:$whatif -Force:$force 3>$null 4>$null 154 | 155 | # Assert that the log file should not be gone 156 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 157 | $logItem | Should -Not -Be $null 158 | } 159 | } 160 | 161 | Context 'Behavior from configuration options' { 162 | 163 | It "Option 'compress': rotates a log file and compresses it" { 164 | $configFileContent = @" 165 | "$logFile" { 166 | compress 167 | compresscmd gzip 168 | compressoptions 169 | compressext .gz 170 | } 171 | "@ 172 | Init 173 | 174 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 175 | 176 | # Assert that the log file should be gone 177 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 178 | $logItem | Should -Be $null 179 | 180 | # Assert that the rotated log file should be there 181 | $rotatedLogItems = @( Get-Item $logDir/* ) 182 | $rotatedLogItems.Count | Should -Be 1 183 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 184 | 185 | # Assert that the rotated log file should be named 186 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1.gz" 187 | } 188 | 189 | It "Option 'compress' with 'compressoptions': rotates a log file and compresses it" { 190 | $configFileContent = @" 191 | "$logFile" { 192 | compress 193 | compresscmd gzip 194 | compressoptions -1 195 | compressext .gz 196 | } 197 | "@ 198 | Init 199 | 200 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 201 | 202 | # Assert that the log file should be gone 203 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 204 | $logItem | Should -Be $null 205 | 206 | # Assert that the rotated log file should be there 207 | $rotatedLogItems = @( Get-Item $logDir/* ) 208 | $rotatedLogItems.Count | Should -Be 1 209 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 210 | 211 | # Assert that the rotated log file should be named 212 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1.gz" 213 | } 214 | 215 | It "Option 'compress' with 'compressext': rotates a log file and compresses it, renaming to a custom extension" { 216 | $configFileContent = @" 217 | "$logFile" { 218 | compress 219 | compresscmd gzip 220 | compressoptions -1 221 | # compressoptions -1 -S .foo # Specify a suffix for gzip (but not compatible with busybox gzip) 222 | compressext .gz 223 | } 224 | "@ 225 | Init 226 | 227 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 228 | 229 | # Assert that the log file should be gone 230 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 231 | $logItem | Should -Be $null 232 | 233 | # Assert that the rotated log file should be there 234 | $rotatedLogItems = @( Get-Item $logDir/* ) 235 | $rotatedLogItems.Count | Should -Be 1 236 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 237 | 238 | # Assert that the rotated log file should be named 239 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1.gz" 240 | } 241 | 242 | It "Option 'copy': rotates a log file as a copy" { 243 | $configFileContent = @" 244 | "$logFile" { 245 | copy 246 | } 247 | "@ 248 | Init 249 | 250 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 251 | 252 | # Assert that the log file should remain 253 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 254 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 255 | $logItem.Name | Should -Be "$( Split-Path $logFile -Leaf )" 256 | 257 | # Assert that the rotated log file should be there 258 | $rotatedLogItems = @( Get-Item $logDir/* ) 259 | $rotatedLogItems.Count | Should -Be 2 260 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 261 | 262 | # Assert that the rotated log file should be named 263 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 264 | 265 | # Assert that the file hashes are the same 266 | $logFileHash = Get-FileHash $logFile -Algorithm md5 267 | $rotatedLogFileHash = Get-FileHash $rotatedLogItems[0].FullName -Algorithm md5 268 | $logFileHash.Hash | Should -Be $rotatedLogFileHash.Hash 269 | } 270 | 271 | It "Option 'copytruncate': rotates a log file as a copy and truncates the original" { 272 | $configFileContent = @" 273 | "$logFile" { 274 | copytruncate 275 | } 276 | "@ 277 | Init 278 | 279 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 280 | 281 | # Assert that the log file should remain 282 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 283 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 284 | $logItem.Name | Should -Be "$( Split-Path $logFile -Leaf )" 285 | $logItem.Length | Should -Be 0 286 | 287 | # Assert that the rotated log file should be there 288 | $rotatedLogItems = @( Get-Item $logDir/* ) 289 | $rotatedLogItems.Count | Should -Be 2 290 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 291 | 292 | # Assert that the rotated log file should be named 293 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 294 | 295 | # Assert that the file hashes are the same 296 | $logFileHash = Get-FileHash $logFile -Algorithm md5 297 | $rotatedLogFileHash = Get-FileHash $rotatedLogItems[1].FullName -Algorithm md5 298 | $logFileHash.Hash | Should -Not -Be $rotatedLogFileHash.Hash 299 | } 300 | 301 | It "Option 'create' (without attributes): rotates a log file and immediately creates a new original file" { 302 | $configFileContent = @" 303 | "$logFile" { 304 | create 305 | } 306 | "@ 307 | Init 308 | 309 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 310 | 311 | # Assert that the log file should remain 312 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 313 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 314 | $logItem.Name | Should -Be "$( Split-Path $logFile -Leaf )" 315 | $logItem.Length | Should -Be 0 316 | 317 | # Assert that the rotated log file should be there 318 | $rotatedLogItems = @( Get-Item $logDir/* ) 319 | $rotatedLogItems.Count | Should -Be 2 320 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 321 | 322 | # Assert that the rotated log file should be named 323 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 324 | } 325 | 326 | It "Option 'create' (with mode, owner, and group attributes): rotates a log file and immediately creates a new original file" { 327 | $configFileContent = @" 328 | "$logFile" { 329 | create 700 1000 1000 330 | } 331 | "@ 332 | Init 333 | 334 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 335 | 336 | # Assert that the log file should remain 337 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 338 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 339 | $logItem.Name | Should -Be "$( Split-Path $logFile -Leaf )" 340 | $logItem.Length | Should -Be 0 341 | 342 | # Assert that the rotated log file should be there 343 | $rotatedLogItems = @( Get-Item $logDir/* ) 344 | $rotatedLogItems.Count | Should -Be 2 345 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 346 | 347 | # Assert that the rotated log file should be named 348 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 349 | } 350 | 351 | It "Option 'daily': rotates a log file only once daily" { 352 | $configFileContent = @" 353 | "$logFile" { 354 | daily 355 | } 356 | "@ 357 | Init 358 | 359 | # Rotate once 360 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 361 | 362 | # Assert that the log file should be gone 363 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 364 | $logItem | Should -Be $null 365 | 366 | # Recreate the log file again 367 | Init 368 | 369 | # Rotate again 370 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 371 | 372 | # Assert that the log file should remain 373 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 374 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 375 | 376 | # Assert that the rotated log file should be there 377 | $rotatedLogItems = @( Get-Item $logDir/* ) 378 | $rotatedLogItems.Count | Should -Be 2 379 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 380 | 381 | # Assert that the rotated log file should be named 382 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 383 | } 384 | 385 | It "Option 'dateext': rotates a log file with a date extension" { 386 | $configFileContent = @" 387 | "$logFile" { 388 | dateext 389 | } 390 | "@ 391 | Init 392 | 393 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 394 | 395 | # Assert that the log file should be gone 396 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 397 | $logItem | Should -Be $null 398 | 399 | # Assert that the rotated log file should be there 400 | $rotatedLogItems = @( Get-Item $logDir/* ) 401 | $rotatedLogItems.Count | Should -Be 1 402 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 403 | 404 | # Assert that the rotated log file should be named 405 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf )$( Get-Date -UFormat '-%Y%m%d' )" 406 | } 407 | 408 | It "Option 'dateext' with 'dateformat': rotates a log file with a date extension with a custom date format" { 409 | $configFileContent = @" 410 | "$logFile" { 411 | dateext 412 | dateformat -%Y%m%d 413 | } 414 | "@ 415 | Init 416 | 417 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 418 | 419 | # Assert that the log file should be gone 420 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 421 | $logItem | Should -Be $null 422 | 423 | # Assert that the rotated log file should be there 424 | $rotatedLogItems = @( Get-Item $logDir/* ) 425 | $rotatedLogItems.Count | Should -Be 1 426 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 427 | 428 | # Assert that the rotated log file should be named 429 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf )$( Get-Date -UFormat '-%Y%m%d' )" 430 | } 431 | 432 | It "Option 'delaycompress': rotates a log file, but delays compressing the newest rotated file" { 433 | $configFileContent = @" 434 | "$logFile" { 435 | compress 436 | compresscmd gzip 437 | compressoptions 438 | compressext .gz 439 | delaycompress 440 | } 441 | "@ 442 | Init 443 | 444 | # Rotate once 445 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 446 | 447 | # Assert that the log file should be gone 448 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 449 | $logItem | Should -Be $null 450 | 451 | # Assert that the rotated log file should be there 452 | $rotatedLogItems = @( Get-Item $logDir/* ) 453 | $rotatedLogItems.Count | Should -Be 1 454 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 455 | 456 | # Assert that the rotated log file should be named 457 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 458 | 459 | # Recreate the log file again 460 | Init 461 | 462 | # Rotate another time 463 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 464 | 465 | # Assert that the log file should be gone 466 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 467 | $logItem | Should -Be $null 468 | 469 | # Assert that the rotated log file(s) should be there 470 | $rotatedLogItems = @( Get-Item $logDir/* ) 471 | $rotatedLogItems.Count | Should -Be 2 472 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 473 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 474 | 475 | # Assert that the newest rotated log file should be named 476 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 477 | # Assert that the oldest rotated log file should be named 478 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).2.gz" 479 | } 480 | 481 | It "Option 'firstaction': rotates a log file with a firstaction script" { 482 | $configFileContent = @" 483 | "$logFile" { 484 | firstaction 485 | echo 'foo' 486 | endscript 487 | } 488 | "@ 489 | Init 490 | 491 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 492 | 493 | # Assert that the log file should be gone 494 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 495 | $logItem | Should -Be $null 496 | 497 | # Assert that the rotated log file should be there 498 | $rotatedLogItems = @( Get-Item $logDir/* ) 499 | $rotatedLogItems.Count | Should -Be 1 500 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 501 | 502 | # Assert that the rotated log file should be named 503 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 504 | 505 | # Expect that the script was run 506 | $result | Should -Be 'foo' 507 | } 508 | 509 | It "Option 'ifempty': rotates a log file even if it is empty" { 510 | $logFileContent = '' # empty 511 | $configFileContent = @" 512 | "$logFile" { 513 | ifempty 514 | } 515 | "@ 516 | Init 517 | 518 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 519 | 520 | # Assert that the log file should be gone 521 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 522 | $logItem | Should -Be $null 523 | 524 | # Assert that the rotated log file should be there 525 | $rotatedLogItems = @( Get-Item $logDir/* ) 526 | $rotatedLogItems.Count | Should -Be 1 527 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 528 | $rotatedLogItems[0].Length | Should -Be 0 529 | 530 | # Assert that the rotated log file should be named 531 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 532 | } 533 | 534 | It "Option 'include': rotates a log file, when 'include' refers to a directory" { 535 | $configFileContent = @" 536 | include $configDir2 537 | "@ 538 | $configFile2Content = @" 539 | "$logFile" { 540 | rotate 3 541 | } 542 | "@ 543 | Init 544 | 545 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 546 | 547 | # Assert that the log file should be gone 548 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 549 | $logItem | Should -Be $null 550 | 551 | # Assert that the rotated log file should be there 552 | $rotatedLogItems = @( Get-Item $logDir/* ) 553 | $rotatedLogItems.Count | Should -Be 1 554 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 555 | 556 | # Assert that the rotated log file should be named 557 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 558 | } 559 | 560 | It "Option 'include': rotates a log file, when 'include' refers to a file" { 561 | $configFileContent = @" 562 | include $configFile2 563 | "@ 564 | $configFile2Content = @" 565 | "$logFile" { 566 | rotate 3 567 | } 568 | "@ 569 | Init 570 | 571 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 572 | 573 | # Assert that the log file should be gone 574 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 575 | $logItem | Should -Be $null 576 | 577 | # Assert that the rotated log file should be there 578 | $rotatedLogItems = @( Get-Item $logDir/* ) 579 | $rotatedLogItems.Count | Should -Be 1 580 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 581 | 582 | # Assert that the rotated log file should be named 583 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 584 | } 585 | 586 | It "Option 'lastaction': rotates a log file with a lastaction script" { 587 | $configFileContent = @" 588 | "$logFile" { 589 | lastaction 590 | echo 'foo' 591 | endscript 592 | } 593 | "@ 594 | Init 595 | 596 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 597 | 598 | # Assert that the log file should be gone 599 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 600 | $logItem | Should -Be $null 601 | 602 | # Assert that the rotated log file should be there 603 | $rotatedLogItems = @( Get-Item $logDir/* ) 604 | $rotatedLogItems.Count | Should -Be 1 605 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 606 | 607 | # Assert that the rotated log file should be named 608 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 609 | 610 | # Expect that the script was run 611 | $result | Should -Be 'foo' 612 | } 613 | 614 | It "Option 'missingok': rotates a log file even when other patterns don't match any log files" { 615 | $nonExistentLogFile = 'foo' 616 | $configFileContent = @" 617 | "$nonExistentLogFile" "$logFile" { 618 | missingok 619 | } 620 | "@ 621 | Init 622 | 623 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 624 | 625 | # Assert that the log file should be gone 626 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 627 | $logItem | Should -Be $null 628 | 629 | # Assert that the rotated log file should be there 630 | $rotatedLogItems = @( Get-Item $logDir/* ) 631 | $rotatedLogItems.Count | Should -Be 1 632 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 633 | 634 | # Assert that the rotated log file should be named 635 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 636 | } 637 | 638 | It "Option 'monthly': rotates a log file only once monthly" { 639 | $configFileContent = @" 640 | "$logFile" { 641 | monthly 642 | } 643 | "@ 644 | Init 645 | 646 | # Rotate once 647 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 648 | 649 | # Assert that the log file should be gone 650 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 651 | $logItem | Should -Be $null 652 | 653 | # Recreate the log file again 654 | Init 655 | 656 | # Rotate again 657 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 658 | 659 | # Assert that the log file should remain 660 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 661 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 662 | 663 | # Assert that the rotated log file should be there 664 | $rotatedLogItems = @( Get-Item $logDir/* ) 665 | $rotatedLogItems.Count | Should -Be 2 666 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 667 | 668 | # Assert that the rotated log file should be named 669 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 670 | } 671 | 672 | It "Option 'nocopy': rotate a log file, but not as a copy" { 673 | $configFileContent = @" 674 | copy 675 | "$logFile" { 676 | nocopy 677 | } 678 | "@ 679 | Init 680 | 681 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 682 | 683 | # Assert that the log file should be gone 684 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 685 | $logItem | Should -Be $null 686 | 687 | # Assert that there should be no rotated files 688 | $rotatedLogItems = @( Get-Item $logDir/* ) 689 | $rotatedLogItems.Count | Should -Be 1 690 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 691 | } 692 | 693 | It "Option 'nocopytruncate': rotate a log file, but not as a copy to be truncated" { 694 | $configFileContent = @" 695 | copytruncate 696 | "$logFile" { 697 | nocopytruncate 698 | } 699 | "@ 700 | Init 701 | 702 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 703 | 704 | # Assert that the log file should remain 705 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 706 | $logItem | Should -Be $null 707 | 708 | # Assert that the rotated log file should be there 709 | $rotatedLogItems = @( Get-Item $logDir/* ) 710 | $rotatedLogItems.Count | Should -Be 1 711 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 712 | 713 | # Assert that the rotated log file should be named 714 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 715 | } 716 | 717 | It "Option 'nocreate': rotate a log file, but do not create a new a log file" { 718 | $configFileContent = @" 719 | create 720 | "$logFile" { 721 | nocreate 722 | } 723 | "@ 724 | Init 725 | 726 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 727 | 728 | # Assert that the log file should be gone 729 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 730 | $logItem | Should -Be $null 731 | 732 | # Assert that there should be no rotated files 733 | $rotatedLogItems = @( Get-Item $logDir/* ) 734 | $rotatedLogItems.Count | Should -Be 1 735 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 736 | } 737 | 738 | It "Option 'nodateext': rotates a log file without a date extension" { 739 | $configFileContent = @" 740 | dateext 741 | "$logFile" { 742 | nodateext 743 | } 744 | "@ 745 | Init 746 | 747 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 748 | 749 | # Assert that the log file should be gone 750 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 751 | $logItem | Should -Be $null 752 | 753 | # Assert that the rotated log file should be there 754 | $rotatedLogItems = @( Get-Item $logDir/* ) 755 | $rotatedLogItems.Count | Should -Be 1 756 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 757 | 758 | # Assert that the rotated log file should be named 759 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 760 | } 761 | 762 | It "Option 'nodelaycompress': rotates a log file, but does not delay compressing the newest rotated file" { 763 | $configFileContent = @" 764 | delaycompress 765 | "$logFile" { 766 | compress 767 | compresscmd gzip 768 | compressoptions 769 | compressext .gz 770 | nodelaycompress 771 | } 772 | "@ 773 | Init 774 | 775 | # Rotate once 776 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 777 | 778 | # Assert that the log file should be gone 779 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 780 | $logItem | Should -Be $null 781 | 782 | # Assert that the rotated log file should be there 783 | $rotatedLogItems = @( Get-Item $logDir/* ) 784 | $rotatedLogItems.Count | Should -Be 1 785 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 786 | 787 | # Assert that the rotated log file should be named 788 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1.gz" 789 | 790 | # Recreate the log file again 791 | Init 792 | 793 | # Rotate another time 794 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 795 | 796 | # Assert that the log file should be gone 797 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 798 | $logItem | Should -Be $null 799 | 800 | # Assert that the rotated log file(s) should be there 801 | $rotatedLogItems = @( Get-Item $logDir/* ) 802 | $rotatedLogItems.Count | Should -Be 2 803 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 804 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 805 | 806 | # Assert that the newest rotated log file should be named 807 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1.gz" 808 | # Assert that the oldest rotated log file should be named 809 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).2.gz" 810 | } 811 | 812 | It "Option 'nomissingok': rotate files, while issuing an error (warning) for pattern that don't match any log files" { 813 | $nonExistentLogFile = 'bar' 814 | $configFileContent = @" 815 | missingok 816 | "$nonExistentLogFile" "$logFile" { 817 | nomissingok 818 | } 819 | "@ 820 | Init 821 | 822 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference -ErrorVariable err #-Verbose 823 | 824 | # Assert that the log file should be gone 825 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 826 | $logItem | Should -Be $null 827 | 828 | # Assert that the rotated log file should be there 829 | $rotatedLogItems = @( Get-Item $logDir/* ) 830 | $rotatedLogItems.Count | Should -Be 1 831 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 832 | 833 | # Assert that the rotated log file should be named 834 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 835 | } 836 | 837 | It "Option 'noolddir': rotates a log file, but not into an olddir" { 838 | $configFileContent = @" 839 | olddir $logOldDir 840 | "$logFile" { 841 | noolddir 842 | } 843 | "@ 844 | Init 845 | 846 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 847 | 848 | # Assert that the log file should be gone 849 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 850 | $logItem | Should -Be $null 851 | 852 | # Assert that the rotated log file should be there 853 | $rotatedLogItems = @( Get-Item $logDir/* ) 854 | $rotatedLogItems.Count | Should -Be 1 855 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 856 | 857 | # Assert that the rotated log file should be named 858 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 859 | } 860 | 861 | It "Option 'nosharedscripts': rotates two log files, running a shared script only once" { 862 | $configFileContent = @" 863 | sharedscripts 864 | "$logFile" "$logFile2" { 865 | prerotate 866 | echo 'foo' 867 | endscript 868 | postrotate 869 | echo 'bar' 870 | endscript 871 | nosharedscripts 872 | } 873 | "@ 874 | Init 875 | 876 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 877 | $result.Count | Should -Be 4 878 | $result[0] | Should -Be 'foo' 879 | $result[1] | Should -Be 'bar' 880 | $result[2] | Should -Be 'foo' 881 | $result[3] | Should -Be 'bar' 882 | 883 | # Assert that the log file should be gone 884 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 885 | $logItem | Should -Be $null 886 | 887 | # Assert that the log file should be gone 888 | $logItem2 = Get-Item $logFile2 -ErrorAction SilentlyContinue 889 | $logItem2 | Should -Be $null 890 | 891 | # Assert that the rotated log file should be there 892 | $rotatedLogItems = @( Get-Item $logDir/* ) 893 | $rotatedLogItems.Count | Should -Be 1 894 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 895 | 896 | # Assert that the rotated log file should be named 897 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 898 | 899 | # Assert that the rotated log file should be there 900 | $rotatedLogItems2 = @( Get-Item $logDir2/* ) 901 | $rotatedLogItems2.Count | Should -Be 1 902 | $rotatedLogItems2[0] | Should -BeOfType [System.IO.FileSystemInfo] 903 | 904 | # Assert that the rotated log file should be named 905 | $rotatedLogItems2[0].Name | Should -Be "$( Split-Path $logFile2 -Leaf ).1" 906 | } 907 | 908 | It "Option 'notifempty': do not rotates a log file if it is empty" { 909 | $logFileContent = '' # empty 910 | $configFileContent = @" 911 | ifempty 912 | "$logFile" { 913 | notifempty 914 | } 915 | "@ 916 | Init 917 | 918 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 919 | 920 | # Assert that the log file should be gone 921 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 922 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 923 | 924 | # Assert that there should be no rotated files 925 | $rotatedLogItems = @( Get-Item $logDir/* ) 926 | $rotatedLogItems.Count | Should -Be 1 927 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 928 | $rotatedLogItems[0].Length | Should -Be 0 929 | } 930 | 931 | It "Option 'olddir': rotates a log file into an olddir" { 932 | $configFileContent = @" 933 | "$logFile" { 934 | olddir $logOldDir 935 | } 936 | "@ 937 | Init 938 | 939 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 940 | 941 | # Assert that the log file should be gone 942 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 943 | $logItem | Should -Be $null 944 | 945 | # Assert that the rotated log file should be there 946 | $rotatedLogItems = @( Get-Item $logOldDir/* ) 947 | $rotatedLogItems.Count | Should -Be 1 948 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 949 | 950 | # Assert that the rotated log file should be named 951 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 952 | } 953 | 954 | It "Option 'postrotate': rotates a log file with a postrotate script" { 955 | $configFileContent = @" 956 | "$logFile" { 957 | postrotate 958 | echo 'foo' 959 | endscript 960 | } 961 | "@ 962 | Init 963 | 964 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 965 | 966 | # Assert that the log file should be gone 967 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 968 | $logItem | Should -Be $null 969 | 970 | # Assert that the rotated log file should be there 971 | $rotatedLogItems = @( Get-Item $logDir/* ) 972 | $rotatedLogItems.Count | Should -Be 1 973 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 974 | 975 | # Assert that the rotated log file should be named 976 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 977 | 978 | # Expect that the script was run 979 | $result | Should -Be 'foo' 980 | } 981 | 982 | It "Option 'preremove': rotates a log file with a preremove script" { 983 | $configFileContent = @" 984 | "$logFile" { 985 | rotate 1 986 | preremove 987 | echo 'foo' 988 | endscript 989 | } 990 | "@ 991 | Init 992 | 993 | # Rotate once 994 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 995 | 996 | # Recreate the log file again 997 | Init 998 | 999 | # Rotate again 1000 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1001 | 1002 | # Assert that the log file should be gone 1003 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1004 | $logItem | Should -Be $null 1005 | 1006 | # Assert that the rotated log file should be there 1007 | $rotatedLogItems = @( Get-Item $logDir/* ) 1008 | $rotatedLogItems.Count | Should -Be 1 1009 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1010 | 1011 | # Assert that the rotated log file should be named 1012 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1013 | 1014 | # Expect that the script was run 1015 | $result | Should -Be 'foo' 1016 | } 1017 | 1018 | It "Option 'prerotate': rotates a log file with a prerotate script" { 1019 | $configFileContent = @" 1020 | "$logFile" { 1021 | prerotate 1022 | echo 'foo' 1023 | endscript 1024 | } 1025 | "@ 1026 | Init 1027 | 1028 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1029 | 1030 | # Assert that the log file should be gone 1031 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1032 | $logItem | Should -Be $null 1033 | 1034 | # Assert that the rotated log file should be there 1035 | $rotatedLogItems = @( Get-Item $logDir/* ) 1036 | $rotatedLogItems.Count | Should -Be 1 1037 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1038 | 1039 | # Assert that the rotated log file should be named 1040 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1041 | 1042 | # Expect that the script was run 1043 | $result | Should -Be 'foo' 1044 | } 1045 | 1046 | It "Option 'rotate': rotates a log file, keeping only a certain number of old files" { 1047 | $configFileContent = @" 1048 | "$logFile" { 1049 | rotate 2 1050 | } 1051 | "@ 1052 | Init 1053 | 1054 | # Rotate once 1055 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1056 | 1057 | # Assert that the log file should be gone 1058 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1059 | $logItem | Should -Be $null 1060 | 1061 | # Recreate the log file again 1062 | Init 1063 | 1064 | # Rotate again 1065 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1066 | 1067 | # Assert that the log file should be gone 1068 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1069 | $logItem | Should -Be $null 1070 | 1071 | # Recreate the log file again 1072 | Init 1073 | 1074 | # Rotate again 1075 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1076 | 1077 | # Assert that the log file should be gone 1078 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1079 | $logItem | Should -Be $null 1080 | 1081 | # Assert that the rotated log file should be there 1082 | $rotatedLogItems = @( Get-Item $logDir/* ) 1083 | $rotatedLogItems.Count | Should -Be 2 1084 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1085 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 1086 | 1087 | # Assert that the newest rotated log file should be named 1088 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1089 | # Assert that the oldest rotated log file should be named 1090 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).2" 1091 | } 1092 | 1093 | It "Option 'sharedscripts': rotates two log files, running a shared script only once" { 1094 | $configFileContent = @" 1095 | "$logFile" "$logFile2" { 1096 | sharedscripts 1097 | prerotate 1098 | echo 'foo' 1099 | endscript 1100 | postrotate 1101 | echo 'bar' 1102 | endscript 1103 | } 1104 | "@ 1105 | Init 1106 | 1107 | $result = Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1108 | $result.Count | Should -Be 2 1109 | $result[0] | Should -Be 'foo' 1110 | $result[1] | Should -Be 'bar' 1111 | 1112 | # Assert that the log file should be gone 1113 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1114 | $logItem | Should -Be $null 1115 | 1116 | # Assert that the log file should be gone 1117 | $logItem2 = Get-Item $logFile2 -ErrorAction SilentlyContinue 1118 | $logItem2 | Should -Be $null 1119 | 1120 | # Assert that the rotated log file should be there 1121 | $rotatedLogItems = @( Get-Item $logDir/* ) 1122 | $rotatedLogItems.Count | Should -Be 1 1123 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1124 | 1125 | # Assert that the rotated log file should be named 1126 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1127 | 1128 | # Assert that the rotated log file should be there 1129 | $rotatedLogItems2 = @( Get-Item $logDir2/* ) 1130 | $rotatedLogItems2.Count | Should -Be 1 1131 | $rotatedLogItems2[0] | Should -BeOfType [System.IO.FileSystemInfo] 1132 | 1133 | # Assert that the rotated log file should be named 1134 | $rotatedLogItems2[0].Name | Should -Be "$( Split-Path $logFile2 -Leaf ).1" 1135 | } 1136 | 1137 | It "Option 'size': rotates a log file larger than specified by 'size'" { 1138 | $configFileContent = @" 1139 | "$logFile" { 1140 | size 1 1141 | } 1142 | "@ 1143 | Init 1144 | 1145 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1146 | 1147 | # Assert that the log file should be gone 1148 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1149 | $logItem | Should -Be $null 1150 | 1151 | # Assert that the rotated log file should be there 1152 | $rotatedLogItems = @( Get-Item $logDir/* ) 1153 | $rotatedLogItems.Count | Should -Be 1 1154 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1155 | 1156 | # Assert that the rotated log file should be named 1157 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1158 | } 1159 | 1160 | It "Option 'start': rotates a log file, with an numbered extension" { 1161 | $configFileContent = @" 1162 | "$logFile" { 1163 | start 100 1164 | } 1165 | "@ 1166 | Init 1167 | 1168 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1169 | 1170 | # Assert that the log file should be gone 1171 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1172 | $logItem | Should -Be $null 1173 | 1174 | # Assert that the rotated log file should be there 1175 | $rotatedLogItems = @( Get-Item $logDir/* ) 1176 | $rotatedLogItems.Count | Should -Be 1 1177 | $rotatedLogItems[0] | Should -BeOfType [System.IO.FileSystemInfo] 1178 | 1179 | # Assert that the rotated log file should be named 1180 | $rotatedLogItems[0].Name | Should -Be "$( Split-Path $logFile -Leaf ).100" 1181 | } 1182 | 1183 | It "Option 'weekly': rotates a log file only once weekly" { 1184 | $configFileContent = @" 1185 | "$logFile" { 1186 | weekly 1187 | } 1188 | "@ 1189 | Init 1190 | 1191 | # Rotate once 1192 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1193 | 1194 | # Assert that the log file should be gone 1195 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1196 | $logItem | Should -Be $null 1197 | 1198 | # Recreate the log file again 1199 | Init 1200 | 1201 | # Rotate again 1202 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1203 | 1204 | # Assert that the log file should remain 1205 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1206 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 1207 | 1208 | # Assert that the rotated log file should be there 1209 | $rotatedLogItems = @( Get-Item $logDir/* ) 1210 | $rotatedLogItems.Count | Should -Be 2 1211 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 1212 | 1213 | # Assert that the rotated log file should be named 1214 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1215 | } 1216 | 1217 | It "Option 'yearly': rotates a log file only once yearly" { 1218 | $configFileContent = @" 1219 | "$logFile" { 1220 | yearly 1221 | } 1222 | "@ 1223 | Init 1224 | 1225 | # Rotate once 1226 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1227 | 1228 | # Assert that the log file should be gone 1229 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1230 | $logItem | Should -Be $null 1231 | 1232 | # Recreate the log file again 1233 | Init 1234 | 1235 | # Rotate again 1236 | Log-Rotate -config $configFile -State $stateFile -ErrorAction $eaPreference #-Verbose 1237 | 1238 | # Assert that the log file should remain 1239 | $logItem = Get-Item $logFile -ErrorAction SilentlyContinue 1240 | $logItem | Should -BeOfType [System.IO.FileSystemInfo] 1241 | 1242 | # Assert that the rotated log file should be there 1243 | $rotatedLogItems = @( Get-Item $logDir/* ) 1244 | $rotatedLogItems.Count | Should -Be 2 1245 | $rotatedLogItems[1] | Should -BeOfType [System.IO.FileSystemInfo] 1246 | 1247 | # Assert that the rotated log file should be named 1248 | $rotatedLogItems[1].Name | Should -Be "$( Split-Path $logFile -Leaf ).1" 1249 | } 1250 | } 1251 | } 1252 | -------------------------------------------------------------------------------- /src/Log-Rotate/Log-Rotate.psd1: -------------------------------------------------------------------------------- 1 | # 2 | # Module manifest for module 'Log-Rotate' 3 | # 4 | # Generated by: The Oh Brothers 5 | # 6 | # Generated on: 09/04/2023 7 | # 8 | 9 | @{ 10 | 11 | # Script module or binary module file associated with this manifest. 12 | RootModule = 'Log-Rotate.psm1' 13 | 14 | # Version number of this module. 15 | ModuleVersion = '0.0.0' 16 | 17 | # Supported PSEditions 18 | # CompatiblePSEditions = @() 19 | 20 | # ID used to uniquely identify this module 21 | GUID = '44347384-7b42-439e-b835-f8bdcfe0c33c' 22 | 23 | # Author of this module 24 | Author = 'The Oh Brothers' 25 | 26 | # Company or vendor of this module 27 | CompanyName = 'The Oh Brothers' 28 | 29 | # Copyright statement for this module 30 | Copyright = '(c) 2017 The Oh Brothers' 31 | 32 | # Description of the functionality provided by this module 33 | Description = 'A replica of the logrotate utility, except this also runs on Windows systems.' 34 | 35 | # Minimum version of the PowerShell engine required by this module 36 | PowerShellVersion = '3.0' 37 | 38 | # Name of the PowerShell host required by this module 39 | # PowerShellHostName = '' 40 | 41 | # Minimum version of the PowerShell host required by this module 42 | # PowerShellHostVersion = '' 43 | 44 | # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 45 | # DotNetFrameworkVersion = '' 46 | 47 | # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. 48 | # ClrVersion = '' 49 | 50 | # Processor architecture (None, X86, Amd64) required by this module 51 | # ProcessorArchitecture = '' 52 | 53 | # Modules that must be imported into the global environment prior to importing this module 54 | # RequiredModules = @() 55 | 56 | # Assemblies that must be loaded prior to importing this module 57 | # RequiredAssemblies = @() 58 | 59 | # Script files (.ps1) that are run in the caller's environment prior to importing this module. 60 | # ScriptsToProcess = @() 61 | 62 | # Type files (.ps1xml) to be loaded when importing this module 63 | # TypesToProcess = @() 64 | 65 | # Format files (.ps1xml) to be loaded when importing this module 66 | # FormatsToProcess = @() 67 | 68 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess 69 | # NestedModules = @() 70 | 71 | # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. 72 | FunctionsToExport = 'Log-Rotate' 73 | 74 | # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. 75 | CmdletsToExport = @() 76 | 77 | # Variables to export from this module 78 | # VariablesToExport = @() 79 | 80 | # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. 81 | AliasesToExport = @() 82 | 83 | # DSC resources to export from this module 84 | # DscResourcesToExport = @() 85 | 86 | # List of all modules packaged with this module 87 | # ModuleList = @() 88 | 89 | # List of all files packaged with this module 90 | # FileList = @() 91 | 92 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. 93 | PrivateData = @{ 94 | 95 | PSData = @{ 96 | 97 | # Tags applied to this module. These help with module discovery in online galleries. 98 | Tags = 'pwsh','powershell','module','logrotate','log','log-administration','log-management','log-rotation','logs' 99 | 100 | # A URL to the license for this module. 101 | LicenseUri = 'https://raw.githubusercontent.com/theohbrothers/Log-Rotate/master/LICENSE' 102 | 103 | # A URL to the main website for this project. 104 | ProjectUri = 'https://github.com/theohbrothers/Log-Rotate' 105 | 106 | # A URL to an icon representing this module. 107 | # IconUri = '' 108 | 109 | # ReleaseNotes of this module 110 | # ReleaseNotes = '' 111 | 112 | # Prerelease string of this module 113 | # Prerelease = '' 114 | 115 | # Flag to indicate whether the module requires explicit user acceptance for install/update/save 116 | # RequireLicenseAcceptance = $false 117 | 118 | # External dependent modules of this module 119 | # ExternalModuleDependencies = @() 120 | 121 | } # End of PSData hashtable 122 | 123 | } # End of PrivateData hashtable 124 | 125 | # HelpInfo URI of this module 126 | # HelpInfoURI = '' 127 | 128 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. 129 | # DefaultCommandPrefix = '' 130 | 131 | } 132 | 133 | -------------------------------------------------------------------------------- /src/Log-Rotate/Log-Rotate.psm1: -------------------------------------------------------------------------------- 1 | $MODULE_BASE_DIR = Split-Path $MyInvocation.MyCommand.Path -Parent 2 | 3 | Get-ChildItem "$MODULE_BASE_DIR/classes/*.ps1" -exclude *.Tests.ps1 | % { 4 | . $_.FullName 5 | } 6 | 7 | Get-ChildItem "$MODULE_BASE_DIR/helpers/*.ps1" -exclude *.Tests.ps1 | % { 8 | . $_.FullName 9 | } 10 | 11 | Get-ChildItem "$MODULE_BASE_DIR/private/" -recurse | ? { $_.Extension -eq '.ps1' -and $_.Name -notlike '*.Tests.ps1' } | % { 12 | . $_.FullName 13 | } 14 | 15 | Get-ChildItem "$MODULE_BASE_DIR/public/*.ps1" -exclude *.Tests.ps1 | % { 16 | . $_.FullName 17 | } 18 | 19 | Export-ModuleMember -Function Log-Rotate 20 | -------------------------------------------------------------------------------- /src/Log-Rotate/classes/New-BlockFactory.ps1: -------------------------------------------------------------------------------- 1 | function New-BlockFactory { 2 | ####################### 3 | # BlockFactory Class # 4 | ####################### 5 | # BlockFactory is a stateful factory that constructs Block Objects, a Configuration. It keeps a list of Blocks. 6 | $BlockFactory = [PSCustomObject]@{ 7 | 'Constants' = [scriptblock]{ 8 | # Constants 9 | $g_globaloptions_allowed_str = 'compress,compresscmd,uncompresscmd,compressext,compressoptions,uncompressoptions,copy,copytruncate,create,daily,dateext,dateformat,delaycompress,extension,ifempty,mail,mailfirst,maillast,maxage,minsize,missingok,monthly,nocompress,nocopy,nocopytruncate,nocreate,nodelaycompress,nodateext,nomail,nomissing,noolddir,nosharedscripts,noshred,notifempty,olddir,rotate,size,sharedscripts,shred,shredcycle,start,tabooext,weekly,yearly' 10 | $g_options_not_singleline_str = 'postrotate,prerotate,firstaction,lastaction,preremove'; 11 | $g_options_not_switches_str = 'compresscmd,uncompresscmd,compressext,compressoptions,uncompressoptions,create,dateformat,extension,include,mail,maxage,minsize,olddir,postrotate,prerotate,firstaction,lastaction,preremove,rotate,size,shredcycle,start,tabooext' 12 | 13 | # Constants as arrays 14 | [string[]]$g_globaloptions_allowed = $g_globaloptions_allowed_str.Split(',') 15 | [string[]]$g_options_not_singleline = $g_options_not_singleline_str.Split(','); 16 | [string[]]$g_localoptions_allowed = $g_globaloptions_allowed + $g_options_not_singleline 17 | [string[]]$g_options_not_switches = $g_options_not_switches_str.Split(',') 18 | 19 | # Define our config-capturing regexes 20 | [Regex]$g_localconfigs_regex = '([^\n]*)({(?:(?:(firstaction|lastaction|prerotate|postrotate|preremove)(?:\s|.)*?endscript)|[^}])*})' 21 | [Regex]$g_globaloptions_allowed_regex = "(?:^|\n)[^\S\n]*\b($( ($g_globaloptions_allowed -join '|') ))\b(.*)" 22 | [Regex]$g_localoptions_allowed_regex = "\n[^\S\n]*(?:\b($( ($g_globaloptions_allowed -join '|') ))\b(.*)|\b(postrotate|prerotate|firstaction|lastaction|preremove)[^\n]*\n((?:.|\s)*?)\n.*\b(endscript)\b)" 23 | [hashtable]$g_no_yes = @{ 24 | 'nocompress' = 'compress' 25 | 'nocopy' = 'copy' 26 | 'nocopytruncate' = 'copytruncate' 27 | 'nocreate' = 'create' 28 | 'nodelaycompress' = 'delaycompress' 29 | 'nodateext' = 'dateext' 30 | 'nomail' = 'mail' 31 | 'nomissingok' = 'missingok' 32 | 'notifempty' = 'ifempty' 33 | 'noolddir' = 'olddir' 34 | 'nosharedscripts' = 'sharedscripts' 35 | 'noshred' = 'shred' 36 | } 37 | #[Regex]$globalconfig_regex = ' 'D:\mycwd\Log-Rotate.status' 87 | # E.g. 'D:\mycwd\.\Log-Rotate.status' -> 'D:\mycwd\Log-Rotate.status' 88 | # E.g. 'D:\mycwd\..\Log-Rotate.status' -> 'D:\Log-Rotate.status' 89 | # E.g. 'D:\mycwd\..\test\Log-Rotate.status' -> 'D:\test\Log-Rotate.status' 90 | $path = Join-Path -Path $PWD.Path -ChildPath $statusfile_path 91 | $this.StatusFile_FullName = [System.IO.Path]::GetFullPath( $path ) 92 | }else { 93 | # An absolute path was provided. Standardize the slashes to platform-specific slashes ([IO.Path]::DirectorySeparatorChar) 94 | $this.StatusFile_FullName = [System.IO.Path]::GetFullPath( $statusfile_path ) 95 | } 96 | } 97 | Write-Verbose "new status file created: $( $this.StatusFile_FullName )" 98 | } 99 | #> 100 | }catch { 101 | Write-Error "STATUSFILE: WARNING: Status file $statusfile_path could not be created" -ErrorAction Continue 102 | throw 103 | } 104 | } 105 | } 106 | 107 | # Parse and store previous rotation status 108 | if ($status) { 109 | $lines = $status.split("`n") 110 | 111 | # The first line must be a Log-Rotate state file title, if not we might be dealing with another file. 112 | if ( $lines[0] -notmatch 'Log\-Rotate state' ) { 113 | throw "Log-Rotate state file $( $this.StatusFile_FullName ) is of the wrong format. Check that you are not overriding another file. If you are not, delete the file and try again." 114 | } 115 | 116 | $lines.Trim() | Where-Object { $_ } | ForEach-Object { 117 | $matches = [Regex]::Matches($_, '"([^"]+)" (.+)') 118 | if ($matches.success) { 119 | $path = $matches.Groups[1].Value 120 | $lastRotateDate = $matches.Groups[2].Value 121 | if (Test-Path $path -PathType Leaf) { 122 | try { 123 | $lastRotateDatetime = Get-Date -Date $lastRotateDate -Format 's' -ErrorAction SilentlyContinue 124 | $this.Status[$path] = $lastRotateDatetime 125 | }catch {} 126 | } 127 | } 128 | } 129 | } 130 | 131 | # Always test for write permissions on the status file 132 | try { 133 | '' | Out-File $this.StatusFile_FullName -Append -Force 134 | if (!$status -and $WhatIf) { 135 | # We're running Log-Rotate the first time in debug mode. 136 | Remove-Item $this.StatusFile_FullName 137 | } 138 | }catch { 139 | Write-Error "STATUSFILE: WARNING: Insufficient write permissions for status file $( $this.StatusFile_FullName ). Resolve this error before continuing." -ErrorAction Continue 140 | throw 141 | } 142 | } 143 | $LogFactory | Add-Member -Name 'Create' -MemberType ScriptMethod -Value { 144 | param ([System.IO.FileInfo]$logfile, [hashtable]$options) 145 | 146 | function Get-Status([System.IO.FileInfo]$file) { 147 | $lastRotationDate = if ($this.Status.ContainsKey($file.FullName)) { 148 | $this.Status[$file.FullName] 149 | }else { 150 | '' 151 | } 152 | [string]$lastRotationDate 153 | } 154 | 155 | $lastRotationDate = Get-Status $logfile 156 | $_logObject = $LogObject.New($logfile, $options, $lastRotationDate) 157 | if ($_logObject) { 158 | $this.LogObjects.Add($_logObject) | Out-Null 159 | return $_logObject 160 | } 161 | $null 162 | } 163 | $LogFactory | Add-Member -Name 'GetAll' -MemberType ScriptMethod -Value { 164 | return $this.LogObjects 165 | } 166 | $LogFactory | Add-Member -Name 'DumpStatus' -MemberType ScriptMethod -Value { 167 | 168 | try { 169 | if (!$WhatIf) { 170 | # Update my state with each logs rotation status 171 | $this.GetAll() | Where-Object { $_.Status['rotation_datetime'] } | ForEach-Object { 172 | $rotationDateISO = $_.Status['rotation_datetime'].ToString('s') 173 | $lastRotationDateISO = if ($this.Status.ContainsKey($_.Logfile.FullName)) { 174 | $this.Status[$_.Logfile.FullName] 175 | } else { 176 | '' 177 | } 178 | if ( !$lastRotationDateISO -or ($rotationDateISO -gt $lastRotationDateISO) ) { 179 | Write-Verbose "Updating status of rotation for log $($_.Logfile.FullName) " 180 | $this.Status[$_.Logfile.FullName] = $rotationDateISO 181 | }else { 182 | Write-Verbose "Not updating status of rotation for log $($_.Logfile.FullName) " 183 | } 184 | } 185 | 186 | # Dump state file 187 | Write-Verbose "Writing status file to $($this.StatusFile_FullName)" 188 | $output = "Log-Rotate state - version $LogRotateVersion" 189 | $this.Status.Keys | ForEach-Object { 190 | $output += "`n`"$_`" $($this.Status[$_])" 191 | } 192 | $output | Out-File $this.StatusFile_FullName -Encoding utf8 193 | }else { 194 | # Dump state file 195 | Write-Verbose "Writing status file to $($this.StatusFile_FullName)" 196 | } 197 | }catch { 198 | Write-Error "Failed to write state file." -ErrorAction Continue 199 | throw 200 | } 201 | } 202 | 203 | $LogFactory 204 | } 205 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Extend-Class.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Extend-Class" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Extend-Class.ps1: -------------------------------------------------------------------------------- 1 | # Class Helper - Unused for now 2 | function Extend-Class { 3 | param ($classObject, [PSModuleInfo]$importedModule) 4 | 5 | $importedModule.ExportedFunctions.Keys | ForEach-Object { 6 | Write-Verbose "Key: $_" 7 | Write-Verbose "Function: $((Get-item function:$_).Definition)" 8 | $scriptblock = [Scriptblock]::Create( (Get-item function:$_).Definition ) 9 | $classObject | Add-Member -Name $_ -MemberType ScriptMethod -Value $scriptblock 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Get-Exception-Message.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Get-Exception-Message" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Get-Exception-Message.ps1: -------------------------------------------------------------------------------- 1 | function Get-Exception-Message ($ErrorRecord) { 2 | # Recurses to get the innermost exception message 3 | function Get-InnerExceptionMessage ($Exception) { 4 | if ($Exception.InnerException) { 5 | Get-InnerExceptionMessage $Exception.InnerException 6 | }else { 7 | $Exception.Message 8 | } 9 | } 10 | $Message = Get-InnerExceptionMessage $ErrorRecord.Exception 11 | if ($WhatIf) { 12 | $Message = $Message + "`nStacktrace:`n" + $ErrorRecord.Exception.ErrorRecord.ScriptStackTrace 13 | } 14 | $Message 15 | } 16 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Get-Size-Bytes.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Get-Size-Bytes" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Get-Size-Bytes.ps1: -------------------------------------------------------------------------------- 1 | function Get-Size-Bytes { 2 | # Returns a size specified with a unit (E.g. 100, 100k, 100M, 100G) into bytes without a unit 3 | param ( 4 | [string]$size_str 5 | ) 6 | if (!$size_str) { 7 | $size_str = '0' 8 | } 9 | 10 | if ($size_str -match '(?:[0-9]+|[0-9]+(?:k|M|G))$') { 11 | $size_unit = $size_str -replace '[0-9]+' 12 | [int64]$size = $size_str -replace $size_unit 13 | switch($size_unit) { 14 | "" { $size = $size } 15 | "k" { $size = $size * 1024 } 16 | "M" { $size = $size * 1024 * 1024 } 17 | "G" { $size = $size * 1024 * 1024 * 1024 } 18 | } 19 | }else { 20 | #Write-Error "The size specified was '$size_str'. Size should be specified in quantity and unit, e.g. '100k', or '100M'. Only units 'k', 'M', or 'G' are allowed." -ErrorAction Stop 21 | throw "The size specified was '$size_str'. Size should be specified in quantity and unit, e.g. '100k', or '100M'. Only units 'k', 'M', or 'G' are allowed." 22 | #Write-Error -Exception (New-Object Exception "The size specified was '$size_str'. Size should be specified in quantity and unit, e.g. '100k', or '100M'. Only units 'k', 'M', or 'G' are allowed.") -ErrorAction Stop 23 | } 24 | $size 25 | } 26 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Start-Script.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Start-Script" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/Start-Script.ps1: -------------------------------------------------------------------------------- 1 | function Start-Script { 2 | [CmdletBinding()] 3 | param ( 4 | [AllowNull()] 5 | [string]$script, 6 | [string]$file_FullName 7 | ) 8 | 9 | begin { 10 | # Save the caller's ErrorAction 11 | $callerEA = $ErrorActionPreference 12 | $ErrorActionPreference = 'Stop' 13 | } 14 | 15 | process { 16 | try { 17 | Write-Verbose "Running script with arg $file_FullName : `n$script" 18 | $OS = $ENV:OS 19 | if (!$WhatIf) { 20 | if ($OS -eq "Windows_NT") { 21 | # E.g. & Powershell -Command { echo $Args[0] } -Args @('D:/console.log') 22 | 23 | # & operator: When we use & $cmd $param, powershell wraps args containing spaces with double-quotes, so we need escape inner double-quotes 24 | $cmd = if ( Get-Command 'powershell' -ErrorAction SilentlyContinue ) { 25 | "powershell" 26 | }elseif ( Get-Command 'pwsh' -ErrorAction SilentlyContinue ) { 27 | "pwsh" 28 | } 29 | $scriptblock = [scriptblock]::Create($script) 30 | #$params = '-Command', $scriptblock, '-Args', @($file_FullName) 31 | $output = & $cmd -Command $scriptblock -Args @('logrotate_script', $file_FullName) 32 | }else { 33 | # E.g. sh -c 'echo ${0}' 'D:\console.log' 34 | 35 | # & operator: When we use & $cmd $param, powershell wraps args containing spaces with double-quotes, so we need escape inner double-quotes 36 | $cmd = 'sh' 37 | $params = '-c', $script.Replace('"', '\"'), 'logrotate_script', $file_FullName 38 | $output = & $cmd $params 39 | 40 | # TODO: Not using jobs for now, because they are slow. 41 | #$script = "sh -c '$script' `$args[0]" 42 | } 43 | 44 | Write-Verbose "Script output: `n$output" 45 | 46 | # Done. Send output down the pipeline. If not, send the success of the script down the pipeline 47 | if ( $LASTEXITCODE ) { 48 | Write-Verbose "Script exited with exit code: $LASTEXITCODE" 49 | throw "Script failed with errors." 50 | } 51 | $output 52 | 53 | # TODO: Not using jobs for now, because they are slow. 54 | <# 55 | $scriptblock = [Scriptblock]::Create($script) 56 | $output = & $scriptblock $file_FullName 57 | $job = Start-Job -ScriptBlock $scriptblock -ArgumentList $file_FullName -ErrorAction Stop 58 | $output = Receive-Job -Job $job -Wait -ErrorAction Stop 59 | if ($job.State -eq 'Failed') { 60 | throw 61 | }else { 62 | Write-Verbose "Script output: `n$output" 63 | } 64 | #> 65 | } 66 | }catch { 67 | throw "Failed to execute script for $file_FullName. `nError: $_ `nScript (possibly with errors): $script" 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/likeIn.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "likeIn" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/helpers/likeIn.ps1: -------------------------------------------------------------------------------- 1 | function likeIn ([string]$string, [string[]]$wildcardblobs) { 2 | foreach ($wildcardblob in $wildcardblobs) { 3 | if ($string -like $wildcardblob) { 4 | return $true 5 | } 6 | } 7 | $false 8 | } 9 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/config/Compile-Full-Config.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Compile-FullConfig" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/config/Compile-Full-Config.ps1: -------------------------------------------------------------------------------- 1 | function Compile-Full-Config { 2 | param ([string]$MultipleConfig) 3 | 4 | [Scriptblock]$matchEvaluator = { 5 | param ($match) 6 | 7 | $include_path = $match.Groups[1].Value.Trim() 8 | # Check if it's a file or directory 9 | if ($include_path -and (Test-Path $include_path)) { 10 | $item = Get-Item $include_path 11 | 12 | if (Test-Path $item.FullName -PathType Container) { 13 | # It's a directory. Include content of all files inside it 14 | $content = "" 15 | Get-ChildItem $item | ForEach-Object { 16 | Write-Verbose "CONFIG: Including file $($item.FullName)" 17 | Write-Verbose "CONFIG: Reading file $($item.FullName)" 18 | $content += Get-Content $_.FullName -Raw 19 | } 20 | }else { 21 | # It's a single file. Include its content 22 | Write-Verbose "CONFIG: Including file $($item.FullName)" 23 | Write-Verbose "CONFIG: Reading file $($item.FullName)" 24 | $content = Get-Content $include_path -Raw 25 | } 26 | }else { 27 | Write-Verbose "CONFIG: Ignoring included path $include_path because it is invalid." 28 | } 29 | 30 | # Return the replacement value 31 | if ($content) { 32 | "`n$content" 33 | } 34 | } 35 | 36 | # Remove all comments (i.e. starting with '#') 37 | [Regex]$remove_comments_regex = '#.*' 38 | $MultipleConfig = $remove_comments_regex.Replace($MultipleConfig, '') 39 | 40 | # Remove all within-block 'include' directives 41 | [Regex]$include_regex = '({[^}]*?)(include[^\n]*)([^}]*})' 42 | $MultipleConfig = $include_regex.Replace($MultipleConfig, '$1$3') 43 | 44 | # Insert all 'include' directives' paths' content 45 | [Regex]$include_regex = '\s*include([^\n]*)' 46 | $MultipleConfig = $include_regex.Replace($MultipleConfig, $matchEvaluator) 47 | 48 | # Remove all comments (i.e. starting with '#') 49 | [Regex]$remove_comments_regex = '#.*' 50 | $MultipleConfig = $remove_comments_regex.Replace($MultipleConfig, '') 51 | 52 | # Return compiled config 53 | $MultipleConfig 54 | } 55 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/config/Validate-Full-Config.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Validate-FullConfig" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/config/Validate-Full-Config.ps1: -------------------------------------------------------------------------------- 1 | function Validate-Full-Config { 2 | param ([string]$FullConfig) 3 | 4 | function Get-LinesAround([string[]]$lines, [int]$line_number) { 5 | $start = 0 6 | $around = 10 7 | $end = $lines.count - 1 8 | 9 | if ( ($line_number -le $around) ) { 10 | $dumpstart = $start 11 | }else { 12 | $dumpstart = $line_number - $around 13 | } 14 | 15 | if ( ($line_number -ge ($end - $around)) ) { 16 | $dumpend = $end 17 | }else { 18 | $dumpend = $line_number + $around 19 | } 20 | 21 | $dump = [System.Collections.ArrayList]@() 22 | foreach ($i in ($dumpstart..$dumpend) ) { 23 | if ( ($i -eq $line_number ) -or ($i -eq ($line_number - 1)) ) { 24 | $dump.Add("NEAR HERE -------->") | Out-Null 25 | } 26 | $dump.Add($lines[$i]) | Out-Null 27 | } 28 | $dump 29 | } 30 | 31 | # Ignore firstaction,lastaction,prerotate,postrotate,preremove endscripts' content. This is adapted from $g_localoptions_allowed_regex. 32 | [Regex]$scripts_content_regex = '\n[^\S\n]*\b(?:postrotate|prerotate|firstaction|lastaction|preremove)[^\n]*\n((?:.|\s)*?)\n.*\b(endscript)\b' 33 | $FullConfig = $scripts_content_regex.Replace($FullConfig, '') 34 | 35 | # Validate block path pattern definition. And find matching bracer. 36 | $lines = $FullConfig.split("`n") 37 | $line_number = 0 38 | $bracer_to_find = '{' 39 | $bracer_left_count = 0 40 | $bracer_right_count = 0 41 | $last_bracer_line = 0 42 | foreach ($line in $lines) { 43 | $line_number++ 44 | $level = 0 45 | 46 | 47 | # Validate block definition 48 | [Regex]$block_path_pattern_line = "(.*)({)" 49 | $matches = $block_path_pattern_line.Matches($line) 50 | if ($matches.success) { 51 | # The path pattern cannot be empty 52 | $path_pattern = $matches.Groups[1].Value.Trim() 53 | if (!$path_pattern) { 54 | $dump = Get-LinesAround $lines $line_number | Out-String 55 | throw "CONFIG: WARNING: Empty path pattern disallowed allowed at line $line_number, marked by NEAR HERE --------> : `n$dump" 56 | } 57 | } 58 | 59 | [Regex]$bracers_regex = "([{}])" 60 | $matches = $bracers_regex.Matches($line) 61 | if ($matches.success) { 62 | # No multiple bracers on the same line 63 | if ($matches.Count -gt 1) { 64 | $dump = Get-LinesAround $lines $line_number | Out-String 65 | throw "CONFIG: WARNING: Multiple bracers disallowed allowed at line $line_number, marked by NEAR HERE --------> : `n$dump" 66 | } 67 | 68 | $bracer_found = $matches.Groups[1].Value 69 | 70 | if ($bracer_found -ne $bracer_to_find) { 71 | $problem_line = if ($bracer_to_find -eq '}') { $last_bracer_line } else { $line_number } 72 | $dump = Get-LinesAround $lines $line_number | Out-String 73 | throw "CONFIG: ERROR: Stay bracer '$bracer_found' at line $problem_line, marked by NEAR HERE --------> : `n$dump" 74 | } 75 | if ($bracer_found -eq '{') { 76 | $bracer_left_count++ 77 | $bracer_to_find = '}' 78 | }else { 79 | $bracer_right_count++ 80 | $bracer_to_find = '{' 81 | } 82 | 83 | $last_bracer_line = $line_number 84 | } 85 | } 86 | if ($bracer_left_count -ne $bracer_right_count) { 87 | $dump = Get-LinesAround $lines $line_number | Out-String 88 | throw "CONFIG: ERROR: Non-matching bracer found at line $line_number, near : `n$dump" 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/rotate/Process-Local-Block.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Process-Local-Block" { 6 | It "does something useful" { 7 | $true | Should -Be $false 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Log-Rotate/private/rotate/Process-Local-Block.ps1: -------------------------------------------------------------------------------- 1 | function Process-Local-Block { 2 | # Validates options for the block, and instantiates any Log Objects. 3 | [CmdletBinding()] 4 | param ( 5 | # The Block object 6 | [Parameter(Mandatory=$True)] 7 | [object]$block, 8 | 9 | # Block Options 10 | [switch]$compress, 11 | [string]$compresscmd, 12 | [string]$uncompresscmd, 13 | [string]$compressext, 14 | [string]$compressoptions, 15 | [string]$uncompressoptions, 16 | [switch]$copy, 17 | [switch]$copytruncate, 18 | [string]$create, 19 | [switch]$daily, 20 | [switch]$delaycompress, 21 | [switch]$dateext, 22 | [string]$dateformat, 23 | [string]$extension, 24 | [switch]$ifempty, 25 | [string]$include, 26 | [string]$mail , 27 | [switch]$mailfirst , 28 | [switch]$maillast , 29 | [string]$maxage , 30 | [string]$minsize , 31 | [switch]$missingok , 32 | [switch]$monthly, 33 | [switch]$nocompress, 34 | [switch]$nocopy, 35 | [switch]$nocopytruncate, 36 | [switch]$nocreate, 37 | [switch]$nodelaycompress, 38 | [switch]$nodateext, 39 | [switch]$nomail, 40 | [switch]$nomissingok, 41 | [switch]$noolddir, 42 | [switch]$nosharedscripts, 43 | [switch]$noshred, 44 | [switch]$notifempty, 45 | [string]$olddir, 46 | [string]$postrotate, 47 | [string]$prerotate, 48 | [string]$firstaction, 49 | [string]$lastaction, 50 | [string]$preremove, 51 | [int]$rotate, 52 | [string]$size, 53 | [switch]$sharedscripts, 54 | [switch]$shred, 55 | [switch]$shredcycle, 56 | [int]$start, 57 | [string]$tabooext, 58 | [switch]$weekly, 59 | [switch]$yearly, 60 | 61 | [switch]$force 62 | ) 63 | 64 | # Validates options for a block 65 | begin 66 | { 67 | # Unpack this block's properties 68 | $blockpath = $block.Path 69 | $logfiles = $block.Logfiles 70 | 71 | # $PSBoundParameters automatic variable is a hashtable containing all bound parameters (keys) and their arguments(values). These are our options. 72 | $options = $PSBoundParameters 73 | 74 | # Override options where overrides exist in this local block 75 | 76 | # Don't do any of the following if we defined so 77 | $options['compress'] = if ($nocompress) { $false } else { $compress } 78 | $options['copy'] = & { 79 | if ($nocopy) { 80 | return $false 81 | } 82 | if ($copy) { 83 | return $true 84 | } 85 | if ($nocopytruncate) { 86 | return $false 87 | } 88 | if ($copytruncate) { 89 | return $true 90 | } 91 | $copy 92 | } 93 | $options['copytruncate'] = if ($nocopytruncate) { $false } else { $copytruncate } 94 | 95 | $options['create'] = if ($nocreate) { '' } else { 96 | # 'create' option's attributes are optional, in which case its value is an empty string 97 | if ($PSBoundParameters.ContainsKey('create') -and $PSBoundParameters['create'] -eq '') { 98 | ' ' # Set to a non-empty string 99 | }else { 100 | $create 101 | } 102 | } 103 | $options['delaycompress'] = if ($nodelaycompress) { $false } else { $delaycompress } 104 | $options['dateext'] = if ($nodateext) { $false } else { $dateext } 105 | $options['mail'] = if ($nomail) { $false } else { $mail } 106 | $options['missingok'] = if ($nomissingok) { $false } else { $missingok } 107 | $options['ifempty'] = if ($notifempty) { $false } else { $ifempty } 108 | $options['olddir'] = if ($noolddir) { '' } else { $olddir } 109 | $options['sharedscripts'] = if ($nosharedscripts) { $false } else { $sharedscripts } 110 | $options['shred'] = if ($noshred) { $false } else { $shred } 111 | 112 | # Compress extension 113 | $options['compressext'] = if ($options['compress']) { 114 | if ($compressext) { 115 | # Use the specified compression file extension 116 | $compressext 117 | }else { 118 | # Try and guess the compression file extension to use 119 | if ($compresscmd -match '7za?') { 120 | '.7z' 121 | }elseif ($compresscmd -match 'gzip') { 122 | '.gz' 123 | } 124 | } 125 | }else { 126 | '' 127 | } 128 | # Validate that the compress command exists 129 | if ($compress -and !$nocompress) { 130 | try { 131 | Get-Command $compresscmd -ErrorAction Stop | Out-Null 132 | }catch { 133 | Write-Error "Skipping log pattern $blockpath because of an invalid compress command '$compresscmd'. " -ErrorAction Continue 134 | throw 135 | } 136 | } 137 | # Validate dateformat if using dateext 138 | # Exit here, if invalid! 139 | if ($dateext) { 140 | if ($dateformat.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -ne -1) { 141 | Write-Error "Skipping log pattern $blockpath because there are invalid characters in option 'dateext'." -ErrorAction Stop 142 | } 143 | } 144 | 145 | # Validate / redefine size 146 | # Exit here, if invalid! 147 | if ($size) { 148 | try { 149 | $_size_bytes = Get-Size-Bytes $size 150 | if ($_size_bytes) { 151 | $options['size'] = $_size_bytes 152 | } else { 153 | Write-Error "Skipping log pattern $blockpath because size cannot be 0." -ErrorAction Stop 154 | } 155 | }catch { 156 | Write-Error "Skipping log pattern $blockpath because of an invalid 'size' option. " -ErrorAction Continue 157 | throw 158 | } 159 | } 160 | 161 | if ($minsize) { 162 | try { 163 | $_minsize_bytes = Get-Size-Bytes $minsize 164 | if ($_minsize_bytes) { 165 | $options['minsize'] = $_minsize_bytes 166 | }else { 167 | Write-Error "Skipping log pattern $blockpath because minsize cannot be 0." -ErrorAction Stop 168 | } 169 | }catch { 170 | Write-Error "Skipping log pattern $blockpath because of an invalid 'minsize' option. " -ErrorAction Continue 171 | throw 172 | } 173 | } 174 | } 175 | 176 | # Constructs Log Objects for log files determined to be rotated. Rotates those logs. 177 | process 178 | { 179 | #try { 180 | # Status Messages 181 | if ($force) { 182 | $_force_msg = "forced from command line" 183 | } 184 | Write-Verbose "Rotating pattern: $blockpath $(Get-Size-Bytes $size) bytes $_force_msg ($rotate rotations)" 185 | $_msg = '' 186 | if ($olddir) { 187 | $_msg += "olddir is $olddir" 188 | } 189 | if (!$ifempty) { 190 | if ($_msg) { $_msg += ', ' } 191 | $_msg += "empty log files are not rotated" 192 | } 193 | 194 | if ($_msg) { $_msg += ', ' } 195 | if ($mail -and ($mailfirst -or $maillast)) { 196 | $_msg += "old logs are mailed to $mail" 197 | }else { 198 | $_msg += "old logs are removed." 199 | } 200 | Write-Verbose $_msg 201 | 202 | if ($logfiles.Count) { 203 | # Get an array of Log Objects of to-be-rotated log files. 204 | $_logsToRotate = New-Object System.Collections.ArrayList 205 | foreach ($logfile in $logfiles) { 206 | Write-Verbose "Considering log $($logfile.FullName)" 207 | try { 208 | $_logObject = $LogFactory.Create($logfile, $options) 209 | if ($_logObject) { 210 | $_logsToRotate.Add($_logObject) | Out-Null 211 | Write-Verbose " log needs rotating" 212 | }else { 213 | Write-Verbose " log does not need rotating." 214 | } 215 | }catch { 216 | Write-Error "Skipping over processing log $($logfile.FullName)." -ErrorAction Continue 217 | } 218 | } 219 | 220 | # These Log Objects should be rotated. Rotate them. 221 | if ($_logsToRotate.Count -gt 0) { 222 | # Run any firstaction/endscript 223 | if ($firstaction) { 224 | try { 225 | # Script output will go down the pipeline 226 | Write-Verbose "Running firstaction script" 227 | Start-Script $firstaction $blockpath -ErrorAction $CallerEA 228 | }catch { 229 | Write-Error "Failed to run firstaction script for $blockpath." -ErrorAction Continue 230 | } 231 | } 232 | 233 | # For sharedscripts, prerotate and postrotate scripts are run once, immediately before and after all of this block's logs are rotated. 234 | # For nosharedscripts, prerotate and postrotate scripts run for each log, immediately before and after it is rotated. 235 | if ($options['sharedscripts']) { 236 | # Do PrePrerotate 237 | $_logsToRotate | ForEach-Object { 238 | try { 239 | # Script output will go down the pipeline 240 | $log = $_ 241 | $log.PrePrerotate() 242 | }catch { 243 | Write-Error "Failed to rotate log $($log['logfile'].FullName)." -ErrorAction Continue 244 | } 245 | } 246 | 247 | # Run any prerotate/endscript, only if using sharedscripts 248 | if ( $prerotate -and ($false -notin $_logsToRotate.status.preprerotate) ) { 249 | try { 250 | # Script output will go down the pipeline 251 | Write-Verbose "Running shared prerotate script" 252 | Start-Script $prerotate $blockpath -ErrorAction $CallerEA 253 | }catch { 254 | Write-Error "Failed to run shared prerotate script for $blockpath. " -ErrorAction Continue 255 | } 256 | } 257 | 258 | # It's time to rotate each of these Log Objects 259 | $_logsToRotate | Where-Object { $_.status.preprerotate -eq $true } | ForEach-Object { 260 | try { 261 | # Script output will go down the pipeline 262 | $log = $_ 263 | $log.RotateMainOnly() 264 | }catch { 265 | Write-Error "Failed to rotate log $($log['logfile'].FullName)." -ErrorAction Continue 266 | } 267 | } 268 | 269 | # Run any postrotate/endscript, only if using sharedscripts 270 | if ( $postrotate -and ($false -notin $_logsToRotate.status.rotate) ) { 271 | try { 272 | Write-Verbose "Running shared postrotate script" 273 | # Script output will go down the pipeline 274 | Start-Script $postrotate $blockpath -ErrorAction $CallerEA 275 | }catch { 276 | Write-Error "Failed to run shared postrotate script for $blockpath. " -ErrorAction Continue 277 | } 278 | } 279 | 280 | # Do PostPostRotate 281 | $_logsToRotate | Where-Object { $_.status.preprerotate -eq $true -and $_.status.rotate -eq $true } | ForEach-Object { 282 | try { 283 | # Script output will go down the pipeline 284 | $log = $_ 285 | $log.PostPostRotate() 286 | }catch { 287 | Write-Error "Failed to rotate log $($log['logfile'].FullName)." -ErrorAction Continue 288 | } 289 | } 290 | }else { 291 | $_logsToRotate | ForEach-Object { 292 | # For each log to rotate: move step-by-step but dont continue if a step is unsuccessful. 293 | try { 294 | # Script output will go down the pipeline 295 | $_.PrePrerotate() 296 | if ( $_.status.preprerotate -and $prerotate ) { $_.Prerotate() } 297 | if ( ! $prerotate -or ( $prerotate -and $_.status.prerotate ) ) { $_.RotateMainOnly() } 298 | if ( $_.status.rotate -and $postrotate ) { $_.Postrotate() } 299 | if ( ! $postrotate -or ( $postrotate -and $_.status.postrotate ) ) { $_.PostPostRotate() } 300 | }catch { 301 | Write-Error -ErrorRecord $_ -ErrorAction Continue 302 | } 303 | } 304 | } 305 | 306 | # Run any lastaction/endscript 307 | if ($lastaction) { 308 | try { 309 | # Script output will go down the pipeline 310 | Write-Verbose "Running lastaction script" -ErrorAction Stop 311 | Start-Script $lastaction $blockpath -ErrorAction $CallerEA 312 | }catch { 313 | Write-Error "Failed to run lastaction script for $blockpath. " -ErrorAction Continue 314 | } 315 | } 316 | }else { 317 | if ($WhatIf) { 318 | Write-Verbose "Not running first action script, since no logs will be rotated" 319 | Write-Verbose "Not running prerotate script, since no logs will be rotated" 320 | Write-Verbose "Not running postrotate script, since no logs will be rotated" 321 | Write-Verbose "Not running last action script, since no logs will be rotated" 322 | } 323 | } 324 | }else { 325 | Write-Verbose "Did not find any logs for path $logpath" 326 | } 327 | #}catch { 328 | # Write-Error $_.Exception.Message -ErrorAction Stop 329 | #} 330 | 331 | } 332 | end { 333 | } 334 | } 335 | -------------------------------------------------------------------------------- /src/Log-Rotate/public/Log-Rotate.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' 3 | . "$here\$sut" 4 | 5 | Describe "Log-Rotate" -Tag 'Unit' { 6 | $initScriptblock = { 7 | $configFile = 'foo' 8 | 9 | Mock Test-Path { $true } 10 | Mock Test-Path -ParameterFilter { $Path -eq 'foo' -and !$PathType } { $true } 11 | Mock Get-Item { [pscustomobject]@{ FullName = 'foo' } } 12 | Mock Test-Path -ParameterFilter { $Path -eq 'foo' -and $PathType } { $false } 13 | Mock Get-ChildItem {} 14 | Mock Get-Content {} 15 | function Compile-Full-Config {} 16 | Mock Compile-Full-Config {} 17 | function Validate-Full-Config {} 18 | Mock Validate-Full-Config {} 19 | 20 | function New-BlockFactory {} 21 | Mock New-BlockFactory { 22 | $BlockFactory = [PSCustomObject]@{} 23 | $BlockFactory | Add-Member -Name 'Create' -MemberType ScriptMethod -Value {} 24 | $BlockFactory | Add-Member -Name 'GetAll' -MemberType ScriptMethod -Value { 25 | @{ 26 | '/path/to/foo/bar/' = @{ 27 | 'LogFiles' = @() 28 | 'Options' = @() 29 | } 30 | } 31 | } 32 | $BlockFactory 33 | } 34 | function New-LogFactory {} 35 | Mock New-LogFactory { 36 | $LogFactory = [PSCustomObject]@{} 37 | $LogFactory | Add-Member -Name 'InitStatus' -MemberType ScriptMethod -Value {} 38 | $LogFactory | Add-Member -Name 'DumpStatus' -MemberType ScriptMethod -Value {} 39 | $LogFactory 40 | } 41 | function New-LogObject {} 42 | Mock New-LogObject {} 43 | function Process-Local-Block {} 44 | Mock Process-Local-Block {} 45 | 46 | } 47 | 48 | 49 | Context 'Invalid parameters (Non-Terminating)' { 50 | 51 | $ErrorActionPreference = 'Continue' 52 | 53 | It 'errors when config is null' { 54 | $invalidConfig = $null 55 | 56 | $err = Log-Rotate -Config $invalidConfig -ErrorVariable err 2>&1 57 | $err | ? { $_ -is [System.Management.Automation.ErrorRecord] } | % { $_.Exception.Message } | Should -Contain "No config file(s) specified." 58 | } 59 | 60 | It 'errors when config is an non-existing file' { 61 | $invalidConfig = 'foo' 62 | Mock Test-Path { $false } 63 | 64 | $err = Log-Rotate -Config $invalidConfig 2>&1 65 | $err | ? { $_ -is [System.Management.Automation.ErrorRecord] } | % { $_.Exception.Message } | Should -Contain "Invalid config path specified: $invalidConfig" 66 | } 67 | 68 | It 'errors when configAsString is null' { 69 | $invalidConfigAsString = $null 70 | 71 | $err = Log-Rotate -ConfigAsString $invalidConfigAsString 2>&1 72 | $err | ? { $_ -is [System.Management.Automation.ErrorRecord] } | % { $_.Exception.Message } | Should -Contain "No config file(s) specified." 73 | } 74 | } 75 | 76 | Context 'Invalid parameters (Terminating)' { 77 | 78 | $ErrorActionPreference = 'Stop' 79 | 80 | It 'errors when config is null' { 81 | $invalidConfig = $null 82 | 83 | { Log-Rotate -Config $invalidConfig 2>$null } | Should -Throw "No config file(s) specified." 84 | } 85 | 86 | It 'errors when config is an non-existing file' { 87 | $invalidConfig = 'foo' 88 | Mock Test-Path { $false } 89 | 6 90 | { Log-Rotate -Config $invalidConfig 2>$null } | Should -Throw "Invalid config path specified: $invalidConfig" 91 | } 92 | 93 | It 'errors when configAsString is null' { 94 | $invalidConfigAsString = $null 95 | 96 | { Log-Rotate -ConfigAsString $invalidConfigAsString 2>$null } | Should -Throw "No config file(s) specified." 97 | } 98 | } 99 | 100 | Context 'Functionality' { 101 | 102 | $ErrorActionPreference = 'Stop' 103 | 104 | It 'shows the help' { 105 | $help = Log-Rotate -Help 106 | 107 | $help | Should -Not -Be $null 108 | } 109 | 110 | It 'compiles configuration from one config file' { 111 | . $initScriptBlock 112 | Mock Compile-Full-Config {} 113 | 114 | Log-Rotate -config $configFile 115 | 116 | Assert-MockCalled Compile-Full-Config -Times 1 117 | } 118 | 119 | It 'compiles configuration from multiple config files' { 120 | . $initScriptBlock 121 | Mock Test-Path -ParameterFilter { $Path -eq 'foo' -and $PathType } { $false } 122 | Mock Compile-Full-Config {} 123 | 124 | Log-Rotate -config $configFile 125 | 126 | Assert-MockCalled Compile-Full-Config -Times 1 127 | } 128 | 129 | It 'validates configuration' { 130 | . $initScriptBlock 131 | Mock Validate-Full-Config {} 132 | 133 | Log-Rotate -config $configFile 134 | 135 | Assert-MockCalled Validate-Full-Config -Times 1 136 | } 137 | 138 | It 'instantiates singleton BlockFactory' { 139 | . $initScriptBlock 140 | Mock New-BlockFactory { 141 | $BlockFactory = [PSCustomObject]@{} 142 | $BlockFactory | Add-Member -Name 'Create' -MemberType ScriptMethod -Value {} 143 | $BlockFactory | Add-Member -Name 'GetAll' -MemberType ScriptMethod -Value { 144 | @{ 145 | '/path/to/foo/bar/' = @{ 146 | 'LogFiles' = @() 147 | 'Options' = @() 148 | } 149 | } 150 | } 151 | $BlockFactory 152 | } 153 | 154 | Log-Rotate -config $configFile 155 | 156 | Assert-MockCalled New-BlockFactory -Times 1 157 | } 158 | 159 | It 'instantiates singleton LogFactory' { 160 | . $initScriptBlock 161 | 162 | Log-Rotate -config $configFile 163 | 164 | Assert-MockCalled New-LogFactory -Times 1 165 | } 166 | 167 | It 'instantiates singleton LogObject' { 168 | . $initScriptBlock 169 | 170 | Log-Rotate -config $configFile 171 | 172 | Assert-MockCalled New-LogObject -Times 1 173 | } 174 | 175 | It 'creates block objects from configuration' { 176 | . $initScriptBlock 177 | Mock New-BlockFactory { 178 | $BlockFactory = [PSCustomObject]@{} 179 | $BlockFactory | Add-Member -Name 'Create' -MemberType ScriptMethod -Value { 180 | 'create' 181 | } 182 | $BlockFactory | Add-Member -Name 'GetAll' -MemberType ScriptMethod -Value { 183 | @{ 184 | '/path/to/foo/bar/' = @{ 185 | 'LogFiles' = @() 186 | 'Options' = @() 187 | } 188 | } 189 | } 190 | $BlockFactory 191 | } 192 | 193 | $result = Log-Rotate -config $configFile 194 | 195 | $result | Should -Be 'create' 196 | } 197 | 198 | It 'initializes the rotation state file' { 199 | . $initScriptBlock 200 | Mock New-LogFactory { 201 | $LogFactory = [PSCustomObject]@{} 202 | $LogFactory | Add-Member -Name 'InitStatus' -MemberType ScriptMethod -Value { 203 | 'initstatus' 204 | } 205 | $LogFactory | Add-Member -Name 'DumpStatus' -MemberType ScriptMethod -Value {} 206 | $LogFactory 207 | } 208 | 209 | $result = Log-Rotate -config $configFile 210 | 211 | $result | Should -Be 'initstatus' 212 | } 213 | 214 | It 'processes a block configuration' { 215 | . $initScriptBlock 216 | 217 | Log-Rotate -config $configFile 218 | 219 | Assert-MockCalled Process-Local-Block -Times 1 220 | } 221 | 222 | It 'dumps the rotation state file' { 223 | . $initScriptBlock 224 | 225 | Mock New-LogFactory { 226 | $LogFactory = [PSCustomObject]@{} 227 | $LogFactory | Add-Member -Name 'InitStatus' -MemberType ScriptMethod -Value {} 228 | $LogFactory | Add-Member -Name 'DumpStatus' -MemberType ScriptMethod -Value { 229 | 'dumpstatus' 230 | } 231 | $LogFactory 232 | } 233 | 234 | $result = Log-Rotate -config $configFile 235 | 236 | $result | Should -Be 'dumpstatus' 237 | } 238 | 239 | It 'Throws no exception only when specified' { 240 | . $initScriptBlock 241 | Mock Process-Local-Block { 242 | Write-Error 'foo' -ErrorAction Continue 243 | } 244 | 245 | # Expect no exception 246 | $err = Log-Rotate -config $configFile -ErrorAction Continue 2>&1 247 | $err | ? { $_ -is [System.Management.Automation.ErrorRecord] } | % { $_.Exception.Message } | Should -Be 'foo' 248 | } 249 | 250 | It 'Throws exception only when specified' { 251 | . $initScriptBlock 252 | Mock Process-Local-Block { 253 | Write-Error 'foo' -ErrorAction Stop 254 | } 255 | 256 | # Expect exception 257 | { Log-Rotate -config $configFile -ErrorAction Stop } | Should -Throw 'foo' 258 | } 259 | 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /src/Log-Rotate/public/Log-Rotate.ps1: -------------------------------------------------------------------------------- 1 | # Log-Rotate Cmdlet 2 | function Log-Rotate { 3 | <# 4 | .SYNOPSIS 5 | A replica of the logrotate utility, except this also runs on Windows systems. 6 | 7 | .DESCRIPTION 8 | The functionality of Log-Rotate was ported from the original logrotate. 9 | It is made to work in the exact way logrotate would work: Same rotation logic, same outputs, same configurations. 10 | Best of all, it works on one more platform: Windows. 11 | 12 | .PARAMETER Config 13 | The path to the Log-Rotate config file, or the path to a directory containing config files. If a directory is given, all files will be read as config files. 14 | Any number of config file paths can be given. 15 | Later config files will override earlier ones. 16 | The best method is to use a single config file that includes other config files by using the 'include' directive. 17 | 18 | .PARAMETER ConfigAsString 19 | The configuration as a string, accepting input from the pipeline. Especially useful when you don't want to use a separate config file. 20 | 21 | .PARAMETER Debug 22 | In debug mode, no logs are rotated. Use this to validate your configs or observe rotation logic. 23 | 24 | .PARAMETER Force 25 | Forces Log-Rotate to perform a rotation for all Logs, even when Log-Rotate deems particular Log(s) to not require rotation. 26 | 27 | .PARAMETER Help 28 | Prints Help information. 29 | 30 | .PARAMETER Mail 31 | Tells logrotate which command to use when mailing logs. 32 | 33 | .PARAMETER State 34 | The path to a Log-Rotate state file to use for previously rotated Logs. May be absolute or relative. 35 | If no state file is provided, by default the location of the state file (named 'Log-Rotate.state') will be in the calling script's directory. If there is no calling script, the location of the state file will be in the current working directory. 36 | If a relative path is provided, the state file path will be resolved to the current working directory. 37 | If a tilde ('~') is used at the beginning of the path, the state file path will be resolved to the user's home directory. 38 | 39 | .PARAMETER Usage 40 | Prints Usage information 41 | 42 | .EXAMPLE 43 | Log-Rotate -ConfigAsString $configAsString -State $state -Verbose 44 | 45 | .EXAMPLE 46 | Log-Rotate -Config "/etc/Log-Rotate.conf" -State "/var/lib/Log-Rotate/Log-Rotate.status" -Verbose 47 | 48 | .EXAMPLE 49 | Log-Rotate -Config "/etc/configs/" -Verbose 50 | 51 | .LINK 52 | https://github.com/theohbrothers/Log-Rotate 53 | 54 | .NOTES 55 | *logrotate manual: https://linux.die.net/man/8/logrotate 56 | 57 | The command line is identical to the actual logrotate utility, if parameter aliases are used. If using full parameters, only optional (-mail, -state) and miscellaneous (-usage, -help) parameters use one instead of two dashes. (i.e. -mail instead of --mail) 58 | For help on command line options, use: 59 | Get-Help Log-Rotate -detailed 60 | 61 | Configuration file(s) should follow the same format and options used by the actual logrotate utility. 62 | See the logrotate manual* for configuration options. 63 | 64 | Because logrotate is constantly being updated, the present utility may not be up to par with it. But it won't be too hard or too long for new features to be integrated. 65 | #> 66 | [CmdletBinding()] 67 | param ( 68 | [Parameter(ValueFromPipeline)] 69 | [string]$ConfigAsString 70 | , 71 | [alias("c")] 72 | [string[]]$Config 73 | , 74 | [alias("d")] 75 | [switch]$WhatIf 76 | , 77 | [alias("f")] 78 | [switch]$Force 79 | , 80 | [alias("h")] 81 | [switch]$Help 82 | , 83 | [alias("m")] 84 | [string]$Mail 85 | , 86 | [alias("s")] 87 | [string]$State 88 | , 89 | [alias("u")] 90 | [switch]$Usage 91 | ) 92 | 93 | if ($WhatIf) { 94 | Write-Warning "We are in Debug mode. No logs will be rotated." 95 | $VerbosePreference = 'Continue' 96 | } 97 | if ($Force) { 98 | Write-Warning "We are in Forced-Rotation mode." 99 | } 100 | 101 | # Use Caller Error action if specified 102 | $CallerEA = $ErrorActionPreference 103 | $ErrorActionPreference = 'Stop' 104 | 105 | # Always use verbose mode? 106 | #$VerbosePreference = 'Continue' 107 | 108 | # PS Defaults 109 | $PSDefaultParameterValues['*-Content:Force'] = $true 110 | $PSDefaultParameterValues['*-Item:Force'] = $true 111 | $PSDefaultParameterValues['Get-ChildItem:Force'] = $true 112 | $PSDefaultParameterValues['Out-File:Force'] = $true 113 | $PSDefaultParameterValues['Invoke-Command:ErrorAction'] = 'Stop' 114 | 115 | # Prints and exits 116 | if ($Help) { 117 | Write-Output (Get-Help Log-Rotate -Full) 118 | return 119 | } 120 | if ($Usage) { 121 | Write-Output (Get-Help Log-Rotate) 122 | return 123 | } 124 | 125 | try { 126 | Write-Verbose "------------------------------ Log-Rotate --------------------------------------" 127 | # Will always reflect the calling script's path, even when used as a Module 128 | if ($MyInvocation.PSCommandPath) { 129 | Write-Verbose "Script root: $( Split-Path -parent $MyInvocation.PSCommandPath )" 130 | } 131 | #Write-Verbose "Current working directory: $( Convert-Path . )" 132 | Write-Verbose "Current working directory: $( $(Get-Location).Path )" 133 | 134 | 135 | # Get the configuration as a string 136 | if ($ConfigAsString) { 137 | # Pipelined string. Keep going 138 | $MultipleConfig = $ConfigAsString 139 | }else { 140 | # No pipeline string. From this point on $Config has to be an array of: a path to a config file, or directory containing config files. 141 | if (!$Config) { 142 | Write-Error "No config file(s) specified." -ErrorAction Stop 143 | } 144 | try { 145 | $MultipleConfig = '' 146 | $Config | ForEach-Object { 147 | # Path has to be valid 148 | if (Test-Path $_) { 149 | 150 | $item = Get-Item $_ 151 | if (Test-Path $item.FullName -PathType Container) { 152 | # It's a directory. Consider all child files as config files. 153 | Get-ChildItem $item.FullName -File | ForEach-Object { 154 | Write-Verbose "Config file found: $($_.FullName)" 155 | $MultipleConfig += "`n" + (Get-Content $_.FullName -Raw -ErrorAction Stop) 156 | } 157 | }else { 158 | # It's a file. 159 | Write-Verbose "Config file found: $($item.FullName)" 160 | $MultipleConfig += "`n" + (Get-Content $item.FullName -Raw -ErrorAction Stop) 161 | } 162 | 163 | }else { 164 | throw "Invalid config path specified: $_" 165 | } 166 | } 167 | }catch { 168 | Write-Error "Unable to retrieve content of config $Config" -ErrorAction Continue 169 | throw 170 | } 171 | } 172 | 173 | # Instantiate our BlockFactory and LogFactory 174 | #$BlockFactory = $BlockFactory.psobject.copy() 175 | #$LogFactory = $LogFactory.psobject.copy() 176 | 177 | # Compile our Full Config 178 | $FullConfig = Compile-Full-Config $MultipleConfig 179 | 180 | # Validate our Full Config 181 | Validate-Full-Config $FullConfig 182 | 183 | # Instantiate Singletons 184 | $BlockFactory = New-BlockFactory 185 | $LogFactory = New-LogFactory 186 | $LogObject = New-LogObject 187 | 188 | # Create Blocks from our Full Config 189 | $BlockFactory.Create($FullConfig) 190 | 191 | # Initialize our Rotation Status 192 | $LogFactory.InitStatus($State) 193 | 194 | $count = 0 195 | $BlockFactory.GetAll().GetEnumerator() | ForEach-Object { 196 | $count += $_.Value.LogFiles.Count 197 | } 198 | Write-Verbose "Handling $count logs" 199 | # Run Log-Rotate for each defined block 200 | $blocks = $BlockFactory.GetAll() 201 | $blocks.GetEnumerator() | ForEach-Object { 202 | # This block object. 203 | $block = $_.Value 204 | $blockoptions = $block.Options 205 | 206 | # Rotate each log of this block 207 | Process-Local-Block -block $block @blockoptions 208 | } 209 | 210 | # Finish up with dumping status 211 | $LogFactory.DumpStatus() 212 | }catch { 213 | Write-Error -ErrorRecord $_ -ErrorAction $CallerEA 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /test/test.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | param ( 3 | [Parameter(Mandatory=$false)] 4 | [ValidateNotNullOrEmpty()] 5 | [string]$Tag = '' 6 | ) 7 | $MODULE_NAME = (Get-Item $PSScriptRoot/../).Name 8 | $MODULE_DIR = "$PSScriptRoot/../src/$MODULE_NAME" 9 | $MODULE_MANIFEST = "$MODULE_DIR/$MODULE_NAME.psd1" 10 | 11 | Set-StrictMode -Version Latest 12 | 13 | # Install Pester if needed 14 | $pester = Get-Module Pester -ListAvailable -ErrorAction SilentlyContinue 15 | $pesterMinVersion = [version]'4.0.0' 16 | $pesterMaxVersion = [version]'4.10.1' 17 | if (!$pester -or !($pester.Version | ? { $_ -ge $pesterMinVersion -and $_ -le $pesterMaxVersion })) { 18 | Install-Module Pester -Force -Scope CurrentUser -MinimumVersion $pesterMinVersion -MaximumVersion $pesterMaxVersion -ErrorAction Stop -SkipPublisherCheck 19 | } 20 | Get-Module Pester | Remove-Module -Force 21 | Import-Module Pester -MinimumVersion $pesterMinVersion -MaximumVersion $pesterMaxVersion -Force -ErrorAction Stop 22 | Get-Module Pester 23 | 24 | # Install RequiredModules if needed 25 | $manifestObj = Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content $MODULE_MANIFEST -Encoding utf8 -Raw))) 26 | if ($manifestObj.Contains('RequiredModules')) { 27 | foreach ($m in $manifestObj['RequiredModules']) { 28 | $m = $m.Clone() 29 | $m['Name'] = $m['ModuleName'] 30 | $m.Remove('ModuleName') 31 | if (!(Get-InstalledModule @m -ErrorAction SilentlyContinue)) { 32 | "Installing required module: $( $m['Name'] )" | Write-Host -ForegroundColor Green 33 | Install-Module @m -Force -Scope CurrentUser -ErrorAction Stop 34 | } 35 | Get-Module $m['Name'] -ListAvailable 36 | } 37 | } 38 | 39 | # Test the module manifest 40 | Test-ModuleManifest "$MODULE_MANIFEST" -ErrorAction Stop > $null 41 | 42 | # Import our module 43 | Get-Module "$MODULE_NAME" | Remove-Module -Force 44 | Import-Module $MODULE_MANIFEST -Force -ErrorAction Stop -Verbose 45 | Get-Module "$MODULE_NAME" 46 | 47 | $global:PesterDebugPreference_ShowFullErrors = $true # For Pester 4 48 | if ($Tag) { 49 | # Run Unit Tests 50 | $res = Invoke-Pester -Script $MODULE_DIR -Tag $Tag -PassThru -ErrorAction Stop 51 | if ($res.FailedCount -gt 0) { 52 | "$( $res.FailedCount ) $Tag tests failed." | Write-Host 53 | } 54 | if ($res -and $res.FailedCount -gt 0) { 55 | throw 56 | } 57 | }else { 58 | # Run Unit Tests 59 | $res = Invoke-Pester -Script $MODULE_DIR -Tag 'Unit' -PassThru -ErrorAction Stop 60 | if ($res.FailedCount -gt 0) { 61 | "$( $res.FailedCount ) unit tests failed." | Write-Host 62 | } 63 | 64 | # Run Integration Tests 65 | $res2 = Invoke-Pester -Script $MODULE_DIR -Tag 'Integration' -PassThru -ErrorAction Stop 66 | if ($res2.FailedCount -gt 0) { 67 | "$( $res2.FailedCount ) integration tests failed." | Write-Host 68 | } 69 | 70 | if (($res -and $res.FailedCount -gt 0) -or ($res2 -and $res2.FailedCount -gt 0)) { 71 | throw 72 | } 73 | } 74 | --------------------------------------------------------------------------------