Double hop and argumentlist

Hi guys. I can’t work out how to pass a variable into a new session that also contains a invoke-command.

I have a script and when it runs its triggers as NT Authority\System, so I need to create a new session with creds to connect to another machine and then use invoke-command.

But I can’t work out how to get my variables inside that session.

$ComputerName = "CompName"
$CMLogFile = 'C:\CMlog.txt'
$password = ConvertTo-SecureString "PlainTextForTest" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("Domain\User.Name", $password)
$CMsession = New-PSSession -ConfigurationName Microsoft.PowerShell32 -ComputerName 'SCCMserver' -Credential $Cred -Name SCCMsession
Invoke-Command -Session $CMsession -ScriptBlock {
Import-Module"$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
cd 001:\
Get-CMDevice-Name $using:ComputerName
} -ArgumentList $ComputerName, $CollectionID, $SoftwareName, $CMLogFile | Out-File -FilePath $CMLogFile -Append
 

 

I should say that hard-coding the values works.

Also, I am running invoke command against an SCCM server, but the console is available on the local machine but when I remove the - computername argument from the new-pssession, it fails with auth errors… would be good to keep it local if I could.

Try this:

$ComputerName = "CompName"
$CMLogFile = 'C:\CMlog.txt'
$password = ConvertTo-SecureString "PlainTextForTest" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("Domain\User.Name", $password)
$CMsession = New-PSSession -ConfigurationName Microsoft.PowerShell32 -ComputerName 'SCCMserver' -Credential $Cred -Name SCCMsession
Invoke-Command -Session $CMsession -ScriptBlock {
param($computername, $collectionID, $softwarename, $cmlogfile)
Import-Module"$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
cd 001:\
Get-CMDevice-Name $using:ComputerName
} -ArgumentList $ComputerName, $CollectionID, $SoftwareName, $CMLogFile | Out-File -FilePath $CMLogFile -Append

 

The first thing I see is that you need to create a param block inside the Invoke-Command if you are using the ArgumentList parameter. The variables inside the param block also have to be listed in the order of the ArgumentList.

Invoke-Command -Session $CMsession -ScriptBlock {
    param ($ComputerName, $CollectionID, $SoftwareName, $CMLogfile)
 
    
} -ArgumentList $ComputerName, $CollectionID, $SoftwareName, $CMLogFile 

Thanks John! That was exactly it.

Also, turns out that Get-CMdevice fails if you use FQDN so had to trim down to just the name which caught me off guard.

Glad that helped.

Thanks Josh but I had just had to add a Param block. No need to use $using:Varible either.