PowerShell 将对象附加到变量列表

Scr*_*ese 1 variables powershell append

对 PowerShell 相当陌生,想要了解如何将对象附加到变量列表。以下是错误消息:

Method invocation failed because [System.IO.FileInfo] does not contain a method named 'op_Addition'.
At C:\Users\Username\Desktop\Sandbox\New folder\BoxProjectFiles.ps1:117 char:4
+             $MechDWGFile += $file
+             ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Run Code Online (Sandbox Code Playgroud)

和代码:

LogWrite "`n-------------Mechanical Drawing(s)------------"
foreach ($file in $MechDWGList)
{
    # Where the file name contains one of these filters
    foreach($filter in $MechDWGFilterList)
    {
        if($file.Name -like $filter)
        {
            $MechDWGFile += $file # this is where the error is happening, so I know it is probably something simple
            LogWrite $file.FullName
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正在使用PowerShell 5.1和Windows 10操作系统。

有人可以帮助我理解我的语法有什么问题吗?

Mat*_*sen 7

根据错误消息,$MechDWGFile已包含单个对象 -或[FileInfo]返回的对象类型。Get-ItemGet-ChildItem

+=运算符在 PowerShell 中重载,这意味着它的行为取决于左侧对象的类型$MechDWGFile- 在本例中包含一个[FileInfo]对象。

$file也包含这样的对象,但[FileInfo] + [FileInfo]没有任何意义,这就是您看到错误的原因。

要使该运算符起作用,您需要使用数组子表达式运算+=符创建一个数组:@()

$MechDWGFile = @()

# ...

# This now works
$MechDWGFile += $file
Run Code Online (Sandbox Code Playgroud)

如果您已使用或 的$MechDWGFile输出进行初始化,只需将现有管道嵌套在 中:Get-ItemGet-ChildItem@()

# `Get-ChildItem |Select -First 1` will only output 1 object, 
# but the @(...) makes PowerShell treat it as a 1-item array
# which in turn allows you to use `+=` later
$MechDWGFile = @(Get-ChildItem -Recurse -File |Select -First 1)
Run Code Online (Sandbox Code Playgroud)