Wednesday, July 31, 2013

PowerShell Script to Run As A Different User

Short script for PowerShell that allows you to start, for example, Dynamics AX client under a different user account.

The main idea is to store the user's password as a secured string in a file, then to restore it from there and create credentials to launch the program.

First, run the script to save the password:


Write-Host "Input password for USERNAME..."
read-host -assecurestring | convertfrom-securestring | out-file C:\Scripts\USERNAMEpwd.txt

The following script can be saved in a file like RunDynamicsAXasUSERNAME.ps1 to be run as you need:


#Alex Voytsekhovskiy 2013-07-29
# Based on the links:
# http://blogs.technet.com/b/robcost/archive/2008/05/01/powershell-tip-storing-and-using-password-credentials.aspx
# http://jdhitsolutions.com/blog/2012/04/scripting-with-pscredential/
###############################################################################################
# This script is to run Dynamics AX under a different user account
# Without user input for credentials
###############################################################################################
[String]$Username = 'DOMAIN\USERNAME'

# Please check the following paths
# Absolute path to Dynamics AX shortcut
[string]$DynamicsAXAbsolutePath = 'S:\Program Files (x86)\Microsoft Dynamics AX\60\Client\Bin\Ax32.exe'

# Absolute path to the secured password file
[string]$PasswordAbsolutePath  = 'C:\Scripts\USERNAMEpwd.txt'

# Get the secured password from the file
$password = get-content $PasswordAbsolutePath | convertto-securestring

# Create credentials for the program launch
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username,$password

# Launch the program
echo "Trying to launch AX 2012..."
start-Process -FilePath $DynamicsAXAbsolutePath  -Credential $credentials 


I used the following links to create this script: http://blogs.technet.com/b/robcost/archive/2008/05/01/powershell-tip-storing-and-using-password-credentials.aspx
http://jdhitsolutions.com/blog/2012/04/scripting-with-pscredential/

Small update for the case when we want to launch AX with a particular configuration file.

# Please check the following paths
# Absolute path to Configuration file
[string]$DynamicsAXC = 'S:\ConfigurationFiles\MyFavouriteConfiguration.axc'

###############################################################################################
# the password should be saved previously as a secured string with the following script
# Write-Host "Input password..."
# read-host -assecurestring | convertfrom-securestring | out-file C:\Users\USERNAME\Documents\AX-DEVS\Scripts\USERNAMEpwd.txt
###############################################################################################

# Launch the program
echo "Trying to launch AX 2012..."
start-Process -FilePath $DynamicsAXAbsolutePath -argumentlist $DynamicsAXC -Credential $credentials