When a Invoke a PowerShell Script which contains ".GetBytes" function and "ToBase64String" function is executed, it fails with an error message
Issue Description
Invoke PowerShell fails with an exception when attempting to execute the sample PowerShell command shown below using “PowerShell 7.2.15”.
PowerShell Code
# Define the string to convert $String = "This is a string"Get the UTF-8 byte array of the string'
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($String)
Error
Message: The following exception occurred while retrieving member "GetBytes": "GenericArguments[0], 'System.ReadOnlySpan`1[System.Char]', on 'System.Func`3[T1,T2,TResult]' violates the constraint of type 'T1'."
Root Cause
The incompatibility between the Microsoft.PowerShell.SDK package and .NET 8 results in the failure. The System package is compiled for .NET 6 to ensure compatibility with older software environments, such as Studio versions targeting .NET 6. Direct use of newer versions of the SDK introduces compatibility challenges.
Resolution
To resolve the issue, you can take the following steps:
- Add the Correct SDK Version:
Adding the updated version of the Microsoft.PowerShell.SDK package as a direct dependency to the project overrides the dependency specified by the System Activities package.
- Address Additional Dependency Issues:
Dependency issues related to VisualBasic may occur after adding the Microsoft.PowerShell.SDK package. The dependency issue affects projects utilizing Invoke Code activities with Visual Basic as the execution language.
-
- Projects without Invoke Code activities that use Visual Basic execution language will remain unaffected.
- In scenarios requiring Visual Basic dependency resolution, the Microsoft.CodeAnalysis.VisualBasic package (version 4.9.2) can be added.
Conclusion
By adding both the necessary Microsoft.PowerShell.SDK package and resolving Visual Basic-related dependencies (if applicable), the compatibility issue with PowerShell 7.2.15 and the System.Text.Encoding usage can be successfully addressed.


