I have a sort of crazy situation. I have to run a powershell script from a SharePoint console app.
This will be running a remote session on a different server. I need to be able to run that remote session with a specific set of credentials in order to update an AD security group.
How can I do that?
Edit: This script is being triggered by a console app and needs to run unattended with no need to provide a password. The credentials will not change. I am looking for a way to provide the credentials via a token file or similar.
$myRemoteSessionCredential = Get-Credential -UserName 'domain\user'
$myRemoteSession = New-PSSession -ComputerName 'myRemoteComputer.FQDN' -Credential $myRemoteSessionCredential
Invoke-Command -Session $myRemoteSession -ScriptBlock {
# my command list to be executed on the remote computer using my remote cred
}
It would appear that I left out a critical component of the description. I need this to run without having to enter a password each time. It will be the same set of credentials and needs to be able to run unattended.
Can I take what you have above and create a token file that can be referenced and used?
Install-Module AZSBTools
$myRemoteSessionCredential = Get-SBCredential -UserName 'domain\user'
$myRemoteSession = New-PSSession -ComputerName 'myRemoteComputer.FQDN' -Credential $myRemoteSessionCredential
Invoke-Command -Session $myRemoteSession -ScriptBlock {
# my command list to be executed on the remote computer using my remote cred
}
The Get-SBCredential cmdlet persists the encrypted credential object to disk for unattended execution (you type in the pwd the first time)
To update the persisted credential (on disk) - say after pwd change, use
MS deliberately makes it difficult to persist credential objects, because of the security risk that represents. So there’s nothing native in PowerShell that makes it easy and straightforward and safe to keep a credential object on-disk.
The “right” way to do this is to use JEA, which is a Microsoft add-in for PowerShell. You can also set this up without JEA, it’s just a bit more manual; “Secrets of PowerShell Remoting” explains these “constrained endpoints.” The theory is that you set up an endpoint which has a persistent “run as” credential, and you let the script log into that to run its command. The credential is stored safely that way.