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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 ](stackoverflow.com/questions/8184827/…)
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.