如何修改PowerShell中Format-Table的输出数据?
解决PowerShell追踪链接点击量的需求
直接上修改后的完整脚本:
# Set the API key and endpoint $apiKey = "API-KEY" $endpoint = "https://api.rebrandly.com/v1/links?&limit=100" # 获取原始数据并处理 $response = Invoke-RestMethod -Method GET -Uri $endpoint -Headers @{ "apikey" = $apiKey } | Where-Object { # 过滤非文件类型链接:判断目标路径包含扩展名(即最后一段有.) $uri = [System.Uri]$_.destination $lastSegment = $uri.Segments[-1] $lastSegment -match '\.' } | Select-Object clicks, @{ Name = 'name' Expression = { # 提取不带扩展名的文件名 $uri = [System.Uri]$_.destination $fileName = $uri.Segments[-1] [System.IO.Path]::GetFileNameWithoutExtension($fileName) } } | Format-Table -AutoSize $response
对应需求的实现说明:
- 列名从
destination改为name:用Select-Object的计算属性(哈希表),指定Name='name',把处理后的文件名映射到这个列。 - 过滤非文件类型链接:通过
Where-Object筛选,先把destination转成Uri对象,取最后一段路径,判断是否包含.(扩展名标识),只保留符合条件的条目。 - 仅显示文件名(不含URL及扩展名):利用
[System.IO.Path]::GetFileNameWithoutExtension()方法,从Uri的最后一段路径中提取不带扩展名的文件名,这个方法能自动处理各种文件名格式,比正则更可靠。
运行后就能得到你想要的结果:
clicks name ------ ---- 11 file1 4 file2 2 main
内容的提问来源于stack exchange,提问作者I am Jakoby
相关产品推荐
相关产品推荐

