【问题标题】:-Filter not working when input file has more than once line [duplicate]-当输入文件有不止一次的行时过滤器不起作用[重复]
【发布时间】:2017-05-02 10:25:24
【问题描述】:

我有这个脚本,它可以 100% 工作,但仅适用于单个项目

我想循环脚本并从 txt 文件中获取内容 您会看到,我的 scipt 搜索特定文件并将其复制到与该文件同名的现有文件夹中。 所以我想要的是从 2 个 txt 文件中获取文件夹的名称和文件的名称并循环脚本

我已经设法从 txt 文件中获取内容,但是如果我在我的 txt 文件中添加带有新值的第二行,我将无法循环脚本。 我总是得到错误:

Get-ChildItem:无法将“System.Object[]”转换为类型 参数“Filter”需要“System.String”。指定的方法是 不支持d。

好的,这是我的脚本:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
# Setup source and destination paths
$Src = '\\192.168.0.216\home\'
$Dst = 'C:\TEST\120629B\'

# Wildcard for filter
$Extension = '120629B.jpg'

# Get file objects recursively
Get-ChildItem -Path $Src -Filter $Extension -Recurse |
    # Skip directories, because XXXReadMe.txt is a valid directory name
    Where-Object {!$_.PsIsContainer} |
        # For each file
        ForEach-Object {

            # If file exist in destination folder, rename it with directory tag
            if(Test-Path -Path (Join-Path -Path $Dst -ChildPath $_.Name))
            {
                # Get full path to the file without drive letter and replace `\` with '-'
                # [regex]::Escape is needed because -replace uses regex, so we should escape '\'
                $NameWithDirTag = (Split-Path -Path $_.FullName -NoQualifier)  -replace [regex]::Escape('\'), '-'

                # Join new file name with destination directory
                $NewPath = Join-Path -Path $Dst -ChildPath $NameWithDirTag
            }
            # Don't modify new file path, if file doesn't exist in target dir
            else
            {
                $NewPath = $Dst
            }

            # Copy file
            Copy-Item -Path $_.FullName -Destination $NewPath
        }

好的,这就是我所做的更改和工作,但只使用一条记录

$Src = '\\192.168.0.216\home\'
$Dst = Get-Content 'C:\TEST\path.txt'

# Wildcard for filter
$Extension = Get-Content 'C:\TEST\file.txt'

【问题讨论】:

    标签: loops powershell


    【解决方案1】:

    错误消息告诉您问题所在,您不能使用数组作为get-childitem 的过滤器。您可能可以在 foreach 循环内嵌套一个 where-object 过滤器,但完成您尝试做的最简单的方法是循环通过您的扩展过滤器,然后在该循​​环内运行您的循环。所以将整个Get-ChildItem 循环包装在Foreach 循环中,如下所示。

    Foreach($e in $extension){
      *Your Code Here*
    }
    

    当然,请确保将 Get-ChildItem-Filter 参数从 $Extension 更改为 $e

    【讨论】:

      【解决方案2】:

      就像错误所说,-Filter 需要一个字符串。 Get-Content 将为多行的文件返回一个对象数组。

      由于您也在使用-Recurse,因此请考虑使用-Include 而不是-Filter,因为它支持字符串数组。这应该无需更改您的输入文件或添加任何其他后处理。来自 [MSDN]

      字符串数组 的形式指定此 cmdlet 包含在操作中的一个或多个项目。此参数的值限定了 Path 参数。输入路径元素或模式,例如 *.txt。允许使用通配符。

      Get-ChildItem -Path $Src -Include $Extension -Recurse 
      

      注意:

      Include 参数仅在命令包含 Recurse 参数或路径指向目录的内容时才有效,例如 C:\Windows*,其中通配符指定 C:\Windows 目录的内容。

      -Exclude 也一样

      【讨论】:

        猜你喜欢
        • 2013-06-29
        • 1970-01-01
        • 2020-08-04
        • 2015-02-05
        • 1970-01-01
        • 2023-01-13
        • 1970-01-01
        • 2018-07-22
        • 1970-01-01
        相关资源
        最近更新 更多