Use function in remote session, return value to local session?

This topic contains 1 reply, has 2 voices, and was last updated by  Daniel Krebs 2 years, 6 months ago.

  • Author
    Posts
  • #24561

    Jason McMahan
    Participant

    I had an interesting problem today I was not quite sure how to address.
    I am manipulating certificates in the localmachine store on a remote server and would like to use a function from the local session within that remote session.
    I am using write-processlog to create a log of the commands as they are executed.

    Function write-Processlog
    {	param([string]$logstring)
        Write-Host $logstring
    	Add-Content -LiteralPath $certCreationLog $logstring
    }
    

    Then I thought I would like to use this function with in my invoke-command block to return the certificates I remove.

            Invoke-Command -ComputerName $FQDN -ScriptBlock {
            param ($FQDN) $certs = Get-ChildItem cert:/localmachine/my | Where-Object {$_.Subject -notmatch $FQDN}
                foreach($cert in $certs){
                    $store = Get-Item $cert.PSParentPath
                    $store.Open('ReadWrite')
                    $store.Remove($cert)
                    $store.Close()
                }
            } -ArgumentList $FQDN -ErrorAction Stop
    

    Any help returning $cert that is removed would be helpful.

  • #24565

    Daniel Krebs
    Moderator

    Hi Jason,

    Returning objects from a remote computer is really easy.

    $RemovedCertInformationList = Invoke-Command -ComputerName $FQDN -ScriptBlock {
            param ($FQDN) $certs = Get-ChildItem cert:/localmachine/my | Where-Object {$_.Subject -notmatch $FQDN}
                foreach($cert in $certs){
                    $store = Get-Item $cert.PSParentPath
                    $store.Open('ReadWrite')
                    $store.Remove($cert)
                    $store.Close()
    
                    Write-Output -InputObject $cert # Output certificate object to the pipeline on the remote computer
                }
            } -ArgumentList $FQDN -ErrorAction Stop
    

    Best,
    Daniel

You must be logged in to reply to this topic.