0

Am trying to echo a string and encode using base64 by getting the echoed string as input.

Write-Host "Hello World" | $b = [System.Convert]::FromBase64String($_) ; [System.Text.Encoding]::UTF8.GetString($b)

But getting below error,

At line:1 char:28
+ Write-Host "Hello World" | $b = [System.Convert]::FromBase64String($_) ; [System ...
+                            ~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

Any idea for this

Karthi1234
  • 949
  • 1
  • 8
  • 28

2 Answers2

1

This means that the function you are trying to pipe to does not accept pipelines.

You will need to use variables to pass into the function.
eg.

// convert string to base64
$a = "Hello World"
$b = [System.Text.Encoding]::UTF8.GetBytes($a)
$c = [System.Convert]::ToBase64String($b)
Write-Host $c
codersl
  • 2,222
  • 4
  • 30
  • 33
  • Yeah that was working for me as well. But I will pass the string from some other script, so I have to get input as that string. – Karthi1234 Mar 03 '17 at 06:36
  • To save output of command to a variable you could try [PowerShell: Capture the output from external process that writes to stderr in a variable ](http://stackoverflow.com/questions/8184827/powershell-capture-the-output-from-external-process-that-writes-to-stderr-in-a) – codersl Mar 03 '17 at 11:01
0

You can use Write-output and pipe it to New-Variable

Write-output "test" | New-Variable -Name b
$b = [System.Convert]::FromBase64String($b)
[System.Text.Encoding]::UTF8.GetString($b)

You can also create function fot this:

function Verb-Noun{
    Param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)][string]$string )

    [System.Text.Encoding]::UTF8.GetString( ( [System.Convert]::FromBase64String($string) ) )
}

Write-Output "test" | Verb-Noun

Note that you must use Write-output to pipe the string. Write-Host will not work here.

Also, your string "Hello world" cannot be converted using this method since [System.Convert]::FromBase64String($string) only works with strings that their length is a multiple of 4. (I suppose this was simply a not very good example)

Moshe perez
  • 1,626
  • 1
  • 8
  • 17