Author Posts

June 18, 2015 at 3:15 pm

I have a script that:
creates directory if it doesn't exists
copies cert with server name to right server
into the right tem directory
then imports it using invoke-command and import-pfxcertificate
then sets the rdp service to use that cert(instead of the default)
something like this:
$certsLocation = "c:\temp"
$servernames=Get-ChildItem $certsLocation |select name |%{$_.name.Split("{.}") |select -First 1}
ForEach ($server in $servernames) {
if(!(Test-Path \\$server\c$\certs)){New-Item -type directory -Path \\$server\c$\certs}
Copy-Item -Path $certsLocation\$server.PFX -Destination \\$server\c$\certs -Force
$data=Invoke-Command -ScriptBlock {Import-PfxCertificate –FilePath C:\certs\'$($server)+".PFX"' cert:\localMachine\my -Password (ConvertTo-SecureString -String "1234" -AsPlainText -Force)} -ComputerName $server
$thumbprint=$data.Thumbprint
$path = (Get-WmiObject -computer adfs1 -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").__path
Set-WmiInstance -Path $path -argument @{SSLCertificateSHA1Hash=$thumbprint
}
}

it seems to break here:
$data=Invoke-Command -ScriptBlock {Import-PfxCertificate –FilePath C:\certs\'$($server)+".PFX"' cert:\localMachine\my -Password (ConvertTo-SecureString -String "1234" -AsPlainText -Force)} -ComputerName $server

with:
The system cannot find the path specified. 0x80070003 (WIN32: 3 ERROR_PATH_NOT_FOUND

now if I run the same command(from same machine im running the script) and I use:
$data=Invoke-Command -ScriptBlock {Import-PfxCertificate –FilePath C:\certs\server1.PFX"' cert:\localMachine\my -Password (ConvertTo-SecureString -String "1234" -AsPlainText -Force)} -ComputerName server1
it works fine.
I can even use -computername $server and it still works fine
so it breaks because of the path(that's what I am guessing)

any ideas what am I missing here?
Thanks in advance

June 18, 2015 at 4:17 pm

Turbo,

The Invoke-Command script block is running in a different session than your main script, so it does not share variables. You have to create the variable within the script block, and you need to pass the value of it in as an argument.

And then because of your single quotes, the $Server variable is not being parsed. Try something like this (untested):

$data = Invoke-Command -ScriptBlock { Param( $Server ); Import-PfxCertificate -FilePath "C:\certs\$server.PFX" cert:\localMachine\my -Password (ConvertTo-SecureString -String "1234" -AsPlainText -Force) } -ComputerName $server -ArgumentList @{ server = $server }

June 18, 2015 at 5:33 pm

Thanks a lot
learned something new:)