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

eco*_*is6 291 powershell powershell-ise windows-server-2008

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

文件系统看起来与此类似

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
Run Code Online (Sandbox Code Playgroud)
  • 每个项目文件夹都有多个修订版.
  • 每个修订文件夹都需要Reports文件夹.
  • 某些"revisions"文件夹已包含Reports文件夹; 但是,大多数人没有.

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

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

And*_*ndi 469

你试过-Force参数吗?

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
Run Code Online (Sandbox Code Playgroud)

你可以Test-Path -PathType Container先用来检查.

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

  • 对于懒惰,有一个简写:md -Force c:\ foo\bar\baz (92认同)
  • 对于那些在创建文件夹时不想要任何输出的人,最后添加"| Out-Null" (66认同)
  • @PeterMortensen对于目录,强制它们不会清除现有内容,它只会抑制错误消息,说明它已经创建.此命令还将创建所需的任何中间文件夹,如果这些文件夹已存在,则这些文件夹的内容也是安全的. (16认同)
  • -Force究竟会做什么?[文档](https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Management/New-Item?view=powershell-5.1)说*"强制此cmdlet创建一个项目,写入现有的只读项目"*.它会删除现有文件夹吗?在这个答案中应该清楚. (14认同)
  • 警告:如果路径上有文件,这将静默进行,与 [System.IO.Directory]::CreateDirectory('path') 不同 (9认同)

小智 143

$path = "C:\temp\NewFolder"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}
Run Code Online (Sandbox Code Playgroud)

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

  • @KCD 解释薛定谔的目录 (5认同)
  • 为什么选择“-Force”? (2认同)

fil*_*nic 17

[System.IO.Directory]::CreateDirectory('full path to directory')
Run Code Online (Sandbox Code Playgroud)

这会在内部检查目录是否存在,如果没有目录,则创建一个。只需一行代码和本机 .NET 方法即可完美运行。


小智 15

用:

$path = "C:\temp\"
    
If (!(test-path $path))
{
    md $path
}
Run Code Online (Sandbox Code Playgroud)
  • 第一行创建了一个名为$path“C:\temp”的变量,并赋予它字符串值

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

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

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

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

New-Item -ItemType Directory -Path $path
Run Code Online (Sandbox Code Playgroud)


小智 13

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

$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)
    }
}
Run Code Online (Sandbox Code Playgroud)


Kla*_*ark 10

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

一内胆:

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

顺便说一句,有关安排任务的信息,请查看以下链接:安排后台工作.


Geo*_*ton 9

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

Method 1: PS C:\> New-Item -ItemType Directory -path "C:\livingston"
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Method 2: PS C:\> [system.io.directory]::CreateDirectory("C:\livingston")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Method 3: PS C:\> md "C:\livingston"
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Nar*_*ddy 5

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

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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"
Run Code Online (Sandbox Code Playgroud)


E.V*_*.L. 4

从您的情况来看,您似乎需要每天创建一个“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 two 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.
}
Run Code Online (Sandbox Code Playgroud)

PowerShell 3.0 安装