0

I am getting the below error while executing the below code Code :

$localScriptPath= "C:\AshishG\powershell\script12.ps1"
$ëncodedResonse = "77u/V3JpdGUtSG9zdCAnc2NyaXB0IGlzIGV4ZWN1dGVkIHN1Y2Nlc3NmdWxseScNCg0KcmV0dXJuICdUaGlzIGlzIHNjcmlwdCBvdXRwdXQn"
Write-Output "ëncodedResonse used is $ëncodedResonse"

[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($ëncodedResonse)) | Out-File $localScriptPath -Force
$Content2 = get-content $localScriptPath
Write-Host "DECODED: " $Content2

$output =Invoke-Expression "& `"$localScriptPath`" "
Write-Host "scriptPath" used is $output

Code explanation:

  1. Assign the path of the script into a variable.
  2. assign the encoded string to a variable
  3. decoding the string and copy into a file.
  4. Executing the PowerShell script and getting the error.

Error:

Write-Host : The term 'Write-Host' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a 
path was included, verify that the path is correct and try again.
At C:\AshishG\powershell\script12.ps1:1 char:1
+ Write-Host 'script is executed successfully'
+ ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Write-Host:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Please see the below points.

  1. I am getting the error while executing the powerscript (C:\AshishG\powershell\script12.ps1).
  2. The string is in an encoded format and I can decode it and I see, the decoded string is also fine.
  3. I observe, The script12.ps1 is generated in UTF-16 LE BOM format. is it creating the issue?

I have written complete code because I am not sure what is the issue?

Ashish Goyanka
  • 207
  • 3
  • 11
  • Just run "Write-Host hello world" in the terminal, is it ok? – navylover Dec 31 '21 at 05:23
  • yes, i am able to do it. – Ashish Goyanka Dec 31 '21 at 05:42
  • I suspect the issue from the encodage of your file. – BETOMBO Dec 31 '21 at 07:19
  • In PowerShell version 5.x, the default encoding for `Out-File` is **Unicode** (Utf16-LE), but you are expecting Utf8 (with or without BOM). This means the script is choking on the Byte Order Mark with which the file content starts (0xFF 0xFE). Use `Set-Content` or change the encoding of the file by using parameter `-Encoding` – Theo Dec 31 '21 at 11:34

1 Answers1

0

The error is coming from the .ps1 file you've created, most likely coming from the encoded string.

You have a non-printing character preceding "Write-host..." as evidenced by executing the following after creating your .ps1 file:

PS C:\>>[int[]][Char[]]((gc $localScriptPath)[0])[0]
65279
PS C:\>

&#65279 is a Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). PowerShell is glomming it with Write-HOst to create an unrecognizable command.

Keith Miller
  • 702
  • 5
  • 13