Powershell 如果文件夹存在,则显示以下消息

Powershell 如果文件夹存在,则显示以下消息,powershell,Powershell,我有一个问题。我不明白我做错了什么,我写了下面的脚本来告诉我文件夹是否存在以显示消息,但它现在正在显示它 If (Test-Path -path ($LabServer + $CaseName) -PathType Container){ Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.MessageBox]::Show('Folder name exists,

我有一个问题。我不明白我做错了什么,我写了下面的脚本来告诉我文件夹是否存在以显示消息,但它现在正在显示它

If (Test-Path -path ($LabServer + $CaseName) -PathType Container){
             Add-Type -AssemblyName System.Windows.Forms
             [System.Windows.Forms.MessageBox]::Show('Folder name exists, please enter a new name')
脚本应该在特定位置创建多个文件夹。我想检查文件夹名称(案例名称)是否已经存在,如果已经存在,请不要使用相同的名称创建文件夹,但脚本将继续并创建文件夹和子文件夹

这是完整的脚本。 谢谢你的帮助

# Load required assemblies
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

# Drawing form and controls
$CreateFolder = New-Object System.Windows.Forms.Form
    $CreateFolder.Text = "Create Multiple Custodian Folders"
    $CreateFolder.Size = New-Object System.Drawing.Size(350,415)
    $CreateFolder.FormBorderStyle = "FixedDialog"
    $CreateFolder.TopMost = $true
    $CreateFolder.MaximizeBox = $false
    $CreateFolder.MinimizeBox = $false
    $CreateFolder.ControlBox = $true
    $CreateFolder.StartPosition = "CenterScreen"
    $CreateFolder.Font = "Segoe UI"


#======================== CASE NAME ========================#
# adding a label to my form
$label_message = New-Object System.Windows.Forms.Label
    $label_message.Location = New-Object System.Drawing.Size(20,8)
    $label_message.Size = New-Object System.Drawing.Size(100,15)
    $label_message.Text = "Case Name"
    $CreateFolder.Controls.Add($label_message)    
# CaseName    
    $CaseName = New-Object System.Windows.Forms.TextBox
    $CaseName.Location = New-Object System.Drawing.Size(20,30)
    $CaseName.Size = New-Object System.Drawing.Size(300,25)
    $CaseName.ScrollBars = "Vertical"
    $CreateFolder.Controls.Add($CaseName)


#======================== DROPBOX ========================#
$label_messageCombobox = New-Object System.Windows.Forms.Label
    $label_messageCombobox.Location = New-Object System.Drawing.Size(20,60)
    $label_messageCombobox.Size = New-Object System.Drawing.Size(100,15)
    $label_messageCombobox.Text = "Pick a Server"
    $CreateFolder.Controls.Add($label_messageCombobox)    

$DropdownBox = New-Object System.Windows.Forms.ComboBox
    $DropdownBox.Location = New-Object System.Drawing.Size(20,80)
    $DropdownBox.Size = New-Object System.Drawing.Size(300,15)
    $DropdownBox.Height = 200
    $Dropdownbox.DropDownStyle = "DropDownList"
    $CreateFolder.Controls.Add($DropdownBox)
    
    $Servers = @("Lab Machine 40","Lab Machine 45","Lab Machine 50","Lab Machine 55")


    foreach($Server in $Servers){
        $DropdownBox.Items.Add($Server) | Out-Null
    }
#======================== FUNCTION TO GET SERVER ========================#
Function Get-Server(){
    $SelectedServer = $DropdownBox.SelectedItem.ToString()

    if($SelectedServer -eq "Lab Machine 50") {
        $Script:LabServer = Set-Location "\\Server50\K$" -PassThru
    }
    elseif($SelectedServer -eq "Lab Machine 55") {
        $Script:LabServer = Set-Location "\\Server55\K$" -PassThru
    }
    elseif($SelectedServer -eq "Lab Machine 40") {
        $Script:LabServer = Set-Location "\\Server40\K$" -PassThru
    }
    elseif($SelectedServer -eq "Lab Machine 45") {
        $Script:LabServer = Set-Location "\\Server45\K$" -PassThru
    }
}

#======================== INPUTBOX ========================#
$label_message2 = New-Object System.Windows.Forms.Label
    $label_message2.Location = New-Object System.Drawing.Size(20,110)
    $label_message2.Size = New-Object System.Drawing.Size(100,15)
    $label_message2.Text = "Custodian Names"
    $CreateFolder.Controls.Add($label_message2)    
    
# Inputbox    
    $Inputbox = New-Object System.Windows.Forms.TextBox
    $Inputbox.Multiline = $True;
    $Inputbox.Location = New-Object System.Drawing.Size(20,130)
    $Inputbox.Size = New-Object System.Drawing.Size(300,200)
    $Inputbox.ScrollBars = "Vertical"
    $CreateFolder.Controls.Add($Inputbox)

 #======================== BUTTON ========================#   
# add a button ti create folder
$button_ClickMe = New-Object System.Windows.Forms.Button
    $button_ClickMe.Location = New-Object System.Drawing.Size(45,340)
    $button_ClickMe.Size = New-Object System.Drawing.Size(240,32)
    $button_ClickMe.TextAlign = "MiddleCenter"
    $button_ClickMe.Text = "Create Folders"
    $button_ClickMe.Add_Click({
    
    #$FolderExist =  $LabServer.Text + $CaseName.Text

    If ($CaseName.TextLength -eq 0){
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show('Please Enter a Case Name')
    }
    else {
        If (Test-Path -path ($LabServer + $CaseName) -PathType Container){
            Add-Type -AssemblyName System.Windows.Forms
            [System.Windows.Forms.MessageBox]::Show('Folder name exists, please enter a new name')
        }
        else {
            if ($Inputbox.TextLength -eq 0){
                Add-Type -AssemblyName System.Windows.Forms
                [System.Windows.Forms.MessageBox]::Show('Please enter 1 custodian name')
            }
            else {
                Get-Server
                Set-Location $LabServer
                New-Item $CaseName.Text -type directory 
                Start-Sleep -Seconds 5
                Set-Location ($LabServer.Text + $CaseName.Text)
                ForEach ($Folder in $Inputbox.lines) {
                    New-Item $Folder -type directory
                }
                 Add-Type -AssemblyName System.Windows.Forms
                 [System.Windows.Forms.MessageBox]::Show('Folders were created')
                 [System.Windows.Forms.Application]::Exit()
                       
            }
        }
    }

 })
     
    $CreateFolder.Controls.Add($button_ClickMe)

# show form
$CreateFolder.Add_Shown({$CreateFolder.Activate()})
[void] $CreateFolder.ShowDialog()

你几乎回答了自己的问题:
#$FolderExist=$LabServer.Text+$CaseName.Text

查看代码中的注释:

If ($CaseName.TextLength -eq 0)
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.MessageBox]::Show('Please Enter a Case Name')
}
else
{
    # If we are here $LabServer is not defined because Get-Server did not run yet
        
    # You can take 2 different approaches, either use your function or
    # Test-Path using the ComboBox
    # Approach 1: Define $LabServer
    Get-Server
    
    # Now you can Test-Path
    $path = Join-Path $LabServer -ChildPath $CaseName.Text
    If (Test-Path -Path $path -PathType Container)
    {
        .....
    }
        
    # Approach 2:
    $path = Join-Path ("\\{0}\K$" -f $DropdownBox.SelectedItem) -ChildPath $CaseName.Text
    If (Test-Path -Path $path -PathType Container)
    {
        .....
    }
.....
编辑 我认为有必要添加一些建议,以减少
AddClick
侦听器上嵌套条件的数量

  • 首先,默认情况下,在表单的开头禁用按钮:
  • 现在,您可以在
    TextChanged
    上为这两个
    TextBox
    添加两个侦听器:
这样,您就可以删除
$CaseName.TextLength-eq 0
$Inputbox.TextLength-eq 0
上的两个条件

  • 最后,您的
    AddClick
    事件如下所示(请注意,您不需要
    Get Server
    功能):

谢谢你的帮助,圣地亚哥, 我听从了你的建议,但收到了以下错误消息:

以下是我所做的改变

$FolderExist =  Join-Path $LabServer -ChildPath $CaseName.Text
If (Test-Path -path $FolderExist -PathType Container){
   Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.MessageBox]::Show('Folder name exists, please enter a new name')
        }
以下是错误消息:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\APPS\Scripts\CreateFolder - Test.ps1:94 char:31
+     $FolderExist =  Join-Path $LabServer -ChildPath $CaseName.Text
+                               ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
 
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\APPS\Scripts\CreateFolder - Test.ps1:101 char:29
+         If (Test-Path -path $FolderExist -PathType Container){
+                             ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

$LabServer+$CaseName
的内容是什么??什么是
$CaseName
。。。不要回答。。。检查一下!!您可以输出变量以检查它们是否包含您期望的内容。;-)您确定
$LabServer
上有一个尾随的反斜杠吗?我会使用
If(测试路径-Path(连接路径$LabServer$CaseName)-PathType容器
来确保路径在测试中的格式正确。比如,如果
$LabServer
“\\LabServer01\d$\CaseFiles”
并且
$CaseName
“4771893”
那么您正在测试的路径就是
“\\LabServer01\d$\CaseFiles4771893”
可能不存在,但您肯定可以更改为
“\\LabServer01\d$\CaseFiles”
,然后创建文件夹
“4771893”
尝试使用我的代码中的
方法2:
$buttonClickEvent = {
    $path = "\\{0}\K$" -f $DropdownBox.SelectedItem
    $path = Join-Path $path -ChildPath $CaseName.Text

    if(Test-Path $path -PathType Container)
    {
        [System.Windows.Forms.MessageBox]::Show('Folder name exists, please enter a new name')
        return
    }

    New-Item $path -Type Directory
    Start-Sleep -Seconds 5
    
    foreach($folder in $Inputbox.Lines)
    {
        $folder = $Folder.Trim()
        $newFolder = Join-Path $path -ChildPath $folder
        New-Item $newFolder -Type Directory
        [System.Windows.Forms.MessageBox]::Show('Folders were created')
        [System.Windows.Forms.Application]::Exit()
    }
}

$button_ClickMe.Add_Click($buttonClickEvent)
$FolderExist =  Join-Path $LabServer -ChildPath $CaseName.Text
If (Test-Path -path $FolderExist -PathType Container){
   Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.MessageBox]::Show('Folder name exists, please enter a new name')
        }
Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\APPS\Scripts\CreateFolder - Test.ps1:94 char:31
+     $FolderExist =  Join-Path $LabServer -ChildPath $CaseName.Text
+                               ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Join-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
 
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\APPS\Scripts\CreateFolder - Test.ps1:101 char:29
+         If (Test-Path -path $FolderExist -PathType Container){
+                             ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand