Forum Discussion
Run PowerShell with different credentials without prompt on remote machines
$credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList "UserName","Password"
powershell.exe -executionpolicy Bypass -file %script% -Credentials $credential
Using Install-Module -Name CredentialManager is also a good approach for credentials.
Firstly, it's bad practice to embed clear-text credentials in a script (I'd even include base64 as that's not actually encryption and can easily be reversed.)
Fetching them from a remote credentials store (such as Azure Key Vault, your suggestion of the downloadable CredentialManager module, or even a custom database) or prompting for them once prior to calling the script x times is okay, but not direct inclusion in the code. Of course, the obvious issue here is that none of these approaches can be leveraged "out of the box", which is another reason why staging the credential prior to calling the script is advantageous (since you'd only need the custom approach to be functional on the host doing the remote callouts.)
Secondly, powershell.exe does not actually contain a "-Credentials" parameter.
about PowerShell exe - PowerShell | Microsoft Docs
Lastly, I'd strongly recommend not leveraging the Bypass execution policy unless there's a profoundly compelling reason for doing so as that undermines system security - possibly for no good reason.
It's a rare day when RemoteSigned is found to be too restrictive.
Cheers,
Lain
- Alan2022Jul 05, 2022Iron ContributorHi LainRobertson
Any idea how to pass the user credential from task scheduler to the powershell script to be more secure in running custom reports?
Currently now im using CredentialManager module but if you have more secure proper way hope you could share what is the best approach for this.
Thanks.- LainRobertsonJul 05, 2022Silver Contributor
I don't have a single preferred method since not all environments I visit are the same. If Credential Manager works for you then that ought to be fine.
So long as credentials aren't being stored directly within the script, then that satisfies good scripting practice.
The question then changes to "how securely are your credentials stored" and maybe also "are they being transmitted over the wire in plain text", but those kinds of questions are not specific to PowerShell and therefore not really PowerShell "best practice"-related.
Cheers,
Lain
Edited to fix a typo and some grammar.