Running PowerCLI as a Secure Scheduled Task

Post date: Jul 22, 2013 8:36:53 PM

Running PowerCLI as a Secure Scheduled task -

  1. Have or create a service account to run the scheduled task. In this case Domain\scripter
    1. This user must also have permissions necessary to Connect-VIserver and complete commands in the ensuing script.
  2. Create a secure string password file that your script will call and decrypt to pass credentials
    1. Run a PowerShell window as the service account.
      1. Shift Right-Click Run as different user ***IMPORTANT***
      2. Use the credentials of the service account. Domain\scripter
    2. $pw = read-host “Enter Password” –AsSecureString
      1. This will prompt you for the password of the service account password, hide the characters, and encrypt the password in System.Security.SecureString
    3. ConvertFrom-SecureString $pw | out-file <Save Location.txt>
      1. This will pipe the encrypted password string to a text file.
      2. It is advisable to deny all permissions except to the service account.
  3. Add the now secure connection information and vi snap-in to the head of the powershell script (.ps1)
    1. add-pssnapin VMware.VImAutomation.Core
      1. This allows Powershell to run vSphere PowerCLI Commands
    2. $pswdSec = Get-Content "D:\PasswordFile.txt" | ConvertTo-SecureString
      1. Calls the Password File containing the secure string
    3. $bPswd = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pswdSec)
    4. $pswd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bPswd)
      1. This converts the Encrypted String to a Text format that is then used to connect the service account in the following line
    5. connect-viserver -Server 123.123.123.123 -Protocol https -User scripter -Password $pswd
      1. This is the VIserver connection command to login using the service account credentials. Everything below this line will be your script.
  4. Configure the scheduled task and run .ps1 as the configured service account.

SOURCES:

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.aspx

http://mcpmag.com/articles/2013/02/26/securing-secure-strings.aspx

http://www.myitforum.com/articles/1/view.asp?id=10779