简体   繁体   English

如何基于 function 在 Powershell 中声明一个变量,以便将其作为参数传递给另一个 function?

[英]How to declare a variable in Powershell based on a function in order to pass it as an argument in another function?

I am trying to declare $workbook1 as the current workbook in order to pass it as an argument in another function, but it is not working.我试图将 $workbook1 声明为当前工作簿,以便将其作为参数传递给另一个 function,但它不起作用。 Here is my code:这是我的代码:

Here is my code:这是我的代码:

Function Open-Workbook($path, $file, $excel) {
    try {
        $wb = $excel.Workbooks.Open("${path}${file}")
    }catch{
        echo $error
        $key = 'Open-Workbook';
        $date = Get-Date -Format 'yyyy-MM-dd';
        Log-Error $key $date;
        $error.Clear()
    }
}

Function xlRefresh($wb){
    try{
    $wb.RefreshAll()
    }catch{
         echo $error
         $key = 'Run-xlRefresh';
         $date = Get-Date -Format 'yyyy-MM-dd';
         Log-Error $key $date;
         $error.Clear()
    }
}

$paths = "C:\Users\"
$files = "Detect Scripts.xlsm" 

try{
    $setexcel = New-Object -ComObject Excel.Application
    $setexcel.Visible = $true
    }catch{
        echo $error
        $key = 'Open-Excel';
        $date = Get-Date -Format 'yyyy-MM-dd';
        Log-Error $key $date;
        $error.Clear()
}


$workbook1 = Open-Workbook $paths $files $setexcel
xlRefresh $workbook1

When I run this, I get this error:当我运行它时,出现此错误:

You cannot call a method on a null-valued expression.您不能对空值表达式调用方法。

Thank you谢谢

You didn't actually output the workbook from your first function, therefore you catch nothing in your variable.您实际上并没有 output 来自您的第一个 function 的工作簿,因此您在变量中什么也没发现。 Just write it out at the end.最后写出来就好了。

Function Open-Workbook($path, $file, $excel) {
    try {
        $wb = $excel.Workbooks.Open("${path}${file}")
    }catch{
        echo $error
        $key = 'Open-Workbook';
        $date = Get-Date -Format 'yyyy-MM-dd';
        Log-Error $key $date;
        $error.Clear()
    }
    $wb
}

Or as zett42 commented, you can simply not capture it and write it implicitly或者正如zett42评论的那样,你可以简单地不捕获它并隐式地写它

Function Open-Workbook($path, $file, $excel) {
    try {
        $excel.Workbooks.Open("${path}${file}")
    }catch{
        echo $error
        $key = 'Open-Workbook';
        $date = Get-Date -Format 'yyyy-MM-dd';
        Log-Error $key $date;
        $error.Clear()
    }
}

You need to actually return the value from the function.您需要实际返回function 中的值。

eg return $excel.Workbooks.Open("${path}${file}")例如return $excel.Workbooks.Open("${path}${file}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM