简体   繁体   中英

how to authenticate domain credential in powershell script

I have a powershell script which validate multiple tests in each windows image. But the below specific test require domain credentials to be used to run successfully when I use this script!

Can anyone help me to fix ?

if (($ImageName -like "*dev*") -or ($ImageName -like "*bare*"))
    {
        #$ADE1 = Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') | out-string ; $ADE = $ADE1.trim().split("")[1]
        Invoke-Expression ('C:\ade\bin\ade.exe | select-string -pattern "begintrans"') > C:\Temp\ade_check.txt 
        $ADE1 = Get-Content C:\Temp\ade_check.txt | Select-String "begintrans" | out-string ;  $ADE = $ADE1.trim().split(" ")[1]

        if ($ADE -eq "begintrans")
        {
        $ADE = "ADE Success"
echo "ADE = ADE Success"
        }

        if ($ADE -eq $null){
        $ADE = "ADE Failed"
echo "ADE = ADE Failed"
        }

    }
    else
        {
        if (($ImageName -like "*simple*") -or ($ImageName -like "*BareOS*")){

        $ADE = "BareOS, ADE Not Installed"
echo "ADE = BareOS, ADE Not Installed"
        }
        }

As suggested by @vonPryz running the script in an authenticated remote session is probably the best thing to. Regarding your concern that Get-Credential is needed for instantiating a remote session and asks for username and password, there are at least two options:

  1. Creating PSCredential on the fly
  2. Reading encrypted credentials from disk

Creating PSCredential on the fly

Creating credentials from clear text passwords is described here: Creating a PS Credential from a Clear Text Password in Powershell

You basically run:

PS C:\> $password = "P@ssw0rd" | ConvertTo-SecureString -asPlainText -Force
PS C:\> $username = "EdgarSchnittenfittich" 
PS C:\> $credential = New-Object System.Management.Automation.PSCredential($username,$password)

Reading encrypted credentials from disk

Once you have a PSCredential object you can export it in an encrypted form via Export-CliXml . To import your credentials just issue Import-CliXml . The credentials are store in an encrypted form with an opaque encryption key for the current user exporting the credentials. This means that only the same user can later on import the credentials again.

Example:

$cred = Get-PSCredential;
$cred | Export-CliXml C:\TEMP\Credentials.xml;

$importedCredentials = Import-CliXml C:\TEMP\Credentials.xml;

Running your Scripts

  • With these credentials you can easily run any script via Enter-PSSession or Invoke-Command .
  • Regarding your Jenkins environment: make sure you export the encrypted credentials under the same service account that you use to import your credentials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM