I have a JavaScript function where I'm trying to write a PowerShell script to a PowerShell file. This is the function:
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();
};
Forget about whether or not the script itself makes sense, the issue is that when I do this the ps1 file comes out with "
and \n
all in one line and basically just messes up the powershell command. How do I make sure that the content of the file looks exactly like this:
$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
Don't use JSON.stringify
, because you're dealing with a string, not an object.
Try replacing:
const fileData = JSON.stringify(script);
const blob = new Blob([fileData], { type: "text/plain" });
with:
const blob = new Blob([script], { type: "text/plain" });