如何使用 PowerShell 循环检查现有文件夹? [英] How to do looping for checking an existing folder with PowerShell?
问题描述
我想根据我的数据决定我需要选择哪个文件夹,然后如果我找不到它,它会显示等待的GUI并循环检查它.我尝试使用此代码,我可以找到该文件夹,但是当我想显示 GUI 时找不到它时,它会返回一些错误.
这就是我检查文件夹的方式
function FIND {Write-Host调用可以调用GUI.ps1脚本的函数"$Path = "D:\进程"写主机开始映射 SSID 并寻找工作"$SSID_Unit = "111dddddfafafesa"尝试{$Path_Job = (Get-Item (Get-ChildItem "$Path\*\SSID_LST" | Select-String -Pattern "$SSID_Unit").Path).Directory.FullName$global:Result = [PSCustomObject]@{存在 = $true文件名 = $Path_Job.FullName尝试 = 1}写入主机作业'$($global:Result.FileName)' 存在.在 $($global:Result.Attempts) 尝试后找到."-前景颜色绿色写主机继续分配的工作"暂停} 抓住 {写主机等待工作"&D:\X\Wait_GUI.ps1 -Path $Path_Job -MaxAttempts 20写入主机在 $($global:Result.Attempts) 尝试后未找到作业."-前景色红色}}找
这是图形界面
参数 ([字符串]$Path = '*.*',[字符串]$MaxAttempts = 5)添加类型 -AssemblyName System.Windows.Forms[System.Windows.Forms.Application]::EnableVisualStyles()# 设置定时器$script:nAttempts = 0$timer = 新对象 System.Windows.Forms.Timer$timer.Interval = 1000 # 1 秒$timer.Add_Tick({$global:Result = $null$script:nAttempts++$Path_Job = Get-Item -Path $Path如果($Path_Job){$global:Result = [PSCustomObject]@{存在 = $true文件名 = $Path_Job.FullName尝试次数 = $script:nAttempts}$timer.Dispose()$Form.Close()}elseif ($script:nAttempts -ge $MaxAttempts) {$global:Result = [PSCustomObject]@{存在 = $false文件名 = ''尝试次数 = $script:nAttempts}$timer.Dispose()$Form.Close()}})添加类型 -AssemblyName System.Windows.Forms[System.Windows.Forms.Application]::EnableVisualStyles()$Form = 新对象 system.Windows.Forms.Form$Form.ClientSize = '617,418'$Form.text = "AutoGM"$Form.BackColor = "#8b572a"$Form.TopMost = $false$Form.WindowState = '最大化'$Label1 = 新对象 system.Windows.Forms.Label$Label1.text = "自动化过程中"$Label1.AutoSize = $true$Label1.width = 25$Label1.height = 10$Label1.Anchor = '上、右、下、左'$Label1.ForeColor = "#ffffff"$Label1.Anchor = "无"$Label1.TextAlign = "MiddleCenter"$Label2 = 新对象 system.Windows.Forms.Label$Label2.text = "等待工作..."$Label2.AutoSize = $true$Label2.width = 25$Label2.height = 10$Label2.ForeColor = "#ffffff"$Label2.Anchor = "无"$Label2.TextAlign = "MiddleCenter"$Form.controls.AddRange(@($Label1,$Label2))[无效]$Form.Show()# 写主机 $Form.Height# 写主机 $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))# 只要对话框可见就启动计时器$Form.Add_Shown({ $timer.Start() })$Form.Visible = $false[无效]$Form.ShowDialog()# 完成后清理$Form.Dispose()
如果没有找到,它返回这个
等待作业尝试 1 次后未找到作业.
并且未显示 GUI
好的,首先,您在代码和 GUI 中对文件和/或目录使用了不同的测试.此外,您使用设置为 $null
值的路径调用 GUI.ps1 文件.
我会把你的代码改成这样:
$Path = "D:\Process\*\SSID_LST\*" # 查找文件的路径$SSID_Unit = "111dddddfafafesa" # 在文件中寻找的搜索模式函数 Test-FileWithGui {[CmdletBinding()]参数([参数(强制= $true,位置= 0)][字符串]$路径,[参数(强制= $true,位置= 2)][字符串]$模式,[int]$MaxAttempts = 5)写主机开始映射 SSID 并寻找工作"# 设置一个空"的 $global:Result 对象以在失败时返回$global:Result = '' |选择对象@{Name = 'Exists';表达式 = {$false}},文件名,目录,@{Name = 'Attempts';表达式 = {1}}# 测试给定的路径是否有效.如果没有,退出函数if (!(Test-Path -Path $Path -PathType Container)) {写警告路径‘$Path’不存在."返回}# 尝试找到包含搜索模式的第一个文件$file = Select-String -Path $Path -Pattern $Pattern -SimpleMatch -ErrorAction SilentlyContinue |选择对象 -First 1如果($文件){$file = Get-Item -Path $file.Path$global:Result = [PSCustomObject]@{存在 = $true文件名 = $file.FullName目录 = $file.DirectoryName尝试 = 1}}别的 {&"D:\GUI.ps1" -Path $Path -Pattern $Pattern -MaxAttempts $MaxAttempts}}#调用可以调用GUI.ps1脚本的函数Test-FileWithGui -Path $Path -Pattern $SSID_Unit -MaxAttempts 20# 显示具有所有属性的 $global:Result 对象$global:结果 |格式列表# 检查全局结果对象如果 ($global:Result.Exists) {写入主机文件 '$($global:Result.FileName)' 存在.在 $($global:Result.Attempts) 尝试后找到."-前景颜色绿色}别的 {写入主机在 $($global:Result.Attempts) 尝试后未找到文件."-前景色红色}
接下来是 GUI 文件.当您现在正在搜索包含一些文本的文件时,您需要第三个参数来调用这个名为 Pattern
的文件.
在 GUI 文件中,我们执行与上面代码完全相同的测试,使用参数 $Pattern
作为搜索字符串:
参数 ([字符串]$路径,[字符串]$模式,[int]$MaxAttempts = 5)添加类型 -AssemblyName System.Windows.Forms[System.Windows.Forms.Application]::EnableVisualStyles()# 设置定时器$script:nAttempts = 0$timer = 新对象 System.Windows.Forms.Timer$timer.Interval = 1000 # 1 秒$timer.Add_Tick({$global:Result = $null$script:nAttempts++# 使用与您在 GUI 之外所做的相同的测试# 尝试找到包含搜索模式的第一个文件$file = Select-String -Path $Path -Pattern $Pattern -SimpleMatch -ErrorAction SilentlyContinue |选择对象 -First 1如果($文件){$file = Get-Item -Path $file.Path$global:Result = [PSCustomObject]@{存在 = $true文件名 = $file.FullName目录 = $file.DirectoryName尝试次数 = $script:nAttempts}$timer.Dispose()$Form.Close()}elseif ($script:nAttempts -ge $MaxAttempts) {$global:Result = [PSCustomObject]@{存在 = $false文件名 = $null目录 = $null尝试次数 = $script:nAttempts}$script:nAttempts = 0$timer.Dispose()$Form.Close()}})$Form = 新对象 system.Windows.Forms.Form$Form.ClientSize = '617,418'$Form.Text = "AutoGM"$Form.BackColor = "#8b572a"$Form.TopMost = $true$Form.WindowState = '最大化'# 我删除了 $Label2 因为它更容易使用# 这里只有一个标签,然后将其停靠以填充.$Label1 = 新对象 system.Windows.Forms.Label$Label1.Text = "在自动化过程中`r`n`r`n等待工作......"$Label1.AutoSize = $false$Label1.Dock = '填充'$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)# 只要对话框可见就启动计时器$Form.Add_Shown({ $timer.Start() })[无效]$Form.ShowDialog()# 完成后清理$Form.Dispose()
测试结果如下
如果在集合中找到文件 MaxAttempts
尝试:
开始映射SSID和找工作存在:真文件名:D:\Process\test\SSID_LST\blah.txt目录:D:\Process\test\SSID_LST尝试:7文件 'D:\Process\test\SSID_LST\blah.txt' 存在.7 次尝试后找到.
未找到文件时:
<块引用>开始映射SSID和找工作存在:错误文件名 :目录 :尝试次数:20尝试 20 次后未找到文件.
如果连文件夹$Path
都没有找到,输出是
开始映射SSID和找工作警告:路径 'D:\Process\*\SSID_LST\*' 不存在.存在:错误文件名 :目录 :尝试:11 次尝试后未找到文件.
希望有帮助
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, I can find the folder, but when I can't find it once I want to show the GUI it returns some error.
This is how I checking the folder
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
This is the 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()
if not found, it return this
Waiting for the jobss
Job not found after 1 attempts.
and the GUI is not shown
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 = "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
}
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
这篇关于如何使用 PowerShell 循环检查现有文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!