如何使用PowerShell循环检查现有文件夹?

时间:2019-08-14 02:46:42

标签: powershell

我想根据数据确定需要选择的文件夹,然后,如果找不到它,它将显示GUI等待并循环执行检查。我尝试使用此代码,可以找到该文件夹​​,但是当我想显示GUI时找不到它时,它将返回一些错误。

这就是我检查文件夹的方式

function FIND {
    Write-Host "call the function that can call the GUI.ps1 script"

        $Path = "D:\Process"
        Write-Host "Starting Mapping SSID and Finding Job"
        $SSID_Unit = "111dddddfafafesa"

        Try{
            $Path_Job = (Get-Item (Get-ChildItem "$Path\*\SSID_LST" | Select-String -Pattern "$SSID_Unit").Path).Directory.FullName

            $global:Result = [PSCustomObject]@{
                Exists   = $true
                FileName = $Path_Job.FullName
                Attempts = 1
            }
            Write-Host "Job'$($global:Result.FileName)' Exists. Found after $($global:Result.Attempts) attempts." -ForegroundColor Green
            Write-Host "Continue to Assigned Job"
            Pause
        } Catch {
            Write-Host "Waiting for the jobss"
            & D:\X\Wait_GUI.ps1  -Path $Path_Job -MaxAttempts 20
            Write-Host "Job not found after $($global:Result.Attempts) attempts." -ForegroundColor Red

        }   
    }
    FIND

这是GUI

    Param (   
        [string]$Path = '*.*',
        [string]$MaxAttempts = 5
    ) 

    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.Application]::EnableVisualStyles()

    # set things up for the timer
    $script:nAttempts = 0
    $timer = New-Object System.Windows.Forms.Timer
    $timer.Interval = 1000  # 1 second
    $timer.Add_Tick({
        $global:Result = $null
        $script:nAttempts++
        $Path_Job = Get-Item -Path $Path
        if ($Path_Job) {
            $global:Result = [PSCustomObject]@{
                Exists   = $true
                FileName = $Path_Job.FullName
                Attempts = $script:nAttempts
            }
            $timer.Dispose()
            $Form.Close()
        }
        elseif ($script:nAttempts -ge $MaxAttempts) {
            $global:Result = [PSCustomObject]@{
                Exists   = $false
                FileName = ''
                Attempts = $script:nAttempts
            }
            $timer.Dispose()
            $Form.Close()
        }
    })

    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.Application]::EnableVisualStyles()

    $Form                            = New-Object system.Windows.Forms.Form
    $Form.ClientSize                 = '617,418'
    $Form.text                       = "AutoGM"
    $Form.BackColor                  = "#8b572a"
    $Form.TopMost                    = $false
    $Form.WindowState                = 'Maximized'

    $Label1                          = New-Object system.Windows.Forms.Label
    $Label1.text                     = "UNDER AUTOMATION PROCESS"
    $Label1.AutoSize                 = $true
    $Label1.width                    = 25
    $Label1.height                   = 10
    $Label1.Anchor                   = 'top,right,bottom,left'

    $Label1.ForeColor                = "#ffffff"
    $Label1.Anchor                   = "None"
    $Label1.TextAlign                = "MiddleCenter"

    $Label2                          = New-Object system.Windows.Forms.Label
    $Label2.text                     = "Waiting for the job..."
    $Label2.AutoSize                 = $true
    $Label2.width                    = 25
    $Label2.height                   = 10

    $Label2.ForeColor                = "#ffffff"
    $Label2.Anchor                   = "None"
    $Label2.TextAlign                = "MiddleCenter"

    $Form.controls.AddRange(@($Label1,$Label2))

    [void]$Form.Show()
    # Write-Host $Form.Height
    # Write-Host $Form.Width

    $Label1.location = New-Object System.Drawing.Point(($Form.Width*0.35), ($Form.Height*0.4))
    $Label2.location = New-Object System.Drawing.Point(($form.Width*0.43), ($Form.Height*0.5))

    $L_S = (($Form.Width/2) - ($Form.Height / 2)) / 15
    $Label1.Font = "Microsoft Sans Serif, $L_S, style=Bold"
    $Label2.Font = "Microsoft Sans Serif, $L_S, style=Bold"

    $Form.controls.AddRange(@($Label1,$Label2))
    # start the timer as soon as the dialog is visible
    $Form.Add_Shown({ $timer.Start() })

    $Form.Visible = $false
    [void]$Form.ShowDialog()

    # clean up when done
    $Form.Dispose()

如果找不到,则返回此

    Waiting for the jobss
    Job not found after 1 attempts.

并且未显示GUI

1 个答案:

答案 0 :(得分:4)

好吧,首先,您正在代码和GUI中对文件和/或目录使用不同的测试。此外,您使用设置为$null值的路径调用GUI.ps1文件。

我会将您的代码更改为以下内容:

$Path      = "D:\Process\*\SSID_LST\*"  # the path to look for files
$SSID_Unit = "111dddddfafafesa"         # the Search pattern to look for inside the files

function Test-FileWithGui {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Path,
        [Parameter(Mandatory = $true, Position = 2)]
        [string]$Pattern,
        [int]$MaxAttempts = 5
    )

    Write-Host "Starting Mapping SSID and Finding Job"

    # set up an 'empty' $global:Result object to return on failure
    $global:Result = '' | Select-Object @{Name = 'Exists'; Expression = {$false}}, FileName, Directory, @{Name = 'Attempts'; Expression = {1}}

    # test if the given path is valid. If not, exit the function
    if (!(Test-Path -Path $Path -PathType Container)) {
        Write-Warning "Path '$Path' does not exist."
        return
    }
    # try and find the first file that contains your search pattern
    $file = Select-String -Path $Path -Pattern $Pattern -SimpleMatch -ErrorAction SilentlyContinue | Select-Object -First 1

    if ($file) {
        $file = Get-Item -Path $file.Path

        $global:Result = [PSCustomObject]@{
            Exists    = $true
            FileName  = $file.FullName
            Directory = $file.DirectoryName
            Attempts  = 1
        }
    }
    else {
        & "D:\GUI.ps1" -Path $Path -Pattern $Pattern -MaxAttempts $MaxAttempts
    }
}

# call the function that can call the GUI.ps1 script
Test-FileWithGui -Path $Path -Pattern $SSID_Unit -MaxAttempts 20

# show the $global:Result object with all properties
$global:Result | Format-List

# check the Global result object
if ($global:Result.Exists) {
    Write-Host "File '$($global:Result.FileName)' Exists. Found after $($global:Result.Attempts) attempts." -ForegroundColor Green
}
else {
    Write-Host "File not found after $($global:Result.Attempts) attempts." -ForegroundColor Red
}

接下来是GUI文件。 现在,当您搜索包含一些文本的文件时,您需要第三个参数来调用名为Pattern的文件。

在GUI文件中,我们使用参数$Pattern作为搜索字符串,执行与上述代码完全相同的测试:

Param (   
    [string]$Path,
    [string]$Pattern,
    [int]$MaxAttempts = 5
) 

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

# set things up for the timer
$script:nAttempts = 0
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 1000  # 1 second
$timer.Add_Tick({
    $global:Result = $null
    $script:nAttempts++

    # use the same test as you did outside of the GUI
    # try and find the first file that contains your search pattern
    $file = Select-String -Path $Path -Pattern $Pattern -SimpleMatch -ErrorAction SilentlyContinue | Select-Object -First 1

    if ($file) {
        $file = Get-Item -Path $file.Path

        $global:Result = [PSCustomObject]@{
            Exists    = $true
            FileName  = $file.FullName
            Directory = $file.DirectoryName
            Attempts  = $script:nAttempts
        }
        $timer.Dispose()
        $Form.Close()
    }
    elseif ($script:nAttempts -ge $MaxAttempts) {
        $global:Result = [PSCustomObject]@{
            Exists    = $false
            FileName  = $null
            Directory = $null
            Attempts  = $script:nAttempts
        }
        $script:nAttempts = 0
        $timer.Dispose()
        $Form.Close()
    }
})

$Form             = New-Object system.Windows.Forms.Form
$Form.ClientSize  = '617,418'
$Form.Text        = "AutoGM"
$Form.BackColor   = "#8b572a"
$Form.TopMost     = $true
$Form.WindowState = 'Maximized'

# I have removed $Label2 because it is easier to use 
# just one label here and Dock it to Fill.
$Label1           = New-Object system.Windows.Forms.Label
$Label1.Text      = "UNDER AUTOMATION PROCESS`r`n`r`nWaiting for the job..."
$Label1.AutoSize  = $false
$Label1.Dock      = 'Fill'
$Label1.TextAlign = "MiddleCenter"
$Label1.ForeColor = "#ffffff"

$L_S = (($Form.Width/2) - ($Form.Height / 2)) / 10
$Label1.Font = "Microsoft Sans Serif, $L_S, style=Bold"

$Form.controls.Add($Label1)

# start the timer as soon as the dialog is visible
$Form.Add_Shown({ $timer.Start() })

[void]$Form.ShowDialog()

# clean up when done
$Form.Dispose()

测试期间的结果如下所示

如果在集合MaxAttempts中找到了该文件,则尝试:

Starting Mapping SSID and Finding Job


Exists    : True
FileName  : D:\Process\test\SSID_LST\blah.txt
Directory : D:\Process\test\SSID_LST
Attempts  : 7



File 'D:\Process\test\SSID_LST\blah.txt' Exists. Found after 7 attempts.

找不到文件时:

Starting Mapping SSID and Finding Job


Exists    : False
FileName  : 
Directory : 
Attempts  : 20



File not found after 20 attempts.

如果甚至找不到文件夹$Path,则输出为

Starting Mapping SSID and Finding Job
WARNING: Path 'D:\Process\*\SSID_LST\*' does not exist.


Exists    : False
FileName  : 
Directory : 
Attempts  : 1



File not found after 1 attempts.

希望有帮助