Token导航 LogoToken导航TokenDH.com
开发敏感数据github未标认证来源可访问许可证需确认审计异常

powershell-scripting-for-security用于安全的 powershell 脚本

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

26,289

周安装

648

GitHub Stars

28

下载量

6,959
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:powershell-scripting-for-security(用于安全的 powershell 脚本)
来源仓库:https://github.com/zebbern/secops-cli-guides
仓库路径:skills/powershell-scripting-for-security
安装命令:
npx skills add https://github.com/zebbern/secops-cli-guides --skill 'PowerShell Scripting for Security'
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/zebbern/secops-cli-guides --skill 'PowerShell Scripting for Security'

简介

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查,帮助 Agent 梳理敏感配置和分析鉴权逻辑。

  • 适用于 PowerShell 脚本在安全领域的应用,如依赖风险检查和生成安全复核清单。
  • 使用时不能将工具输出直接当作最终结论,涉及密钥、令牌或生产系统时应先确认最小权限和操作边界。
  • 安装前需确认是否会触发联网、命令执行或文件读写,避免误改关键数据。
  • powershell-scripting-for-security 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

PowerShell Scripting for Security

Purpose

Develop PowerShell scripting skills for security automation, penetration testing, and system administration. This skill covers variables, operators, control structures, functions, modules, error handling, and practical security automation examples essential for red team operations and security assessments.

Prerequisites

Required Environment

  • Windows PowerShell 5.1 or PowerShell 7+
  • Administrator access for certain operations
  • Text editor (VS Code with PowerShell extension recommended)

Required Knowledge

  • Basic command-line familiarity
  • Understanding of programming concepts
  • Windows operating system fundamentals

Outputs and Deliverables

  1. Reusable Security Scripts - Automation scripts for common security tasks
  2. Custom PowerShell Functions - Modular security tools
  3. PowerShell Modules - Packaged security utilities
  4. Automation Workflows - Complete security assessment scripts

Core Workflow

Phase 1: Variables and Data Types

Work with PowerShell variables:

# Variable declaration ($ prefix required)
$target = "192.168.1.100"
$ports = @(21, 22, 80, 443, 3389)
$credentials = Get-Credential

# Check data type
$target.GetType().Name  # String
$ports.GetType().Name   # Object[]

# Type casting
$portString = "443"
$portInt = [int]$portString

# Common data types
[string]   # Text
[int]      # Integer
[bool]     # True/False
[array]    # Array of values
[hashtable]# Key-value pairs
[datetime] # Date and time
[psobject] # PowerShell object

Important automatic variables:

$_         # Current pipeline object
$?         # Last command success (True/False)
$Error     # Array of recent errors
$null      # Empty/null value
$true      # Boolean True
$false     # Boolean False
$PSScriptRoot  # Script directory path
$env:USERNAME  # Environment variables

Phase 2: Operators

Master PowerShell operators:

# Arithmetic operators
$a = 10; $b = 3
$a + $b   # 13 (addition)
$a - $b   # 7 (subtraction)
$a * $b   # 30 (multiplication)
$a / $b   # 3.33 (division)
$a % $b   # 1 (modulus)

# Comparison operators
$a -eq $b    # Equal
$a -ne $b    # Not equal
$a -lt $b    # Less than
$a -gt $b    # Greater than
$a -le $b    # Less or equal
$a -ge $b    # Greater or equal

# String comparison
"PowerShell" -like "*Shell*"     # Wildcard match
"PowerShell" -match "Shell$"     # Regex match
"192.168.1.1" -match "^\d+\.\d+\.\d+\.\d+$"  # IP pattern

# Logical operators
($a -gt 5) -and ($b -lt 5)  # AND
($a -gt 5) -or ($b -gt 5)   # OR
-not ($a -eq 10)            # NOT
!($a -eq 10)                # NOT (alternative)

# Assignment operators
$a += 5   # Add and assign
$a -= 5   # Subtract and assign
$a *= 2   # Multiply and assign
$a++      # Increment
$a--      # Decrement

Phase 3: Control Structures

Implement conditional logic:

# If/ElseIf/Else
$status = "open"
if ($status -eq "open") {
    Write-Host "Port is open"
} elseif ($status -eq "filtered") {
    Write-Host "Port is filtered"
} else {
    Write-Host "Port is closed"
}

# Switch statement
$port = 443
switch ($port) {
    21 { "FTP" }
    22 { "SSH" }
    80 { "HTTP" }
    443 { "HTTPS" }
    3389 { "RDP" }
    default { "Unknown service" }
}

# Switch with regex
switch -Regex ($input) {
    "^[A-Z]" { "Starts with letter" }
    "^[0-9]" { "Starts with number" }
    default { "Unknown format" }
}

Implement loops:

# ForEach-Object (pipeline)
$targets | ForEach-Object {
    Write-Host "Scanning: $_"
    Test-Connection -ComputerName $_ -Count 1
}

# Foreach statement
foreach ($target in $targets) {
    Write-Host "Scanning: $target"
}

# For loop
for ($i = 1; $i -le 254; $i++) {
    $ip = "192.168.1.$i"
    Test-Connection -ComputerName $ip -Count 1 -Quiet
}

# While loop
$count = 0
while ($count -lt 10) {
    Write-Host "Attempt: $count"
    $count++
}

# Do-While / Do-Until
do {
    $response = Invoke-WebRequest -Uri $url
} while ($response.StatusCode -ne 200)

# Break and Continue
foreach ($port in $ports) {
    if ($port -eq 0) { continue }  # Skip invalid
    if ($port -gt 65535) { break } # Stop loop
    Test-NetConnection -Port $port
}

Phase 4: Functions

Create reusable functions:

# Basic function
function Test-Port {
    param (
        [string]$ComputerName,
        [int]$Port
    )

    $connection = Test-NetConnection -ComputerName $ComputerName -Port $Port
    return $connection.TcpTestSucceeded
}

# Call the function
Test-Port -ComputerName "192.168.1.100" -Port 80

# Advanced function with CmdletBinding
function Invoke-PortScan {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [string]$Target,

        [Parameter()]
        [int[]]$Ports = @(21, 22, 80, 443, 3389),

        [Parameter()]
        [int]$Timeout = 1000
    )

    begin {
        Write-Verbose "Starting port scan"
        $results = @()
    }

    process {
        foreach ($port in $Ports) {
            $tcpClient = New-Object System.Net.Sockets.TcpClient
            $connect = $tcpClient.BeginConnect($Target, $port, $null, $null)
            $wait = $connect.AsyncWaitHandle.WaitOne($Timeout, $false)

            if ($wait -and $tcpClient.Connected) {
                $results += [PSCustomObject]@{
                    Target = $Target
                    Port = $port
                    Status = "Open"
                }
            }
            $tcpClient.Close()
        }
    }

    end {
        Write-Verbose "Scan complete"
        return $results
    }
}

# Usage
Invoke-PortScan -Target "192.168.1.100" -Ports 80,443 -Verbose

Phase 5: Error Handling

Implement robust error handling:

# Try/Catch/Finally
function Test-RemoteConnection {
    param([string]$Computer)

    try {
        $session = New-PSSession -ComputerName $Computer -ErrorAction Stop
        Write-Host "Connected to $Computer"
        return $session
    }
    catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
        Write-Warning "Cannot connect to $Computer - Access denied"
    }
    catch {
        Write-Warning "Error: $($_.Exception.Message)"
    }
    finally {
        Write-Verbose "Connection attempt completed"
    }
}

# ErrorAction parameter
Get-Service -Name "FakeService" -ErrorAction SilentlyContinue
Get-Service -Name "FakeService" -ErrorAction Stop  # Throws terminating error

# Check for errors
if ($Error.Count -gt 0) {
    Write-Host "Last error: $($Error[0].Exception.Message)"
}

Phase 6: Working with Objects

Manipulate PowerShell objects:

# Create custom objects
$scanResult = [PSCustomObject]@{
    Target = "192.168.1.100"
    Port = 80
    Status = "Open"
    Timestamp = Get-Date
}

# Add properties
$scanResult | Add-Member -NotePropertyName "Banner" -NotePropertyValue "Apache"

# Select specific properties
Get-Process | Select-Object Name, CPU, WorkingSet

# Filter objects
Get-Process | Where-Object { $_.CPU -gt 10 }

# Sort objects
Get-Process | Sort-Object CPU -Descending

# Group objects
Get-EventLog -LogName Security -Newest 1000 |
    Group-Object -Property EntryType

# Export objects
$results | Export-Csv -Path "results.csv" -NoTypeInformation
$results | ConvertTo-Json | Out-File "results.json"

Phase 7: Arrays and Hashtables

Work with collections:

# Arrays
$targets = @("192.168.1.1", "192.168.1.2", "192.168.1.3")
$targets += "192.168.1.4"  # Add element
$targets[0]                 # Access first element
$targets[-1]                # Access last element
$targets.Count              # Array length

# Hashtables
$credentials = @{
    Username = "admin"
    Password = "password123"
    Domain = "CORP"
}
$credentials["Username"]    # Access value
$credentials.Keys           # List keys
$credentials.Values         # List values

# Ordered hashtable
$config = [ordered]@{
    Target = "192.168.1.100"
    Ports = @(80, 443)
    Timeout = 5000
}

# ArrayList (dynamic sizing)
$results = [System.Collections.ArrayList]@()
$results.Add($scanResult) | Out-Null

Phase 8: File Operations

Handle files and output:

# Read files
$content = Get-Content -Path "targets.txt"
$json = Get-Content -Path "config.json" | ConvertFrom-Json
$csv = Import-Csv -Path "hosts.csv"

# Write files
$data | Out-File -Path "output.txt"
$data | Set-Content -Path "output.txt"
$results | Export-Csv -Path "results.csv" -NoTypeInformation
$config | ConvertTo-Json | Out-File "config.json"

# Append to file
Add-Content -Path "log.txt" -Value "$(Get-Date): Scan started"

# Test file existence
if (Test-Path -Path $filePath) {
    $content = Get-Content -Path $filePath
}

# Create directories
New-Item -ItemType Directory -Path ".\results" -Force

Phase 9: Network Operations

Perform network-related tasks:

# Web requests
$response = Invoke-WebRequest -Uri "https://target.com"
$response.StatusCode
$response.Content

# REST API calls
$apiResult = Invoke-RestMethod -Uri "https://api.target.com/users" -Method Get

# Download files
Invoke-WebRequest -Uri $url -OutFile "downloaded.exe"

# DNS lookups
Resolve-DnsName -Name "target.com" -Type A
Resolve-DnsName -Name "target.com" -Type MX

# Test connections
Test-Connection -ComputerName "192.168.1.100" -Count 4
Test-NetConnection -ComputerName "192.168.1.100" -Port 443

# Get network adapters
Get-NetAdapter | Where-Object Status -eq "Up"
Get-NetIPAddress -AddressFamily IPv4

Phase 10: Security Scripts

Create practical security scripts:

# Simple port scanner
function Invoke-QuickScan {
    param(
        [string]$Target,
        [int[]]$Ports = @(21,22,23,25,53,80,110,135,139,143,443,445,993,995,1433,3306,3389,5432,8080)
    )

    $openPorts = @()

    foreach ($port in $Ports) {
        $socket = New-Object System.Net.Sockets.TcpClient
        try {
            $socket.Connect($Target, $port)
            if ($socket.Connected) {
                $openPorts += $port
                Write-Host "[+] Port $port is OPEN" -ForegroundColor Green
            }
            $socket.Close()
        }
        catch {
            Write-Verbose "[-] Port $port is closed"
        }
    }

    return $openPorts
}

# Password generator
function New-SecurePassword {
    param([int]$Length = 16)

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"
    $password = ""

    for ($i = 0; $i -lt $Length; $i++) {
        $randomIndex = Get-Random -Minimum 0 -Maximum $chars.Length
        $password += $chars[$randomIndex]
    }

    return $password
}

# Log analyzer
function Search-SecurityLog {
    param(
        [int]$EventID,
        [int]$Hours = 24
    )

    $startTime = (Get-Date).AddHours(-$Hours)

    Get-WinEvent -FilterHashtable @{
        LogName = 'Security'
        ID = $EventID
        StartTime = $startTime
    } | Select-Object TimeCreated, Message
}

Quick Reference

Common Cmdlets

CmdletPurpose
Get-CommandFind commands
Get-HelpGet documentation
Get-MemberInspect object properties
Select-ObjectChoose properties
Where-ObjectFilter objects
ForEach-ObjectProcess each object
Sort-ObjectSort output
Export-CsvExport to CSV
ConvertTo-JsonConvert to JSON

Comparison Operators

OperatorMeaning
-eqEqual
-neNot equal
-ltLess than
-gtGreater than
-leLess or equal
-geGreater or equal
-likeWildcard match
-matchRegex match

Special Variables

VariableDescription
$_Current pipeline object
$PSScriptRootScript directory
$ErrorError collection
$nullNull value
$true / $falseBoolean values
$env:VAREnvironment variable

Script Structure Template

#Requires -Version 5.1
<#
.SYNOPSIS
    Brief description
.DESCRIPTION
    Detailed description
.PARAMETER Target
    Parameter description
.EXAMPLE
    Usage example
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [string]$Target
)

# Script logic here

Constraints and Limitations

Execution Policy

  • May need to set: Set-ExecutionPolicy RemoteSigned
  • Scripts from internet may be blocked
  • Consider signing scripts for production

Security Considerations

  • Credentials should use SecureString
  • Avoid hardcoding passwords
  • Use Get-Credential for interactive input
  • Store secrets in secure vaults

Performance

  • Large loops can be slow
  • Use -Parallel in PowerShell 7+ for parallelism
  • Avoid excessive pipeline operations
  • Pre-filter data when possible

Troubleshooting

Script Won't Execute

Solutions:

  1. Check execution policy: Get-ExecutionPolicy
  2. Unblock downloaded scripts: Unblock-File script.ps1
  3. Run as administrator if required
  4. Check PowerShell version compatibility

Module Not Found

Solutions:

  1. Install module: Install-Module -Name ModuleName
  2. Check PSModulePath: $env:PSModulePath
  3. Import explicitly: Import-Module -Name ModuleName
  4. Verify repository: Get-PSRepository

Permission Denied

Solutions:

  1. Run PowerShell as Administrator
  2. Check file permissions
  3. Verify user has required access
  4. Check remote PowerShell is enabled

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.13%
按下载量换算2,514

Claude

30.83%
按下载量换算2,145

Cursor

19.74%
按下载量换算1,374

Gemini CLI

9.2%
按下载量换算640

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

未通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills