442

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

文件系统看起来与此类似

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
  • 每个项目文件夹都有多个修订版。
  • 每个修订文件夹都需要一个 Reports 文件夹。
  • 一些“修订”文件夹已经包含一个报告文件夹;但是,大多数都没有。

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

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

4

12 回答 12

684

试试这个-Force参数:

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

您可以使用Test-Path -PathType Container先检查。

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

于 2013-06-04T06:50:49.023 回答
216
$path = "C:\temp\NewFolder"
If(!(test-path $path))
{
      New-Item -ItemType Directory -Force -Path $path
}

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

于 2016-08-25T20:48:41.753 回答
26
[System.IO.Directory]::CreateDirectory('full path to directory')

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

于 2020-08-08T02:44:35.833 回答
22

利用:

$path = "C:\temp\"
    
If (!(test-path $path))
{
    md $path
}
  • 第一行创建一个名为的变量$path并为其分配字符串值“C:\temp”

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

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

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

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

New-Item -ItemType Directory -Path $path
于 2017-10-12T16:42:22.070 回答
20

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

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"
于 2017-11-07T07:21:52.757 回答
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)
    }
}
于 2013-11-15T17:32:48.650 回答
11

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

单线:

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

顺便说一句,要安排任务,请查看此链接:安排后台作业

于 2013-06-04T09:15:34.477 回答
10

我知道使用 PowerShell 创建目录的三种方法:

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"

在此处输入图像描述

于 2016-10-26T10:58:37.310 回答
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.
}

PowerShell 3.0 安装

于 2013-06-03T22:12:21.003 回答
2

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

$rptpath = "C:\temp\reports\exchange"

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}
于 2017-09-18T12:55:29.223 回答
2

我希望能够轻松地让用户为 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";
};
于 2016-12-29T10:21:16.610 回答
0
$mWarningColor = 'Red'

<#
.SYNOPSIS
    Creates a new directory. 
.DESCRIPTION
    Creates a new directory. If the directory already exists, the directory will
    not be overwritten. Instead a warning message that the directory already
    exists will be output.
.OUTPUT
    If the directory already exists, the directory will not be overwritten.
    Instead a warning message that the directory already exists will be output.
.EXAMPLE    
    Sal-New-Directory -DirectoryPath '.\output'
#>
function Sal-New-Directory {
    param(
        [parameter(mandatory=$true)]
        [String]
        $DirectoryPath
    )
    $ErrorActionPreference = "Stop"
    try {
        if (!(Test-Path -Path $DirectoryPath -PathType Container)) {

            # Sal-New-Directory is not designed to take multiple 
            # directories. However, we use foreach to supress the native output
            # and substitute with a custom message.
            New-Item -Path $DirectoryPath -ItemType Container | `
              foreach {'Created ' + $_.FullName}
        } else {
            Write-Host "$DirectoryPath already exists and" `
                        "so will not be (re)created." `
                        -ForegroundColor $mWarningColor
        }
    } finally {
        $ErrorActionPreference = "Continue"
    }
}

“Sal”只是我自己的库的任意前缀。您可以将其删除或替换为您自己的。

另一个例子(放在这里是因为它会破坏stackoverflow语法高亮):

Sal-New-Directory -DirectoryPath ($mCARootDir + "private\")
于 2021-05-02T12:10:52.980 回答