将CSV信息导入powershell脚本

时间:2018-01-04 18:51:56

标签: powershell csv

我正在尝试运行一个脚本,将CSV信息导入PowerShell以卸载远程计算机上的软件。 CSV文件包含主机名,IP地址和已安装应用程序名称等信息。 CSV文件看起来像这样(抱歉输入错误):

Name,Serial Number,IP Address,MAC Address,Installed Applications
computer1,ABC123,1.1.1.1,12:34:45:67:89,Adobe Air

基本上,我们的想法是卸载"已安装的应用程序" (在这个例子中为Adobe Air)在" Name" (计算机主机名)。

PowerShell脚本:

$csv = Import-Csv C:\path\report.csv
$DisplayName = $csv."Installed Applications"
$path = Split-Path -Path $MyInvocation.MyCommand.Path
$computers = $csv.Name

foreach ($server in $computers) {
    $app = Get-WmiObject -Class Win32_Product -ComputerName $server |
           Where-Object {$_.DisplayName -match $csv."Installed Applications"}
     $pathobj = New-Object -TypeName PSobject
     $pathobj | Add-Member -MemberType NoteProperty -Name Computername -Value $server.ToUpper()
     $pathobj | Add-Member -MemberType NoteProperty -Name Software -Value $csv."Installed Applications"
     $var = ($app.Uninstall()).ReturnValue

    if($var -eq 0) {
        $pathobj | Add-Member -MemberType NoteProperty -Name Status -Value "Successfully Uninstalled"
        $pathobj | Add-Member -MemberType NoteProperty -Name Date -Value $(Get-Date)
    } else {
        $pathobj | Add-Member -MemberType NoteProperty -Name Status -Value "Unable to uninstall"
        $pathobj | Add-Member -MemberType NoteProperty -Name Date -Value $(Get-Date)
    }
    #Write-Output $pathobj | Export-Csv "$path\ObsoleteStatus.csv" -NoTypeInformation -Append
}

当我执行它时,它总是给我:

You cannot call a method on a null-valued expression.
At C:\Users\sbellec\Desktop\test5.ps1:18 char:28
+      $var = ($app.Uninstall <<<< ()).ReturnValue
    + CategoryInfo          : InvalidOperation: (Uninstall:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

我尝试了不同的方法来修复它而没有结果。关于我做错了什么想法?

1 个答案:

答案 0 :(得分:0)

$computers = $csv.Name

仅选择一列,因此当您运行foreach时,您将在此列中进行迭代;

$_.DisplayName -match $csv."Installed Applications"

以相同的方式检查天文件DisplayName是否与已安装的应用程序列匹配,因此您在那里没有得到任何明智的结果。

你只需要在整个csv数组上运行你的foreach

foreach ($row in $csv) {

然后使用$ row.Name和$ row。&#34;已安装的应用程序&#34;对于与同一服务器行对应的值。