将powershell变量放入where对象不返回数据

时间:2018-07-18 21:54:37

标签: function powershell

我正在编写一个脚本,以最终检查一个服务器块中的FriendlyName证书,然后返回并在确认后将其删除。现在,我只是想让最初的检查工作。当前它不返回任何数据。有人可以帮忙吗?

$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

1 个答案:

答案 0 :(得分:1)

正如Mathias R. Jessen所评论的那样,您的findcert函数需要一个证书名称作为参数,并且在调用它时不会传递任何内容,因此它将无法正常运行。

您还试图在远程计算机上的invoke-command中使用本地计算机变量$Certificate,并且远程计算机无法在远程处理中使用该变量。

我用$using:重写了它,它是一种语法,它告诉PS通过远程会话发送值,并使用重命名的变量,以便更清楚地了解哪个部分正在访问哪些变量:

$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