Search code examples
windowspowershellaccountsccm

How to correctly decrypt account credentials and pass them to Add-LocalGroupMember command


I am trying to create a script which adds currently logged on user account to local admin group which is to be deployed as SCCM package to freshly deployed computers in one particular AD OU group. I have encoded a service account credentials using a .key seed and stored them in a .txt file. Unfortunately I'm unable to retrieve/pass the current user account to aforementioned command.

I've tried running package with administrative rights option enabled, skipping credential encode and using various methods without success outside of lab, hence why I had to request a service account which would have enough rights to get the job done. Ive also tried various ways of identifying user accounts, however this is the only one which retrieves the actual account of windows user rather than the one under which PS session is running.

$User = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Computer = $env:COMPUTERNAME $svcAcc = "xxx\xx-xx" $PasswordFile = ".\Password.txt" $KeyFile = ".\AES.key" $key = Get-Content $KeyFile
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $svcAcc,(Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

Invoke-Command -ComputerName $Computer -Credential $Cred -ScriptBlock {Add-LocalGroupMember -Group "Administratorer" -Member $User}

I expected the $User variable to be passed correctly as when I run [System.Security.Principal.WindowsIdentity]::GetCurrent().Name selection, correct details are shown. Instead I get an error

Cannot validate argument on parameter 'Member'. The argument is null or empty"

Any pointers would be greatly appreciated


Solution

  • Everything within the scriptblock is executed on the remote machine. That remote machine does not have access to the local variable "$User"

    Use the -ArgumentList parameter to pass the $user variable to the Scriptblock.

    Invoke-Command -ComputerName $Computer -ScriptBlock {Add-LocalGroupMember -Group "Administratorer" -Member $args[0]} -ArgumentList $User