Fixxer
Fixxer

Reputation: 93

powershell variable into where-object does not return data

I am writing a script to ultimately check a block of servers for a certificate by FriendlyName and then go back and delete them once confirmed. Right now I am just trying to get the initial check to work. Currently it is not returning any data. Can anyone help?

$ContentsPath = "C:\Servers.txt"
$Servers = Get-Content $ContentsPath
$CertDeletionFile = "C:\CertsDeleted.csv"
$Today = Get-Date

$Certificate = Read-Host -Prompt "What certificate would you like to 
REMOVE?"
write-host $Certificate

function findCert {
param ([string]$Certificate)
Invoke-Command -ComputerName $Servers -ScriptBlock {Get-Childitem -Path 
Cert:LocalMachine\My | where {$_.friendlyname -eq $Certificate } | Select- 
Object -Property FriendlyName }
}
findCert

Upvotes: 0

Views: 361

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

As Mathias R. Jessen comments, your findcert function needs a certificate name as a parameter, and you aren't passing anything when you call it, so it won't run properly.

You're also trying to use a local computer variable $Certificate, on a remote computer inside an invoke-command, and the remote computer can't get to that variable across the remoting.

I've rewritten it, with $using: which is a syntax that tells PS to send the value over the remoting session, and with renamed variables so it's more clear which part is accessing which variables:

$ContentsPath = 'C:\Servers.txt'
$Servers = Get-Content -LiteralPath $ContentsPath
$CertDeletionFile = 'C:\CertsDeleted.csv'
$Today = Get-Date

$typedCertificateName = Read-Host -Prompt "What certificate would you like to 
REMOVE?"
write-host $typedCertificateName

function findCert {
    param ([string]$Certificate)

    Invoke-Command -ComputerName $Servers -ScriptBlock {

        Get-Childitem -Path  Cert:LocalMachine\My |
            where-Object {$_.friendlyname -eq $using:Certificate } |
            Select-Object -Property FriendlyName
    }
}

findCert -Certificate $typedCertificateName

Upvotes: 1

Related Questions