如何用[System.Windows.Forms.Clipboard]::ContainsData检测剪贴板HTML格式?
解决PowerShell中获取剪贴板HTML内容的问题
问题出在你使用的剪贴板格式标识符不正确。[System.Windows.Forms.Clipboard]::ContainsData('html')返回false是因为剪贴板中HTML格式的标准标识符不是小写的html,而是HTML Format,对应[System.Windows.Forms.DataFormats]::Html常量。
以下是正确的操作步骤:
加载System.Windows.Forms程序集
PowerShell 7中默认不会自动加载该程序集,需先执行:Add-Type -AssemblyName System.Windows.Forms检测剪贴板中的HTML格式
使用正确的格式标识符:# 使用内置常量检测 [System.Windows.Forms.Clipboard]::ContainsData([System.Windows.Forms.DataFormats]::Html) # 或直接使用格式名称字符串 [System.Windows.Forms.Clipboard]::ContainsData('HTML Format')获取剪贴板的HTML内容字符串
获取到的数据为MemoryStream类型,需要转换为字符串:if ([System.Windows.Forms.Clipboard]::ContainsData([System.Windows.Forms.DataFormats]::Html)) { $htmlStream = [System.Windows.Forms.Clipboard]::GetData([System.Windows.Forms.DataFormats]::Html) $htmlContent = (New-Object System.IO.StreamReader($htmlStream.GetStream())).ReadToEnd() # 输出或后续处理HTML内容 $htmlContent }
补充说明
- 剪贴板中的HTML内容通常包含额外头部信息(如源URL、片段范围标记等),并非纯HTML,你可能需要根据需求截取实际HTML部分。
- 该方法仅适用于Windows平台的PowerShell 7,因为
System.Windows.Forms是Windows专属组件。
内容的提问来源于stack exchange,提问作者Ralf_Reddings
相关产品推荐
相关产品推荐

