Credentials

Aus Wiki-WebPerfect
Wechseln zu: Navigation, Suche

Store password as securestring in a script (no plaintext)

IMPORTANT: It only works if it is created on the same server as it is running.

$Username = '<username>'
$Password = '<password>'
 
$SecurePassword = ConvertTo-SecureString -AsPlainText $Password -Force
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$SecurePassword


Now you can use the variable $Credentials in the parameter -Credential. For example:

Invoke-Command -ComputerName <hostname> -Credential $Credentials -ScriptBlock {
    Invoke-Expression $using:LogmanCMDStop 
}


Function to get plaintext from securestring

#Define function
Function Get-PlainFromSecureString {
    param (
        [Parameter(Mandatory = $true)]
        [securestring]$SecureString
    )
    return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString))
}
 
#Use the function
Get-PlainFromSecureString $YourPSCredentials.Password