Link to home
Start Free TrialLog in
Avatar of Bret Robinson
Bret Robinson

asked on

I cannot use a variable for Set-AdComputer within the invoke-command

I appreciate the help as I am new to PowerShell.
I am trying to script changing the Set-AdComputer using an imported list of servers. I am able to run the script using the server name directly. As soon as I use a variable I get the following error: "Cannot validate argument on parameter 'Identity'. The argument is null."
Even if I remove the Import-CSV and set the variable manually I still get the same error.

Here is a simplified version of the script.

I appreciate the help!

Bret
Set-StrictMode -Version Latest
Import-Module ActiveDirectory

$Time = (Get-Date -UFormat "%A, %b %d, %Y %r")
$CertChk = (New-PSSessionOption -SkipCNCheck -SkipCACheck -SkipRevocationCheck)
$Server = "ServerName"
$Desc = "Account Disabled Due to DECOM on $Time"


$SvcAcctCreds = IMPORT-CLIXML "$env:USERPROFILE\svc_acct_corp_creds.xml"
$CorpDesc = Invoke-Command -ComputerName DC -Credential $SvcAcctCreds -UseSSL -SessionOption $CertChk -ScriptBlock {Set-ADComputer $Server -Description $Desc}

$CorpDesc

Open in new window

Avatar of Greg Besso
Greg Besso
Flag of United States of America image

Hi there, I've run into that at one point. I am not sure if it's the only/best way but what I read and then did was to create a filter scriptblock and then pass that along with the function call. Something  like this for example...

$filter = [scriptblock]::Create("SamAccountName -eq `"$SamAccountName`"")
$user = Get-ADUser -Filter $filter -Properties *

Try it out and let us know if that helps. :-)
I think I misunderstood your question actually. I was thinking of another issue I ran into related to passing variables to filters in one-line remote sessions somewhere else. What I think you meant was maybe something like this. Here is one example of how to send your variable from local script to the remote session...

# just a test variable with something to send to the remote system...
$var1 = 'username'

#make the session if you don't have it already...
If (!($sessionAD)) { $sessionAD = New-PSSession -ComputerName 'DCNAMEHERE'}

#use the session you have setup...
Invoke-Command -Session $sessionAD -ScriptBlock {
    # get input from function calling remote session
    Param ($var1)

    Import-Module ActiveDirectory
    $thisUser = Get-ADUser -Identity $var1

} -ArgumentList $var1
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bret Robinson
Bret Robinson

ASKER

Thank you both! Foo, worked perfectly I appreciate the help and the information regarding passing info into the session!