sporty_1993
sporty_1993

Reputation: 123

Accessing credential in the script executing from Invoke-Command

I am trying to execute the following command in PowerShell:

Invoke-Command -ComputerName <computerName> -FilePath script.ps1 -Credential $cred

Using Invoke-Command I am executing a PowerShell script "script.ps1" providing credentials in $cred.

Is there any way I can use the passed variable $cred in the above Invoke-Command, in the script again without asking a user about credentials? i.e. something like below:

script.ps1:

New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection

Upvotes: 1

Views: 282

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

You can have the script accept a credential parameter:

script.ps1:

Param([PSCredential]$Credential)
New-PSSession ... -Credential $Credential

and invoke it while passing $cred as an argument like this:

Invoke-Command -Computer $computer -FilePath script.ps1 -ArgumentList $cred -Credential $cred

Upvotes: 4

Related Questions