The -Credential parameter can also be used with a System.Management.Automation.PSCredential
object, and this is much more secure. Within Powershell, you can create an object of this type with
$UserName = 'domainpart\userIdPart'
$SecureStringPassword = Get_Password $UserName
$Credential = New-Object System.Management.Automation.PSCredential($UserName,$SecureStringPassword)
Start-Process $SomeExe -Credential $Credential ...
Then you must implement a function Get_Password
to retrieve the password in some secure manner. Reading a clear-text password from a text file is NOT the way to go. As Zeitlin says above, it is perhaps the worst security practice one could conceive of - even worse that putting your password on a sticky on your screen.
Instead, store the password as an encrypted string in the .txt file as follows. First, get a password as input, encrypt it, and store the encrypted string:
function Global:Get_PasswordFileName($Username)
{
$baseName = "encrypted_$UserName.txt" -replace '\','_'
"${env:LOCALAPPDATA}\$baseName"
}
$encryptedString = Read-Host -AsSecureString "Enter password for $UserName" | convertfrom-securestring
$passwordFileName = Get_PasswordFileName $Username
[System.IO.File]::WriteAllLines($passwdFileName, $encryptedString)
There are many ways to write the file, [System.IO.File]::WriteAllLines
is just one, and Get_PasswordfileName
can be tweaked to use any reasonable directory.
Then define Get_Password
as
function Global:Get_Password($UserName)
{
$passwordFileName = Get_PasswordFileName $Username
$EncryptedString = Get-Content $passwordFileName
ConvertTo-SecureString $EncryptedString
}
-credential
and-verb
in the samestart-process
command. I'd use-credential (get-credential)
or use encrypted password to automate this: adminarsenal.com/blog/…. Keep in mind,-verb RunAs
Creates an admin token to get rid of an UAC dialog, but will run as the current user.-credential
will run as the specified user, but won't surpress the UAC dialog.