在PowerShell7.0中执行时出错:您无法在空值表达式上调用方法

问题描述

我尝试使用Powershell 7版本中的ForEach-Object -Parallel选项示例程序来并行执行Excel减法运算。

Param(
   [Parameter(Position=1)]
   [string]$input_filename,[Parameter(Position=2)]
   [string]$output_filename
)

# Instantiate Excel instnace
$excel_test = New-Object -ComObject Excel.Application

# Make the instance visiable to work with it
$excel_test.visible = $False

# Catch alerts
$excel_test.displayAlerts = 'False'

# Add in the file source
$workbook = $excel_test.Workbooks.Add($input_filename)

# Choose a sheet in the workbook
$Sheet = $excel_test.Worksheets.Item(1)

$totalNoOfRecords = ($Sheet.UsedRange.Rows).count

# Assign the formula to the target variable
$Sheet.Cells.Item(1,3) = "Substraction"

Measure-Command {

    2..$totalNoOfRecords | ForEach-Object -Parallel {

        # Assign a formula to the target variable
        $i = $_
        $strFormula_1 =  "=(A$($i)- B$($i))"
        Write-Host $strFormula_1
        Write-Host $i
        $Sheet.Cells.Item($i,3) = "=(A$($i) - B$($i))"
    } -ThrottleLimit 3
}

# Exit the XLS
$workbook.SaveAs($output_filename)  
$workbook.close($false)
$excel_test.Quit()

但是,它会引发如下错误

InvalidOperation:
Line |
   8 |          $Sheet.Cells.Item($i,3) = "=(A$($i) - B$($i))"
     |                                                   ~~
     | You cannot call a method on a null-valued expression.

如何在此处解决错误

解决方法

将$ using:sheet放入循环中,就像处理作业和invoke-command一样。