首页 文章

如果目录不存在,请创建目录

提问于
浏览
235

我正在编写一个PowerShell脚本来创建几个目录(如果它们不存在) .

文件系统看起来与此类似

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
  • 每个项目文件夹都有多个修订版 .

  • 每个修订文件夹都需要一个Reports文件夹 .

  • 某些"revisions"文件夹已包含Reports文件夹;但是,大多数人没有 .

我需要编写一个每天运行的脚本来为每个目录创建这些文件夹 .

我能够编写脚本来创建文件夹,但创建多个文件夹是有问题的 .

10 回答

  • 2

    你试过 -Force 参数吗?

    New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
    

    您可以先使用Test-Path -PathType Container进行检查 .

    有关更多详细信息,请参阅New-Item MSDN帮助文章 .

  • 1

    从您的情况来看,您需要每天创建一次“Revision#”文件夹,其中包含“Reports”文件夹 . 如果是这种情况,您只需要知道下一个修订号是什么 . 编写一个获取下一个修订号Get-NextRevisionNumber的函数 . 或者你可以这样做:

    foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
        #Select all the Revision folders from the project folder.
        $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory
    
        #The next revision number is just going to be one more than the highest number.
        #You need to cast the string in the first pipeline to an int so Sort-Object works.
        #If you sort it descending the first number will be the biggest so you select that one.
        #Once you have the highest revision number you just add one to it.
        $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1
    
        #Now in this we kill 2 birds with one stone. 
        #It will create the "Reports" folder but it also creates "Revision#" folder too.
        New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory
    
        #Move on to the next project folder.
        #This untested example loop requires PowerShell version 3.0.
    }
    

    PowerShell 3.0 installation

  • 4

    我希望能够轻松地让用户为PowerShell创建默认配置文件以覆盖某些设置,最后使用以下单行(多个语句是,但可以粘贴到PowerShell中并立即执行,这是主要目标):

    cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };
    

    为了便于阅读,以下是我将如何在ps1文件中执行此操作:

    cls; # Clear console to better notice the results
    [string]$filePath = $profile; # declared as string, to allow the use of texts without plings and still not fail.
    [string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
    if(!(Test-Path $filePath)) {
      New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
      $fileContents | Set-Content $filePath; # Creates a new file with the input
      Write-Host 'File created!';
    } else {
      Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
    };
    
  • 7
    $path = "C:\temp\NewFolder"
    If(!(test-path $path))
    {
          New-Item -ItemType Directory -Force -Path $path
    }
    

    Test-Path 检查路径是否存在 . 如果没有,它将创建一个新目录 .

  • 1

    这是一个适合我的简单方法 . 它检查路径是否存在,如果不存在,它不仅会创建根路径,还会创建所有子目录:

    $rptpath = "C:\temp\reports\exchange"
    
    if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}
    
  • 399
    $path = "C:\temp\"
    
    If(!(test-path $path))
    
    {md C:\Temp\}
    
    • 第一行创建一个名为 $path 的变量,并为其指定"C:\temp"的字符串值

    • 第二行是 If 语句,它依赖于Test-Path cmdlet来检查变量 $path 是否不存在 . 使用 ! 符号限定not exists

    • 第三行:如果找不到上面字符串中存储的路径,将运行大括号之间的代码

    md 是输入的简短版本: New-Item -ItemType Directory -Path $path

    注意:我没有使用下面的 -Force 参数进行测试,以查看路径是否已存在时是否存在不良行为 .

    New-Item -ItemType Directory -Path $path

  • 92

    我有同样的问题 . 你可以使用这样的东西:

    $local = Get-Location;
    $final_local = "C:\Processing";
    
    if(!$local.Equals("C:\"))
    {
        cd "C:\";
        if((Test-Path $final_local) -eq 0)
        {
            mkdir $final_local;
            cd $final_local;
            liga;
        }
    
        ## If path already exists
        ## DB Connect
        elseif ((Test-Path $final_local) -eq 1)
        {
            cd $final_local;
            echo $final_local;
            liga;  (function created by you TODO something)
        }
    }
    
  • 12

    我知道使用PowerShell创建目录的方法有3种

    Method 1: PS C:\> New-Item -ItemType Directory -path "c:\livingston"
    
    Method 2: PS C:\> [system.io.directory]::CreateDirectory("c:\livingston")
    
    Method 3: PS C:\> md "c:\livingston"
    
  • 8

    以下代码段可帮助您创建完整路径 .

    Function GenerateFolder($path){
        $global:foldPath=$null
        foreach($foldername in $path.split("\")){
              $global:foldPath+=($foldername+"\")
              if(!(Test-Path $global:foldPath)){
                 New-Item -ItemType Directory -Path $global:foldPath
                # Write-Host "$global:foldPath Folder Created Successfully"
                }
        }   
    }
    

    上面的函数拆分传递给函数的路径,并检查每个文件夹是否存在 . 如果它不存在,它将创建相应的文件夹,直到创建目标/最终文件夹 .

    要调用该函数,请使用以下语句:

    GenerateFolder "H:\Desktop\Nithesh\SrcFolder"
    
  • 2

    指定 -Force 标志时,如果文件夹已存在,PowerShell将不会报警 .

    一内胆:

    Get-ChildItem D:\TopDirec\SubDirec\Project* | `
      %{ Get-ChildItem $_.FullName -Filter Revision* } | `
      %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }
    

    顺便说一下,有关安排任务的信息,请查看以下链接:Scheduling Background Jobs .

相关问题