Search code examples
powershellvspherepowercli

Unable to pass param to ConvertTo-SecureString, only script defined variable


This one has been confusing me or the last couple of days. Unable to pass param to ConvertTo-SecureString, only script defined variable.

When I run a script I pass a number of params. On of the tasks it needs to do is connect to a remote machine via PSSession, i.e.

./myscript.ps1 -VMPass "12345@!" -VMuser abc

In my script I have the following which will be passed to New-PSSession:

[CmdletBinding()] 
Param(
    $VMuser,
    $VMPass
)

$PWord = ConvertTo-SecureString -AsPlainText -String "$VMPass" -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $VMuser, $PWord
$NewVMSession = (New-PSSession -ComputerName $NewVMAddress -Credential $cred -ErrorAction Stop)

When I run this I get the following error:

New-PSSession : [WIN-V2BK0KCPC7H] Connecting to remote server WIN-V2BK0KCPC7H
failed with the following error message : Access is denied. For more information,
see the about_Remote_Troubleshooting Help topic.
At C:\Users\ChildsC\Documents\Git\BAIC\Controller.ps1:85 char:26
+ ... MSession = (New-PSSession -ComputerName $NewVMAddress -Credential $vm ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed

However, if I were to explicitly define $VMPass = "12345@!" in the script OR if I were to call Get-Credential it works fine.

So there is a small issue in the way the param is being passed.


Solution

  • sorry for the late response.

    Later when I tried to explicitly call with the password in the script rather than passing it via a variable I was facing issues of intermittent connection.

    If I were to connect to a machine already on our domain with the same script above then it works fine. This issue seems to be only when a machines is not connected to the domain.

    I had thought about setting up an OS Template but I can not use templates to setup the VM to the domain because we have too many OUs.

    My workaround is to disable the firewall. I have scripts that connect the VM to the domain and once added I can then re-enable the firewall.

    I am not particularly satisfied with this but it is the only thing that works for now and is consistent. I did try opening some specific ports as detailed here: https://blogs.technet.microsoft.com/christwe/2012/06/20/what-port-does-powershell-remoting-use/

    But I again I was not getting consistent results. But as I know that the firewall is an issue I can go back to it later to determine which ports I should open. I am open to ideas about how to do this if anyone has anything :).

    I will mark this as answered.

    Thanks for your time.