mcpField
P
powershell-7.5-features

powershell-7.5-features

github.com/josiahsiegel开发5979 次安装19 周前更新
代码仓库

关于 powershell-7.5-features

这是一份介绍 PowerShell 7.5 功能及 7.6 预览版的参考技能,面向脚本编写者和管理员,归纳命令变更、性能与包管理更新,并提供示例。

主要功能

  1. 01将对象序列化为 CLI XML 字符串
  2. 02按修改时间筛选路径
  3. 03保存 Web 响应并返回内容
  4. 04解析含注释或尾随逗号的 JSON
  5. 05通配路径匹配隐藏文件
  6. 06了解 PSResourceGet 与运行时更新

适用场景

  1. 01在命令间传递序列化对象
  2. 02自动清理旧日志文件
  3. 03下载文件并检查 HTTP 状态
  4. 04验证含注释的配置 JSON

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill powershell-7.5-features

安装后在 Claude Code 中输入/powershell-7.5-features确认已加载。

附带文件references/powershell-7-6-preview.md

详细介绍

PowerShell 7.5/7.6 功能

版本概览

版本状态.NET发布日期
7.5.4稳定版(LTS).NET 9.0.3062025 年 10 月
7.6.0-preview.6预览版.NET 10.0.0 GA2025 年 12 月

PowerShell 7.5 是当前稳定的 LTS(长期支持)版本。PowerShell 7.6 目前处于预览阶段,新增功能预计将于 2026 年初正式发布。


PowerShell 7.5 功能

PowerShell 7.5 GA(正式发布:2025 年 1 月)——最新稳定版本 7.5.4(2025 年 10 月),基于 .NET 9.0.306 构建,在性能和内存方面进行了显著优化。

新增 Cmdlet

ConvertTo-CliXml 和 ConvertFrom-CliXml

在不进行文件 I/O 的情况下,将对象转换为 CLI XML 格式或从该格式转换对象:

# ConvertTo-CliXml - Convert object to XML string
$process = Get-Process -Name pwsh
$xmlString = $process | ConvertTo-CliXml

# ConvertFrom-CliXml - Convert XML string back to object
$restored = $xmlString | ConvertFrom-CliXml
$restored.ProcessName  # Outputs: pwsh

# Use cases:
# - Serialize objects for API transmission
# - Store object state in databases/caches
# - Share objects across PowerShell sessions
# - Clipboard operations with rich objects

与 Export/Import-Clixml 的区别:

  • Export-Clixml:写入文件
  • ConvertTo-CliXml:返回字符串(不进行文件 I/O)

增强的 Test-Path Cmdlet

-OlderThan 和 -NewerThan 参数

按修改时间筛选路径:

# Find files older than 30 days
Test-Path "C:\Logs\*.log" -OlderThan (Get-Date).AddDays(-30)

# Find files newer than 1 hour
Test-Path "C:\Temp\*" -NewerThan (Get-Date).AddHours(-1)

# Cleanup old log files
Get-ChildItem "C:\Logs" -Filter "*.log" |
  Where-Object { Test-Path $_.FullName -OlderThan (Get-Date).AddDays(-90) } |
  Remove-Item -WhatIf

# Find recent downloads
Get-ChildItem "C:\Users\*\Downloads" -Recurse |
  Where-Object { Test-Path $_.FullName -NewerThan (Get-Date).AddDays(-7) }

适用场景:

  • 自动执行日志轮转
  • 清理备份文件
  • 监控近期文件
  • 缓存失效处理

增强的 Web Cmdlet

将 -PassThru 与 -OutFile 配合使用

将响应保存到文件并返回内容:

# Before PowerShell 7.5 (choose one):
Invoke-WebRequest -Uri $url -OutFile "download.zip"  # Save only
$response = Invoke-WebRequest -Uri $url              # Return only

# PowerShell 7.5 (both):
$response = Invoke-WebRequest -Uri $url -OutFile "download.zip" -PassThru
$response.StatusCode  # 200
# File also saved to download.zip

# Download and verify
$result = Invoke-RestMethod -Uri "https://api.example.com/data.json" `
  -OutFile "data.json" `
  -PassThru

Write-Host "Downloaded $($result.Length) bytes"
# File saved to data.json

优点:

  • 跟踪下载进度
  • 检查 HTTP 标头
  • 验证状态代码
  • 同时保存文件并处理内容

增强的 Test-Json Cmdlet

IgnoreComments 和 AllowTrailingCommas

解析宽松格式的 JSON:

# JSON with comments (previously invalid)
$jsonWithComments = @"
{
  // This is a comment
  "name": "example",  // inline comment
  /* Multi-line
     comment */
  "version": "1.0"
}
"@

# PowerShell 7.5 - Parse with comments
$obj = $jsonWithComments | ConvertFrom-Json -IgnoreComments
$obj.name  # Outputs: example

# JSON with trailing commas (previously invalid)
$jsonTrailing = @"
{
  "items": [
    "first",
    "second",  // trailing comma
  ],
}
"@

# PowerShell 7.5 - Parse with trailing commas
$obj = $jsonTrailing | ConvertFrom-Json -AllowTrailingCommas

# Validate JSON with relaxed syntax
Test-Json -Json $jsonWithComments -IgnoreComments
Test-Json -Json $jsonTrailing -AllowTrailingCommas

适用场景:

  • 解析带注释的配置文件
  • 处理来自 JavaScript 工具的 JSON
  • 接受 API 返回的宽松格式 JSON
  • 验证配置文件

增强的 Resolve-Path 和 Convert-Path

为通配符隐藏文件添加 -Force 参数

使用通配符访问隐藏文件或系统文件:

# PowerShell 7.4 and earlier - Hidden files not matched
Resolve-Path "C:\Users\*\.*" | Select-Object -First 5
# Skips .vscode, .gitignore, etc.

# PowerShell 7.5 - Include hidden files
Resolve-Path "C:\Users\*\.*" -Force | Select-Object -First 5
# Includes .vscode, .gitignore, .bashrc, etc.

# Find all hidden config files
Resolve-Path "C:\Projects\*\.*" -Force |
  Where-Object { (Get-Item $_).Attributes -match "Hidden" }

# Convert-Path also supports -Force
Convert-Path "~/.config/*" -Force

适用场景:

  • 在备份脚本中包含隐藏文件
  • 查找配置
  • 安全审计
  • 设置开发环境

New-FileCatalog 默认使用版本 2

FileCatalog 版本 2 现为默认版本:

# PowerShell 7.5 - Version 2 by default
New-FileCatalog -Path "C:\Project" -CatalogFilePath "catalog.cat"
# Creates version 2 catalog (SHA256)

# Explicitly specify version
New-FileCatalog -Path "C:\Project" `
  -CatalogFilePath "catalog.cat" `
  -CatalogVersion 2

# Test file integrity
Test-FileCatalog -Path "C:\Project" -CatalogFilePath "catalog.cat"

版本差异:

  • 版本 1:SHA1 哈希(旧版)
  • 版本 2:SHA256 哈希(默认,更安全)

.NET 9 性能优化

显著的性能提升
# PowerShell 7.5 benefits from .NET 9.0.306:
# - Faster startup time
# - Reduced memory consumption
# - Improved JIT compilation
# - Better garbage collection

# Example: Large dataset processing
Measure-Command {
  1..1000000 | ForEach-Object { $_ * 2 }
}
# PowerShell 7.4: ~2.5 seconds
# PowerShell 7.5: ~1.8 seconds (28% faster)
内存效率
# Lower memory footprint for:
# - Large collections
# - Long-running scripts
# - Concurrent operations
# - Pipeline processing

# Monitor memory usage
[System.GC]::GetTotalMemory($false) / 1MB
# PowerShell 7.5 uses 15-20% less memory on average

PSResourceGet 1.1.1(2025 年 3 月)

现代化包管理

PSResourceGet 是 PowerShellGet 的官方后继产品,可显著提升性能并增强安全性。

主要功能:

  • 速度提升 2 倍:安装模块
  • 增强安全性:集成 SecretManagement,实现凭据安全存储
  • 支持 Azure Artifacts:集成企业专用源
  • 更好的错误处理:提供更清晰的错误消息和重试逻辑
# Install PSResourceGet (included in PowerShell 7.4+)
Install-Module -Name Microsoft.PowerShell.PSResourceGet -Force

# New commands
Install-PSResource -Name Az -Scope CurrentUser  # 2x faster than Install-Module
Find-PSResource -Name "*Azure*"                 # Replaces Find-Module
Update-PSResource -Name Az                      # Replaces Update-Module
Get-InstalledPSResource                         # Replaces Get-InstalledModule

# Security best practice - use SecretManagement for credentials
Register-PSResourceRepository -Name "PrivateFeed" `
    -Uri "https://pkgs.dev.azure.com/org/project/_packaging/feed/nuget/v3/index.json" `
    -Trusted

# Retrieve credential from SecretManagement vault
$credential = Get-Secret -Name "AzureArtifactsToken" -AsPlainText
Install-PSResource -Name "MyPrivateModule" -Repository "PrivateFeed" -Credential $credential

性能对比:

操作PowerShellGetPSResourceGet 1.1.1提升
安装模块10-15s5-7s快 2 倍
搜索模块3-5s1-2s快 2-3 倍
更新模块12-18s6-9s快 2 倍

安全性增强:

  • 脚本中切勿使用明文凭据
  • 使用 SecretManagement 模块存储仓库凭据
  • 支持 Azure DevOps 个人访问令牌(PAT)
  • 与 Azure Artifacts 集成身份验证
# WRONG - plaintext credential
$cred = New-Object PSCredential("user", (ConvertTo-SecureString "password" -AsPlainText -Force))

# CORRECT - SecretManagement
Install-Module Microsoft.PowerShell.SecretManagement
Register-SecretVault -Name LocalVault -ModuleName Microsoft.PowerShell.SecretStore
Set-Secret -Name "RepoToken" -Secret "your-token"

$token = Get-Secret -Name "RepoToken" -AsPlainText
Install-PSResource -Name "Module" -Repository "Feed" -Credential $token

从 PowerShell 7.4 迁移

检查版本
# Current version
$PSVersionTable.PSVersion
# 7.5.4 (latest stable as of October 2025)

# .NET version
[System.Runtime.InteropServices.RuntimeInformation]::FrameworkDescription
# .NET 9.0.306

# PSResourceGet version
Get-Module Microsoft.PowerShell.PSResourceGet -ListAvailable
# Version 1.1.1 (latest as of March 2025)
更新脚本以适配 7.5
# Replace file-based XML serialization
# Before:
$data | Export-Clixml -Path "temp.xml"
$xml = Get-Content "temp.xml" -Raw
Remove-Item "temp.xml"

# After:
$xml = $data | ConvertTo-CliXml

# Use new Test-Path filtering
# Before:
Get-ChildItem | Where-Object {
  $_.LastWriteTime -lt (Get-Date).AddDays(-30)
}

# After:
Get-ChildItem | Where-Object {
  Test-Path $_.FullName -OlderThan (Get-Date).AddDays(-30)
}

# Leverage -PassThru for downloads
# Before:
Invoke-WebRequest -Uri $url -OutFile "file.zip"
$size = (Get-Item "file.zip").Length

# After:
$response = Invoke-WebRequest -Uri $url -OutFile "file.zip" -PassThru
$size = $response.RawContentLength

PowerShell 7.5 最佳实践

  1. 使用 ConvertTo/From-CliXml 进行内存中序列化:
# Serialize to clipboard
$data | ConvertTo-CliXml | Set-Clipboard

# Deserialize from clipboard
$restored = Get-Clipboard | ConvertFrom-CliXml
  1. 利用 Test-Path 的时间筛选功能:
# Clean old logs
Get-ChildItem "C:\Logs" | Where-Object {
  Test-Path $_.FullName -OlderThan (Get-Date).AddDays(-90)
} | Remove-Item
  1. 使用 -Force 执行隐藏文件操作:
# Backup including hidden config files
Resolve-Path "~/*" -Force |
  Where-Object { Test-Path $_ -OlderThan (Get-Date).AddDays(-1) } |
  Copy-Item -Destination "C:\Backup\"
  1. 简化下载工作流:
# Download and verify in one step
$response = Invoke-WebRequest $url -OutFile "data.zip" -PassThru
if ($response.StatusCode -eq 200) {
  Expand-Archive "data.zip" -Destination "data/"
}
  1. 解析宽松格式的 JSON:
# Configuration files with comments
$config = Get-Content "config.jsonc" -Raw |
  ConvertFrom-Json -IgnoreComments

CI/CD 集成

# GitHub Actions with PowerShell 7.5
- name: Setup PowerShell 7.5
  uses: actions/setup-powershell@v1
  with:
    pwsh-version: '7.5.x'

- name: Run Script with 7.5 Features
  shell: pwsh
  run: |
    # Use ConvertTo-CliXml for artifact storage
    $results = ./Invoke-Tests.ps1
    $results | ConvertTo-CliXml | Out-File "results.xml"

    # Download dependencies with -PassThru
    $response = Invoke-WebRequest $depUrl -OutFile "deps.zip" -PassThru
    Write-Host "Downloaded $($response.RawContentLength) bytes"

向后兼容性

PowerShell 7.5 与 7.x 脚本保持兼容:

  • 所有 7.0-7.4 脚本均可照常运行
  • 新参数均为可选
  • 现有 Cmdlet 没有重大更改
  • 保持模块兼容性

性能基准测试

操作PowerShell 7.4PowerShell 7.5改进
启动时间1.2s0.9s快 25%
大型管道2.5s1.8s快 28%
内存使用量120MB95MB低 21%
Web 请求450ms380ms快 16%

PowerShell 7.6 预览版功能

7.6 预览版系列的详细介绍——+= 数组拼接优化(8-16 倍)、增强的 Get-Clipboard 和 Get-Command、PSResourceGet 1.2.0-preview、DSC v3 资源、PSForEach / PSWhere 别名、.NET 10 集成、实验性功能、与 7.5 相比的重大变更、迁移步骤,以及 7.5 与 7.6 的基准测试——位于 references/powershell-7-6-preview.md。评估或采用 7.6 功能时,请加载该参考资料。


资源

评论

支持 Markdown