save PSCredential in the file

前端 未结 2 1294
無奈伤痛
無奈伤痛 2020-11-29 07:25

I know I can save password to the file:

Read-Host \"Enter Password\" -AsSecureString |  ConvertFrom-SecureString | Out-File $passwordfile

a

2条回答
  •  执笔经年
    2020-11-29 08:16

    Building on Briantist & Graham: This will ask for a credential and store it on first run, then reuse it on subsequent runs from the same code. In my case drive H is the user's home directory, used for tidiness, not security.

    # the path to stored credential
    $credPath = "H:\Secrets\Cred_${env:USERNAME}_${env:COMPUTERNAME}.xml"
    # check for stored credential
    if ( Test-Path $credPath ) {
        #crendetial is stored, load it 
        $cred = Import-CliXml -Path $credPath
    } else {
        # no stored credential: create store, get credential and save it
        $parent = split-path $credpath -parent
        if ( -not ( test-Path $parent ) ) {
            New-Item -ItemType Directory -Force -Path $parent
        }
        $cred = get-credential
        $cred | Export-CliXml -Path $credPath
    }
    

    This block of code can be chucked in any script that needs it and the problem is more-or-less solved from then on.

    Could possibly also check for a successful credential before writing it if the application permits it. Note that if the password changes the user must delete the file. [edit: missing parenthesis in code]

提交回复
热议问题