I want to run sudo pwsh
, Import-Module myFile.psm1
, Set-Values -Body 10
in 1 line in bash script.
Tried using &&
and and ;
operator but didn't work.
Any way to do this?
CodePudding user response:
I'd like to offer an alternative approach to this, which is even more useful when you have a complex set of commands that you'd like to run as a one-liner.
Both PowerShell and PowerShell Core support an -EncodedCommand parameter. The article above details the parameter as:
Accepts a Base64-encoded string version of a command. Use this parameter to submit commands to PowerShell that require complex, nested quoting. The Base64 representation must be a UTF-16LE encoded string.
With the EncodedCommand parameter, it's possible for us to pass a single Base64 string to the PowerShell or PWSH program and it will decode it and interpret it as though the original commands were run. I've found this extremely useful in the past when dealing with nested statements and script blocks containing quotes and apostrophes.
As detailed above, the EncodedCommand parameter expects the commands to be converted to a UTF-16LE Base64 string. There are various online convertors that will handle the conversion if you wish (one such converter can be found here: PowerShell Encoder)
As an example, let's pretend we want to run the following commands:
Import-Module ./myFile.psm1
Set-Values -Body 10
Upload-Values
$result = Confirm-Upload
if ($result -eq "OK") {
Write-Host 'Upload Successful'
} else {
Write-Host 'Upload Failed'
}
After conversion to the Base64 string, we end up with this string:
SQBtAHAAbwByAHQALQBNAG8AZAB1AGwAZQAgAC4ALwBtAHkARgBpAGwAZQAuAHAAcwBtADEADQAKAFMAZQB0AC0AVgBhAGwAdQBlAHMAIAAtAEIAbwBkAHkAIAAxADAADQAKAFUAcABsAG8AYQBkAC0AVgBhAGwAdQBlAHMADQAKACQAcgBlAHMAdQBsAHQAIAA9ACAAQwBvAG4AZgBpAHIAbQAtAFUAcABsAG8AYQBkAA0ACgBpAGYAIAAoACQAcgBlAHMAdQBsAHQAIAAtAGUAcQAgACIATwBLACIAKQAgAHsADQAKACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAFUAcABsAG8AYQBkACAAUwB1AGMAYwBlAHMAcwBmAHUAbAAnAA0ACgB9ACAAZQBsAHMAZQAgAHsADQAKACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAFUAcABsAG8AYQBkACAARgBhAGkAbABlAGQAJwANAAoAfQA=
To execute this, we'd simply do the following:
pwsh -EncodedCommand SQBtAHAAbwByAHQALQBNAG8AZAB1AGwAZQAgAC4ALwBtAHkARgBpAGwAZQAuAHAAcwBtADEADQAKAFMAZQB0AC0AVgBhAGwAdQBlAHMAIAAtAEIAbwBkAHkAIAAxADAADQAKAFUAcABsAG8AYQBkAC0AVgBhAGwAdQBlAHMADQAKACQAcgBlAHMAdQBsAHQAIAA9ACAAQwBvAG4AZgBpAHIAbQAtAFUAcABsAG8AYQBkAA0ACgBpAGYAIAAoACQAcgBlAHMAdQBsAHQAIAAtAGUAcQAgACIATwBLACIAKQAgAHsADQAKACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAFUAcABsAG8AYQBkACAAUwB1AGMAYwBlAHMAcwBmAHUAbAAnAA0ACgB9ACAAZQBsAHMAZQAgAHsADQAKACAAIAAgAFcAcgBpAHQAZQAtAEgAbwBzAHQAIAAnAFUAcABsAG8AYQBkACAARgBhAGkAbABlAGQAJwANAAoAfQA=
CodePudding user response:
It can be done as :
pwsh -Command "Import-Module myFile.psm1; Set-Values -Body 10"