How to do looping for checking an existing folder with PowerShell?

前端 未结 1 1569
不思量自难忘°
不思量自难忘° 2021-01-16 16:37

I want to decide which folder that I need to choose based on my data, then if I can\'t find it, it will show the GUI for waiting and do looping to check it. I try this code,

1条回答
  •  情话喂你
    2021-01-16 17:08

    Ok, first of all, you are using different tests for the file and/or directory in the code and in the GUI. Furthermore, you call the GUI.ps1 file with a path set to a $null value.

    I would change your code to something like this:

    $Path      = "D:\Process\*\SSID_LST\*"  # the path to look for files
    $SSID_Unit = "111ffffffffdfafafesa"         # 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
    }
    

    Next the GUI file. As you are now searching for a file that contains some text, you need a third parameter to call this named Pattern.

    Inside the GUI file we perform the exact same test as we did in the code above, using the parameter $Pattern as search string:

    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()
    

    The results during testing came out like below

    If the file was found within the set MaxAttempts tries:

    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.
    

    When the file was NOT found:

    Starting Mapping SSID and Finding Job
    
    
    Exists    : False
    FileName  : 
    Directory : 
    Attempts  : 20
    
    
    
    File not found after 20 attempts.
    

    If even the folder $Path was not found, the output is

    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.
    

    Hope that helps

    0 讨论(0)
提交回复
热议问题