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

文件系统与此类似

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\

每个项目文件夹都有多个版本。 每个修订文件夹都需要一个Reports文件夹。 一些“修订”文件夹已经包含了一个报告文件夹;然而,大多数人并没有。

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

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


当前回答

$path = "C:\temp\NewFolder"
If(!(test-path -PathType container $path))
{
      New-Item -ItemType Directory -Path $path
}

Test-Path -PathType容器检查路径是否存在,是否为目录。如果没有,它将创建一个新目录。如果路径存在但是一个文件,New-Item将引发一个错误(如果您有风险,可以使用-force参数覆盖该文件)。

其他回答

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

一行程序:

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

顺便说一下,要调度任务,请查看这个链接:调度后台任务。

试试-Force参数:

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

可以先使用Test-Path -PathType容器进行检查。

请参阅新项目MSDN帮助文章了解更多详细信息。

$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\")
[System.IO.Directory]::CreateDirectory('full path to directory')

这将在内部检查目录是否存在,如果没有目录,则创建一个。只有一行代码和本地的。net方法可以完美地工作。

我知道用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"