
Analyzing Powershell Script Block Logging
- 258 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Guide analysis of Windows PowerShell Script Block Logging events for threat detection and incident review on defender-heavy stacks.
About
analyzing-powershell-script-block-logging is a cybersecurity-oriented agent skill focused on interpreting PowerShell Script Block Logging—Windows Event Tracing for Defender-class pipelines that records de-obfuscated script segments at execution time. Solo builders shipping SaaS on Windows servers or supporting enterprise customers often inherit EDR and SIEM expectations even when their day job is product code; this skill gives agents a named procedure for turning noisy script-block events into reviewable findings instead of ad-hoc grep. It sits in the Ship security lane because you typically enable, tune, and validate logging before you sign off on production posture, though operators may revisit it during incidents. Expect advanced familiarity with Windows logging, event IDs, and defender tooling; it is not a substitute for full purple-team exercises or generic secret scanning in CI.
- Centers on PowerShell Script Block Logging as a Windows telemetry source
- Fits anthropic-cybersecurity-skills family for structured defensive analysis
- Supports audit and compliance workflows on Microsoft-centric environments
- Targets interpreter-level script visibility rather than static repo scanning alone
Analyzing Powershell Script Block Logging by the numbers
- 258 all-time installs (skills.sh)
- +19 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #671 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-powershell-script-block-loggingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 258 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Guide analysis of Windows PowerShell Script Block Logging events for threat detection and incident review on defender-heavy stacks.
Files
Analyzing PowerShell Script Block Logging
When to Use
- When investigating security incidents that require analyzing powershell script block logging
- When building detection rules or threat hunting queries for this domain
- When SOC analysts need structured procedures for this analysis type
- When validating security monitoring coverage for related attack techniques
Prerequisites
- Familiarity with security operations concepts and tools
- Access to a test or lab environment for safe execution
- Python 3.8+ with required dependencies installed
- Appropriate authorization for any testing activities
Instructions
1. Install dependencies: pip install python-evtx lxml 2. Collect PowerShell Operational logs: Microsoft-Windows-PowerShell%4Operational.evtx 3. Parse Event ID 4104 entries using python-evtx to extract ScriptBlockText, ScriptBlockId, and MessageNumber/MessageTotal for multi-part script reconstruction. 4. Apply detection heuristics:
- Base64-encoded commands (
-EncodedCommand,FromBase64String) - Download cradles (
DownloadString,DownloadFile,Invoke-WebRequest,Net.WebClient) - AMSI bypass patterns (
AmsiUtils,amsiInitFailed) - Obfuscation indicators (high entropy, tick-mark insertion, string concatenation)
5. Generate a report with reconstructed scripts, risk scores, and MITRE ATT&CK mappings.
python scripts/agent.py --evtx-file /path/to/PowerShell-Operational.evtx --output ps_analysis.jsonExamples
Detect Encoded Command Execution
import base64
if "-encodedcommand" in script_text.lower():
encoded = script_text.split()[-1]
decoded = base64.b64decode(encoded).decode("utf-16-le")Reconstruct Multi-Block Script
Scripts split across multiple 4104 events share a ScriptBlockId. Concatenate blocks ordered by MessageNumber to recover the full script.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: PowerShell Script Block Logging Analysis
python-evtx Library
FileHeader
from Evtx.Evtx import FileHeader
with open(evtx_path, "rb") as f:
fh = FileHeader(f)
for record in fh.records():
xml_string = record.xml() # Returns XML string of the eventEvent XML Structure (Event ID 4104)
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<EventID>4104</EventID>
<TimeCreated SystemTime="2024-01-15T10:30:00.000Z"/>
</System>
<EventData>
<Data Name="MessageNumber">1</Data>
<Data Name="MessageTotal">3</Data>
<Data Name="ScriptBlockText">...powershell code...</Data>
<Data Name="ScriptBlockId">guid-string</Data>
<Data Name="Path">C:\script.ps1</Data>
</EventData>
</Event>lxml etree Parsing
from lxml import etree
NS = {"evt": "http://schemas.microsoft.com/win/2004/08/events/event"}
root = etree.fromstring(xml_bytes)
event_id = root.find(".//evt:System/evt:EventID", NS).text
data_elems = root.findall(".//evt:EventData/evt:Data", NS)
for elem in data_elems:
name = elem.get("Name")
value = elem.textScript Block Reconstruction
Large PowerShell scripts are split across multiple Event 4104 entries:
ScriptBlockId: Unique GUID shared across all partsMessageNumber: Part index (1-based)MessageTotal: Total number of parts- Reconstruct: concatenate parts ordered by MessageNumber
Key Detection Patterns
| Pattern | MITRE | Risk |
|---|---|---|
-EncodedCommand | T1059.001 | High |
FromBase64String | T1140 | High |
Invoke-Expression / iex | T1059.001 | High |
DownloadString / Net.WebClient | T1105 | Critical |
AmsiUtils / amsiInitFailed | T1562.001 | Critical |
Invoke-Mimikatz | T1003 | Critical |
| High entropy (>5.5) | T1027 | Medium |
#!/usr/bin/env python3
"""PowerShell Script Block Logging Analyzer - Parses Event 4104 from EVTX for obfuscated commands."""
import json
import math
import re
import base64
import logging
import argparse
from collections import defaultdict
from datetime import datetime
from Evtx.Evtx import FileHeader
from lxml import etree
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
NS = {"evt": "http://schemas.microsoft.com/win/2004/08/events/event"}
SUSPICIOUS_PATTERNS = [
(r"(?i)\-[Ee]ncoded[Cc]ommand", "Encoded command parameter", "T1059.001", "high"),
(r"(?i)FromBase64String", "Base64 decoding", "T1140", "high"),
(r"(?i)(Invoke-Expression|iex)\s*\(", "Invoke-Expression execution", "T1059.001", "high"),
(r"(?i)(DownloadString|DownloadFile|Invoke-WebRequest|wget|curl)", "Download cradle", "T1105", "critical"),
(r"(?i)(Net\.WebClient|WebRequest\.Create)", "Network client instantiation", "T1071.001", "high"),
(r"(?i)(AmsiUtils|amsiInitFailed|AmsiScanBuffer)", "AMSI bypass attempt", "T1562.001", "critical"),
(r"(?i)(Invoke-Mimikatz|Invoke-Kerberoast|Invoke-TokenManipulation)", "Offensive PowerShell tool", "T1003", "critical"),
(r"(?i)(Add-MpPreference\s*-ExclusionPath)", "Defender exclusion", "T1562.001", "high"),
(r"(?i)(Set-MpPreference\s*-DisableRealtimeMonitoring)", "Defender disable", "T1562.001", "critical"),
(r"(?i)(New-Object\s+System\.Net\.Sockets\.TCPClient)", "Reverse shell pattern", "T1059.001", "critical"),
(r"(?i)(Get-Process\s+lsass|MiniDump)", "LSASS dump attempt", "T1003.001", "critical"),
(r"(?i)(ConvertTo-SecureString|PSCredential)", "Credential handling", "T1078", "medium"),
]
def calculate_entropy(text):
"""Calculate Shannon entropy of a string to detect obfuscation."""
if not text:
return 0.0
freq = defaultdict(int)
for char in text:
freq[char] += 1
length = len(text)
return -sum((count / length) * math.log2(count / length) for count in freq.values())
def parse_evtx_4104(evtx_path):
"""Parse Event ID 4104 entries from a PowerShell Operational EVTX file."""
script_blocks = defaultdict(dict)
with open(evtx_path, "rb") as f:
fh = FileHeader(f)
for record in fh.records():
try:
xml = record.xml()
root = etree.fromstring(xml.encode("utf-8"))
event_id_elem = root.find(".//evt:System/evt:EventID", NS)
if event_id_elem is None or event_id_elem.text != "4104":
continue
event_data = {}
for data_elem in root.findall(".//evt:EventData/evt:Data", NS):
name = data_elem.get("Name", "")
event_data[name] = data_elem.text or ""
script_block_id = event_data.get("ScriptBlockId", "")
message_number = int(event_data.get("MessageNumber", "1"))
message_total = int(event_data.get("MessageTotal", "1"))
script_text = event_data.get("ScriptBlockText", "")
time_elem = root.find(".//evt:System/evt:TimeCreated", NS)
timestamp = time_elem.get("SystemTime", "") if time_elem is not None else ""
if script_block_id not in script_blocks:
script_blocks[script_block_id] = {
"parts": {},
"total": message_total,
"timestamp": timestamp,
"path": event_data.get("Path", ""),
}
script_blocks[script_block_id]["parts"][message_number] = script_text
except Exception:
continue
logger.info("Parsed %d unique script blocks from %s", len(script_blocks), evtx_path)
return script_blocks
def reconstruct_scripts(script_blocks):
"""Reconstruct full scripts from multi-part script block entries."""
reconstructed = []
for block_id, block_data in script_blocks.items():
parts = block_data["parts"]
total = block_data["total"]
ordered = [parts.get(i, "") for i in range(1, total + 1)]
full_script = "".join(ordered)
reconstructed.append({
"script_block_id": block_id,
"timestamp": block_data["timestamp"],
"path": block_data["path"],
"part_count": total,
"script_text": full_script,
"length": len(full_script),
})
logger.info("Reconstructed %d complete scripts", len(reconstructed))
return reconstructed
def decode_base64_commands(script_text):
"""Attempt to decode Base64-encoded command strings found in scripts."""
decoded_commands = []
b64_pattern = re.compile(r"[A-Za-z0-9+/=]{40,}")
for match in b64_pattern.finditer(script_text):
try:
decoded = base64.b64decode(match.group()).decode("utf-16-le", errors="ignore")
if any(c.isalpha() for c in decoded[:20]):
decoded_commands.append({"encoded": match.group()[:60], "decoded": decoded[:500]})
except Exception:
continue
return decoded_commands
def analyze_script(script_entry):
"""Analyze a single reconstructed script for suspicious patterns."""
text = script_entry["script_text"]
findings = []
for pattern, description, mitre, severity in SUSPICIOUS_PATTERNS:
matches = re.findall(pattern, text)
if matches:
findings.append({
"pattern": description,
"mitre_technique": mitre,
"severity": severity,
"match_count": len(matches),
"sample": matches[0][:100] if matches else "",
})
entropy = calculate_entropy(text)
if entropy > 5.5 and len(text) > 200:
findings.append({
"pattern": "High entropy (possible obfuscation)",
"mitre_technique": "T1027",
"severity": "medium",
"entropy": round(entropy, 2),
})
decoded = decode_base64_commands(text)
if decoded:
findings.append({
"pattern": "Base64-encoded content decoded",
"mitre_technique": "T1140",
"severity": "high",
"decoded_count": len(decoded),
"samples": decoded[:3],
})
return findings
def generate_report(scripts, all_findings):
"""Generate PowerShell script block analysis report."""
critical = sum(1 for f in all_findings if any(ff["severity"] == "critical" for ff in f["findings"]))
report = {
"timestamp": datetime.utcnow().isoformat(),
"total_scripts": len(scripts),
"suspicious_scripts": len([f for f in all_findings if f["findings"]]),
"critical_scripts": critical,
"findings": all_findings[:50],
}
print(f"PS SCRIPT BLOCK REPORT: {len(scripts)} scripts, {critical} critical")
return report
def main():
parser = argparse.ArgumentParser(description="PowerShell Script Block Logging Analyzer")
parser.add_argument("--evtx-file", required=True, help="Path to PowerShell Operational EVTX")
parser.add_argument("--output", default="ps_analysis.json")
args = parser.parse_args()
blocks = parse_evtx_4104(args.evtx_file)
scripts = reconstruct_scripts(blocks)
all_findings = []
for script in scripts:
findings = analyze_script(script)
if findings:
all_findings.append({
"script_block_id": script["script_block_id"],
"timestamp": script["timestamp"],
"path": script["path"],
"length": script["length"],
"findings": findings,
"script_preview": script["script_text"][:300],
})
report = generate_report(scripts, all_findings)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
Related skills
FAQ
Is Analyzing Powershell Script Block Logging safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.