New-PSSession with creds from secure file

Hello all.
I am trying to write PS script to automate decomissioning of our VM’s

The trouble I ma running into is the New_PSSession command.
I am trying to pull the password from an encrypted password file but I keep running into an issue.
Here is my code

To create the secure password file

<# Set and encrypt credentials to file using default method #>

'$0meP@ss"*%W0rd' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Scripts\Password.txt"

To execute the command to disjoin the computer from the domain

$securePassFile = "C:\Scripts\Password.txt"
$usr = 'Domain\Usert'
$pw = Get-Content $securePassFile | ConvertTo-SecureString
$MyCredential = new-object System.Management.Automation.PSCredential($usr, $pw)

$RemoteSession = New-PSSession -ComputerName "$vmHost" -Credential $MyCredential

Invoke-Command -Session $RemoteSession -ScriptBlock {Remove-Computer -ComputerName "$vmHost" -UnjoinDomaincredential $MyCredential -PassThru -Verbose -Restart}

The error I am getting is

New-PSSession : [COMPUTER] Connecting to remote server COMPUTER failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\Scripts\ServerDecom.ps1:22 char:18
+ ... teSession = New-PSSession -ComputerName "$vmHost" -Credential $MyCred ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Scripts\ServerDecom.ps1:24 char:25
+ Invoke-Command -Session $RemoteSession -ScriptBlock {Remove-Computer  ...
+                         ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Thanks in advance for the help!

You know you have to use the same user on the same computer to be able to decrypt the password you saved this way, don’t you?

AND you have to use scoped variables inside your script block to be able to use them when they are defined outside of it.
So instead of $vmHost it has to be $USING:vmHost and instead of $MyCredential it has to be $USING:MyCredential.

1 Like