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

Welcome Forums General PowerShell Q&A Use function in remote session, return value to local session?

This topic contains 1 reply, has 2 voices, and was last updated by

 
Moderator
3 years, 8 months ago.

  • Author
    Posts
  • #24561

    Participant
    Points: 1
    Rank: Member

    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

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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

The topic ‘Use function in remote session, return value to local session?’ is closed to new replies.