Powershell - 如果文件夹不存在则跳过

Powershell - Skip folder if it doesn't exist

我想通过右键单击 .PS1 文件 -> 运行 使用 PowerShell 来 运行 PowerShell 脚本。问题是 $srcRoot 包含三个不同的父目录,其中一个、一些或 none 可能存在于 'C:\parentfolder5.5\web\','C:\parentfolder7.0\web\', and/or 'C:\parentfolder8.0\web\'。但是,运行直接在 PowerShell 终端中运行脚本似乎适用于确实存在的父文件夹,即使对于不存在的父文件夹会弹出错误。

目标是根据确实存在的父目录继续 运行ning 脚本,目前看起来 .PS1 文件在查看第一项后停止$srcRoot 列表。以下是正在处理的代码:

$filterLists = '*overview*', '*summary*', '*home*', '*floor*', '*flr*', '*level*', '*lvl*', '*roof*', '*basement*', '*first*', '*second*', '*third*', '*fourth*'

$srcRoot = 'C:\parentfolder5.5\web\','C:\parentfolder7.0\web\','C:\parentfolder8.0\web\'
$dstRoot = $MyInvocation.MyCommand.Path
    
$params = @{
    Path      = LiteralPath      = $srcRoot |Where-Object { Test-Path -LiteralPath $_ -PathType Container }
    Filter    = 'views'
    Recurse   = $true
    Directory = $true
}

# All folders under `$srcRoot` with name 'views'
$viewsFolders = Get-ChildItem @params #this line is where the issue 
seems to start when Right-clicking -> Run with PowerShell
$params.LiteralPath = $viewsFolders.FullName
$params.Filter = 'graphics'
# All folders under `$viewsFolders` with name 'graphics'
$graphicsFolders = Get-ChildItem @params
$params.Remove('Directory')
$params.LiteralPath = $graphicsFolders.FullName
$params.File = $true # Only search for Files
$params.Force = $true
$params.Remove('Filter')

# All files under `$graphicsFolders`
foreach($file in Get-ChildItem @params)
{
    # Where the file name contains one of these filters
    foreach($filter in $filterLists)
    {
        if($file.Name -like $filter)
        {
            #$file
            Copy-Item -Path $($file.FullName) -Destination $dstRoot
            # if you want to stop at the first finding
            # add `break` here
        }
    }
}

将不胜感激!

您可以使用Where-Object 来过滤路径列表。使用Test-Path测试每个是否存在并且是一个目录路径:

$params = @{
    LiteralPath = $srcRoot |Where-Object { Test-Path -LiteralPath $_ -PathType Container }
    Filter      = 'views'
    Recurse     = $true
    Directory   = $true
}

# this will only attempt directory paths that actually exist now
$viewsFolders = Get-ChildItem @params

注意:使用上面的 LiteralPath(而不是 Path)是有意的 - 使用 Path 将导致 PowerShell 尝试扩展像 ?*[abc] 这样的通配符,而 -LiteralPath 只使用确切的 file/folder 名称。