Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Optimize the output of pscmd
#1
Powershell syntax is simple, has been updated to 6.x, and the function is getting stronger!It can also call libraries supported by .net

I found a situation, using the pscmd function, after executing the code, the output results always have some fixed, extra characters, very regular, is there a way to display only the results?

Maybe already have a solution, just I don't know, Thanks in advance

extra characters:

first line:
#< CLIXML

last line:
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS><I64 N="SourceId">1</I64><PR N="Record"><AV>Preparing modules for first use.</AV><AI>0</AI><Nil /><PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj></Objs>

There is also an example here:
http://www.quickmacros.com/forum/showthr...8#pid33538

Macro PS
Code:
Copy      Help
str code=
;get-process
PsCmd code "" _s
out _s
#2
workaround
Code:
Copy      Help
PsCmd "get-process" "-Version 2.0"
#3
Use this function instead of PsCmd.

Function PsCmd3
Code:
Copy      Help
;/
function# $commands [$cl] [str&output] [flags] ;;flags: 1 UTF-8 output, 2 ANSI output

;Executes PowerShell script stored in a variable or macro.
;Waits and returns powershell.exe's return value.

;commands - one or more PowerShell commands.
;;;QM 2.3.5. Can be macro, like "macro:MacroName". Gets whole text, or text that follows #ret line. Ignores first line if it looks like macro options ( /...).
;;;QM 2.3.5. If "", gets caller's text that follows #ret line.
;cl - additional powershell.exe command line arguments.
;output - variable that receives output text. If omitted or 0, displays the text in QM output.
;flags - output text encoding. See example.

;REMARKS
;Uses a temporary file and command line -File to pass it to powershell.exe. Also adds command line -ExecutionPolicy Bypass.
;Error if powershell.exe does not exist. PowerShell is available on Windows 7/2008/+, and can be downloaded for some older Windows versions.

;See also: <PsFile>

;EXAMPLES
;PsCmd3 "get-date"

;str code=
;;get-process
;PsCmd3 code "" _s
;out _s

;PsCmd3 "" "" 0 1
;#ret
;[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
;Write-Host "test ąčę αβγ"


#exe addtextof "<script>"
#opt nowarnings 1
opt noerrorshere 1

Scripting_GetCode commands _s

__TempFile tf.Init("ps1")
if(_unicode) str s.from("[0xEF][0xBB][0xBF]" commands); s.setfile(tf)
else _s=commands; _s.setfile(tf)

s.format("%s -ExecutionPolicy Bypass -File ''%s''" cl tf)

ret sub.PsRunCL(s output flags)


#sub PsRunCL
function# $cl [str&output] [flags]

opt noerrorshere 1

str ps.searchpath("powershell.exe"); if(!ps.len) end "PowerShell not installed"
str s.format("%s %s" ps cl)
if(!&output) int print=1; str so; &output=so
int enc=0; if(flags&1) enc=0x800; else if(flags&2) enc=0x400
int r=RunConsole2(s output 0 enc)
output.trim("[]")
if(print and output.len) out output
ret r
#4
thank you for your reply

I used the above code to test that pscmd3 cannot call jint.dll


Macro PSrunjs
Code:
Copy      Help
str s
_s=
;function Invoke-JSAdd ($a, $b) {
;;;;;Add-Type –Path  "C:\Jint.dll"
;;;;;;;;;;;;;;
;;;;;$JavaScript = "
;;;;;;;;;function add(a, b) {
;;;;;;;;;;;;;return a + b;
;;;;;;;;;}
;;;;;"
;;;;;$add = (New-Object Jint.Engine).
;;;;;;;;;;;;;Execute($JavaScript).
;;;;;;;;;;;;;GetValue("add")
;;;;;;;;;;;;;;
;;;;;$add.Invoke($a, $b).ToString()
;}
;
;Invoke-JSAdd 5 6
PsCmd _s "-Version 5.0" s ;;success  But there are extra characters
;PsCmd3 _s "" s ;;failure
;PsCmd3 _s "-Version 2.0" s ;;failure
;PsCmd3 _s "-Version 5.0" s ;;failure
mes s


Attached Files
.zip   Jint.zip (Size: 96.91 KB / Downloads: 28)
#5
Works here. I get output 11.

Macro Macro356
Code:
Copy      Help
out
PsCmd3 ""

#ret
function Invoke-JSAdd ($a, $b) {
;;;;Add-Type –Path  "Q:\Test\Jint.dll"
;;;;;;;;;;;;;
;;;;$JavaScript = "
;;;;;;;;function add(a, b) {
;;;;;;;;;;;;return a + b;
;;;;;;;;}
;;;;"
;;;;$add = (New-Object Jint.Engine).
;;;;;;;;;;;;Execute($JavaScript).
;;;;;;;;;;;;GetValue("add")
;;;;;;;;;;;;;
;;;;$add.Invoke($a, $b).ToString()
}

Invoke-JSAdd 5 6
#6
Still can't output the result, I am using win7 system, powershell updated to 5.1
Below is an animated GIF demo

https://ibb.co/FJrM2kX
#7
How to pause these animated gifs?
#8
https://drop.me/BbRR4m

I turned GIF into video.
#9
I don't know why –P is damaged. On my PC works well. I'm using Windows 10 with its PowerShell, don't know which version.
If you have the very first version of PsCmd3, try current version. It marks the file as UTF-8 if QM is in Unicode mode (default). The first version did not support Unicode.
#10
I don't have the first version of PsCmd3, now the QM option is unicode mode.

View powershell version command
$PSVersionTable

my ver


Attached Files Image(s)
   
#11
Name                           Value
----                           -----
PSVersion                      5.1.18362.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.18362.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
#12
Strange, pscmd can output, But with extra code


Attached Files Image(s)
   
#13
The – before Path is some Unicode character, not true -. Replace it.
#14
I do not understand

PsCmd _s "-Version 2.0" s ;;failure
PsCmd _s "-Version 5.0" s ;;success  But there are extra characters
#15
Unable to use .net class

I am running the powershell code directly, it is successful.

But using pscmd3 is a failure


Macro PS net
Code:
Copy      Help
str s1="$desktop$\1.png"
_s=
F
;Add-Type -AssemblyName System.Web;
;$url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic';
;$pic='{s1.expandpath}';
;$imagedata=[Web.HttpUtility]::UrlEncode([Convert]::ToBase64String([IO.File]::ReadAllBytes($pic)));
;$poststr=@(
;;;;;'access_token=24.b305c9822131e65eda05e29c157dd719.2592000.1559103982.282335-16139329',
;;;;;$('image='+$imagedata),
;;;;;'language_type=CHN_ENG',
;;;;;'detect_direction=false',
;;;;;'detect_language=false',
;;;;;'probability=false'
;) -join '&';
;$web=New-Object System.Net.WebClient;
;$web.Headers.Add('Content-Type', 'application/x-www-form-urlencoded');
;[byte[]]$postdata=[Text.Encoding]::UTF8.GetBytes($poststr);
;[byte[]]$responsedata=$web.UploadData($url, 'POST', $postdata);
;[Text.Encoding]::UTF8.GetString($responsedata);

str s
PsCmd3 _s "" s
mes s


Attached Files Image(s)
   
#16
Run successfully using the code below
in the ps code, variable Cannot be included
 $pic='{s1.expandpath}';


Macro PS2
Code:
Copy      Help
str s1="$desktop$\1.png"
_s=
F
;Add-Type -AssemblyName System.Web;
;$url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic';
;$pic='C:\1.png';
;$imagedata=[Web.HttpUtility]::UrlEncode([Convert]::ToBase64String([IO.File]::ReadAllBytes($pic)));
;$poststr=@(
;;;;;'access_token=24.b305c9822131e65eda05e29c157dd719.2592000.1559103982.282335-16139329',
;;;;;$('image='+$imagedata),
;;;;;'language_type=CHN_ENG',
;;;;;'detect_direction=false',
;;;;;'detect_language=false',
;;;;;'probability=false'
;) -join '&';
;$web=New-Object System.Net.WebClient;
;$web.Headers.Add('Content-Type', 'application/x-www-form-urlencoded');
;[byte[]]$postdata=[Text.Encoding]::UTF8.GetBytes($poststr);
;[byte[]]$responsedata=$web.UploadData($url, 'POST', $postdata);
;[Text.Encoding]::UTF8.GetString($responsedata);

str s
PsCmd _s "-Version 2.0" s
mes s

Is there a solution? Smile
#17
I tested your code with {variable} and it works without errors. Don't know why not on your PC. Result:
{"log_id": 1252041876708167624, "words_result_num": 0, "words_result": []}
#18
Tip in the image upper right corner: File not found

The file path in the image lower left corner seems to be split in two lines.

I think in the Chinese version of the system, it should be escaping \n

I very much hope to solve this problem.

Because I think it is very convenient to use PS to call the .net class library.

PS syntax is simpler than C#, automatic task is completely enough


Attached Files Image(s)
   
#19
I reinstalled the English version of the system, the test results are also wrong, there are garbled

But directly using Windows PowerShell ISE, no garbled, I recorded a video demo


Attached Files
.zip   Video_demo.zip (Size: 5.04 MB / Downloads: 20)
.txt   Powershell Code.txt (Size: 766 bytes / Downloads: 22)
#20
I found some rules again:

Under the Chinese system: pscmd can support unicode characters very well, pscmd3 will generate garbled characters.

Under the English system: pscmd and pscmd3 are not very good for unicode character support.

However, using powershell ise to execute the code, in Chinese and English systems, the output is always successful, there is no garbled

Because of the garbled, many of Powershell's code can't be used in QM.
Shy

Please see the GIF demo below


Macro Macro14
Code:
Copy      Help
;Under the Chinese operating system
_s=
;"letter`ttotal总空间(GB)`tAvailable space(GB)`tUsed space(GB)`tUsage rate"
;gwmi win32_logicaldisk -filter "drivetype = 3" | % {
;;;;;$_.deviceid + "`t" + `
;;;;;($_.size/1GB).tostring("f2") + "`t`t" + `
;;;;;($_.freespace/1GB).tostring("f2") + "`t`t" + `
;;;;;($_.size/1GB-$_.freespace/1GB).tostring("f2") + "`t`t" + `
;;;;;(($_.size-$_.freespace)/$_.size*100).tostring("f2") + "%"
;}

;PsCmd _s "-Version 2.0" str's ;;Output: Unicode characters are not garbled
PsCmd3 _s "" str's ;;Output: Unicode characters are garbled

mes s


Attached Files Image(s)
   
#21
It seems you use the old version of PsCmd3. As I wrote previously, it did not support Unicode. Also need flag 1 and OutputEncoding, like in the example in PsCmd3 code.

This works well here:
Code:
Copy      Help
PsCmd3 "" "" 0 1

#ret
[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
Write-Host "test ąčę αβγ"
#22
Sorry, I just saw the above pscmd3 code updated.  Wink

I added parameter 1 with the new version of pscmd3 but still garbled?
Shy

Macro Macro14
Code:
Copy      Help
;Under the Chinese operating system
_s=
;Add-Type -AssemblyName System.Web;
;$url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic';
;$pic='C:\1.png';
;$imagedata=[Web.HttpUtility]::UrlEncode([Convert]::ToBase64String([IO.File]::ReadAllBytes($pic)));
;$poststr=@(
;;;;;'access_token=24.b305c9822131e65eda05e29c157dd719.2592000.1559103982.282335-16139329',
;;;;;$('image='+$imagedata),
;;;;;'language_type=CHN_ENG',
;;;;;'detect_direction=false',
;;;;;'detect_language=false',
;;;;;'probability=false'
;) -join '&';
;$web=New-Object System.Net.WebClient;
;$web.Headers.Add('Content-Type', 'application/x-www-form-urlencoded');
;[byte[]]$postdata=[Text.Encoding]::UTF8.GetBytes($poststr);
;[byte[]]$responsedata=$web.UploadData($url, 'POST', $postdata);
;[Text.Encoding]::UTF8.GetString($responsedata);

PsCmd3 _s "" str's 1 ;;Output: Unicode characters are garbled

mes s

PsCmd3 _s "" str's 1 ;;Output: Unicode characters are garbled
PsCmd3 _s "" str's ;;Output: Unicode characters are not garbled

Why?
Huh

I just tested the English version of the system, the parameters have no effect, will produce garbled, please see the following GIF demo


Attached Files Image(s)
       
#23
try this

Macro Macro28
Code:
Copy      Help
str s1.expandpath("$desktop$\3.png")
_s=
F
;[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
;Add-Type -AssemblyName System.Web;
;$url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic';
;$pic='{s1}';
;$imagedata=[Web.HttpUtility]::UrlEncode([Convert]::ToBase64String([IO.File]::ReadAllBytes($pic)));
;$poststr=@(
;;;;;'access_token=24.b305c9822131e65eda05e29c157dd719.2592000.1559103982.282335-16139329',
;;;;;$('image='+$imagedata),
;;;;;'language_type=CHN_ENG',
;;;;;'detect_direction=false',
;;;;;'detect_language=false',
;;;;;'probability=false'
;) -join '&';
;$web=New-Object System.Net.WebClient;
;$web.Headers.Add('Content-Type', 'application/x-www-form-urlencoded');
;[byte[]]$postdata=[Text.Encoding]::UTF8.GetBytes($poststr);
;[byte[]]$responsedata=$web.UploadData($url, 'POST', $postdata);
;[Text.Encoding]::UTF8.GetString($responsedata);

str s
PsCmd3 _s "" s 1
mes s

and make sure this is your PsCmd3 code

Function PsCmd3
Code:
Copy      Help
;;/
function# $commands [$cl] [str&output] [flags] ;;flags: 1 UTF-8 output, 2 ANSI output

;Executes PowerShell script stored in a variable or macro.
;Waits and returns powershell.exe's return value.

;commands - one or more PowerShell commands.
;;;QM 2.3.5. Can be macro, like "macro:MacroName". Gets whole text, or text that follows #ret line. Ignores first line if it looks like macro options ( /...).
;;;QM 2.3.5. If "", gets caller's text that follows #ret line.
;cl - additional powershell.exe command line arguments.
;output - variable that receives output text. If omitted or 0, displays the text in QM output.
;flags - output text encoding. See example.

;REMARKS
;Uses a temporary file and command line -File to pass it to powershell.exe. Also adds command line -ExecutionPolicy Bypass.
;Error if powershell.exe does not exist. PowerShell is available on Windows 7/2008/+, and can be downloaded for some older Windows versions.

;See also: <PsFile>

;EXAMPLES
;PsCmd3 "get-date"

;str code=
;;get-process
;PsCmd3 code "" _s
;out _s

;PsCmd3 "" "" 0 1
;#ret
;[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
;Write-Host "test ąčę αβγ"


#exe addtextof "<script>"
#opt nowarnings 1
opt noerrorshere 1

Scripting_GetCode commands _s

__TempFile tf.Init("ps1")
if(_unicode) str s.from("[0xEF][0xBB][0xBF]" commands); s.setfile(tf)
else _s=commands; _s.setfile(tf)

s.format("%s -ExecutionPolicy Bypass -File ''%s''" cl tf)

ret sub.PsRunCL(s output flags)


#sub PsRunCL
function# $cl [str&output] [flags]

opt noerrorshere 1

str ps.searchpath("powershell.exe"); if(!ps.len) end "PowerShell not installed"
str s.format("%s %s" ps cl)
if(!&output) int print=1; str so; &output=so
int enc=0; if(flags&1) enc=0x800; else if(flags&2) enc=0x400
int r=RunConsole2(s output 0 enc)
output.trim("[]")
if(print and output.len) out output
ret r
#24
Perfect solution, thanks for your help Heart

Powershell is much more powerful than vbs, a few lines of code to achieve the effect of dozens of lines of VBS code

More importantly, it can call the .net class library, omnipotent Tongue
#25
your above code had garbled text because you didn't set the console  like Gintaras suggested

this line was  the difference between proper output and garbled text

[Console]::OutputEncoding=[System.Text.Encoding]::UTF8
#26
Thanks for your explanation of the problem.


Forum Jump:


Users browsing this thread: 1 Guest(s)