Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write a multiline string into a file without adding characters to the string?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" });    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading