@@ -139,6 +139,12 @@ public SecureString SecureString
139139 }
140140 }
141141
142+ /// <summary>
143+ /// Gets or sets a switch to get the secure string as plain text.
144+ /// </summary>
145+ [ Parameter ( ParameterSetName = "AsPlainText" ) ]
146+ public SwitchParameter AsPlainText { get ; set ; }
147+
142148 /// <summary>
143149 /// Processes records from the input pipeline.
144150 /// For each input object, the command encrypts
@@ -165,6 +171,19 @@ protected override void ProcessRecord()
165171 {
166172 encryptionResult = SecureStringHelper . Encrypt ( SecureString , Key ) ;
167173 }
174+ else if ( AsPlainText )
175+ {
176+ IntPtr valuePtr = IntPtr . Zero ;
177+ try
178+ {
179+ valuePtr = Marshal . SecureStringToGlobalAllocUnicode ( SecureString ) ;
180+ exportedString = Marshal . PtrToStringUni ( valuePtr ) ;
181+ }
182+ finally
183+ {
184+ Marshal . ZeroFreeGlobalAllocUnicode ( valuePtr ) ;
185+ }
186+ }
168187 else
169188 {
170189 exportedString = SecureStringHelper . Protect ( SecureString ) ;
@@ -342,22 +361,8 @@ protected override void ProcessRecord()
342361 }
343362 else
344363 {
345- if ( ! Force )
346- {
347- string error =
348- SecureStringCommands . ForceRequired ;
349- Exception e = new ArgumentException ( error ) ;
350- WriteError ( new ErrorRecord ( e , "ImportSecureString_ForceRequired" , ErrorCategory . InvalidArgument , null ) ) ;
351- }
352- else
353- {
354- // The entire purpose of the SecureString is to prevent a secret from being
355- // permanently stored in memory as a .Net string. If they use the
356- // -AsPlainText and -Force flags, they consciously have made the decision to be OK
357- // with that.
358- importedString = new SecureString ( ) ;
359- foreach ( char currentChar in String ) { importedString . AppendChar ( currentChar ) ; }
360- }
364+ importedString = new SecureString ( ) ;
365+ foreach ( char currentChar in String ) { importedString . AppendChar ( currentChar ) ; }
361366 }
362367 }
363368 catch ( ArgumentException e )
0 commit comments