Powershell Get-ChildItem检查文件名不起作用

时间:2015-01-14 16:22:37

标签: powershell get-childitem

我想要做的是查找文件夹中的特定文件,然后检查每个文件的名称,并将其放在另一个文件夹中。以下是我正在尝试做的一个示例:

$FileABackupLoc = "C:\FolderA"
$FileBBackupLoc = "C:\FolderB"

Get-ChildItem -Path $SourceFolder -Include *Membership*.pgp -Name -Recurse | 
%{ 

    Write-Host "Current file: $_"

    if($_ -like '*FileA*')
    {
        [System.IO.FileInfo]$FileADestination = (Join-Path -Path $FileABackupLoc -ChildPath $_.Name.replace(“_”,“\”))
    move-item -Path $_.FullName -Destination $FileADestination.FullName -Verbose
   }

    if($_ -like '*FileB*')
    {
        [System.IO.FileInfo]$FileBDestination = (Join-Path -Path $FileBBackupLoc -ChildPath $_.Name.replace(“_”,“\”))
    move-item -Path $_.FullName -Destination $FileBDestination.FullName -Verbose
   }

}

当我运行代码时,我收到此错误但不明白为什么: 您无法在空值表达式上调用方法。

1 个答案:

答案 0 :(得分:1)

也许试试这个:

Get-ChildItem -Path $SourceFolder -Include *Membership*.pgp -Recurse | % {

if ($_ -like '.*FileA.*')
{
  $FileADestination = Join-Path -Path $FileBBackupLoc -ChildPath (Split-Path -Leaf -Path $_.FullName)
  Move-Item -Path $_.FullName -Destination $FileADestination
}
...

我相信您在原始Get-ChildItem中使用-Name参数可能会妨碍您从文档中获取:

  

-Name

     

仅获取位置中项目的名称。如果将此命令的输出传递给另一个命令,则仅发送项目名称。