Why does Powershell say that my variables are empty or null?

Dear powershell community

I wanted to ask why my Script keeps on saying that these variables are empty or null. the following variables are affected:

$pcname = 'server01'
$RDdestfile = "C:\Scripts\Cert\Certificate_04.pfx"
$ThumbprintPath = 'RDS:\GatewayServer\SSLCertificate\Thumbprint'

As you can see, these Variables clearly have something in them.

Here is where I want to use them:

$RemoteSession = New-PSSession -ComputerName $pcname -Credential $cred
        Invoke-Command -Session $RemoteSession -ScriptBlock {
            Import-PfxCertificate -FilePath $RDdestfile -CertStoreLocation $CertLocation
            $certificate = Get-PfxCertificate -FilePath $RDdestfile
            Import-Module RemoteDesktopServices
            Set-Item -Path $ThumbprintPath -Value $certificate.Thumbprint -ErrorAction Stop
        }

 

I hope you can help me

Greetings

Martin

If you create your variables outside the scriptblock the scriptblock will not see them. To achieve this you can use the scope modifier “Using”. … like this:

$RemoteSession = New-PSSession -ComputerName $pcname -Credential $cred
        Invoke-Command -Session $RemoteSession -ScriptBlock {
            Import-PfxCertificate -FilePath $USING:RDdestfile -CertStoreLocation $CertLocation
            $certificate = Get-PfxCertificate -FilePath $USING:RDdestfile
            Import-Module RemoteDesktopServices
            Set-Item -Path $USING:ThumbprintPath -Value $certificate.Thumbprint -ErrorAction Stop
        }

I assume you will have to use the scope modifer for $CertLocation and $certificate as well.

Thank you for your reply!

I was able to get rid of the Error without putting the scope modifier for $certificate as well.

So thank you again for your help!

[quote quote=249062]If you create your variables outside the scriptblock the scriptblock will not see them. To achieve this you can use the scope modifier “Using”. …. like this:

$RemoteSession = New-PSSession -ComputerName $pcname -Credential $cred
Invoke-Command -Session $RemoteSession -ScriptBlock {
Import-PfxCertificate -FilePath $USING:RDdestfile -CertStoreLocation $CertLocation
$certificate = Get-PfxCertificate -FilePath $USING:RDdestfile
Import-Module RemoteDesktopServices
Set-Item -Path $USING:ThumbprintPath -Value $certificate.Thumbprint -ErrorAction Stop
}
I assume you will have to use the scope modifer for $CertLocation and $certificate as well.

[/quote]
Can I somehow mark this question as the Answer?

That’s unnecessary. A simple “Thanks” as your last reply will do the job. :wink: