Home > database >  Powershell ConvertTo-SecureString not recognised if run script inline from cmd
Powershell ConvertTo-SecureString not recognised if run script inline from cmd

Time:12-21

When running from cmd.exe

powershell .\scripts\scriptname.ps1

Which has a line to convert plain text to secure string

[securestring]$secString = ConvertTo-SecureString $SampleString -AsPlainText -Force

I get error:

ConvertTo-SecureString : The 'ConvertTo-SecureString' command was found in the module 'Microsoft.PowerShell.Security', but the module could not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.Security'.

However if I open / run the script direct in powershell it runs fine?

If I try to import the module manually I get:

Import-Module : The following error occurred while loading the extended type data file: Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member AuditToString is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member AccessToString is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member Sddl is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member Access is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member Group is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member Owner is already present.
Error in TypeData "System.Security.AccessControl.ObjectSecurity": The member Path is already present.

Powershell version is

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      22621  963

CodePudding user response:

The symptom implies that you're indirectly launching powershell.exe, the Windows PowerShell CLI, from PowerShell (Core) 7 , in which case the latter's definition of the $env:PSModulePath variable makes Windows PowerShell (powershell.exe) attempt to load PowerShell (Core)'s modules instead.

Per GitHub issue #18530, the solution is to (temporarily) reset the PSModulePath environment variable:

set "PSModulePath="
powershell .\scripts\scriptname.ps1
  • Related