如何在JavaScript中将多行PowerShell字符串原样写入.ps1文件?
解决PowerShell脚本导出时的格式错乱问题
问题说明
使用JavaScript函数导出PowerShell脚本到.ps1文件时,生成的文件内容出现"和\n转义字符,所有代码挤成一行,导致PowerShell命令无法正常执行。
原JavaScript代码:
const script = `$Win32Product= Get-WmiObject -Class Win32_Product | Where Name -like 'Test Client' if ($Win32Product -eq $null){$Check=$false}else{$Check=$true} $Hash = @{ Check = $Check } Return $Hash | ConvertTo-Json -Compress`; const writeStringToPowerShellFile = () => { const blob = new Blob([script], { type: "text/plain" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.download = "resultScript.ps1"; link.href = url; link.click(); };
期望生成的.ps1文件内容:
$Win32Product= Get-WmiObject -Class Win32_Product | Where Name -like 'Test Client' if ($Win32Product -eq $null){$Check=$false}else{$Check=$true} $Hash = @{ Check = $Check } Return $Hash | ConvertTo-Json -Compress
解决步骤
- 确保字符串换行符正确:Windows平台下的文本文件使用
\r\n作为换行符,直接用模板字符串可能在部分环境中被转译成\n的字面量而非真实换行。改用数组拼接的方式生成带正确换行符的字符串; - 指定文件编码:创建Blob时明确指定UTF-8编码,避免字符转义问题;
- 释放URL对象:点击下载链接后释放
Object URL,避免内存泄漏。
修改后的代码:
// 用数组拼接生成带Windows换行符的脚本内容 const script = [ "$Win32Product= Get-WmiObject -Class Win32_Product | Where Name -like 'Test Client'", "if ($Win32Product -eq $null){$Check=$false}else{$Check=$true}", "$Hash = @{ Check = $Check }", "Return $Hash | ConvertTo-Json -Compress" ].join('\r\n'); const writeStringToPowerShellFile = () => { // 指定UTF-8编码确保内容正确解析 const blob = new Blob([script], { type: "text/plain;charset=utf-8" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.download = "resultScript.ps1"; link.href = url; link.click(); // 释放URL对象 URL.revokeObjectURL(url); };
原理说明
- 数组拼接后用
\r\n连接,确保生成的字符串包含Windows平台认可的换行符,而非转义字符; - 指定
charset=utf-8避免浏览器默认编码导致的字符转义; - 调用
URL.revokeObjectURL释放临时URL,防止浏览器内存占用过高。
内容的提问来源于stack exchange,提问作者TheStranger
相关产品推荐
相关产品推荐

