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

文件系统与此类似

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

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

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

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


当前回答

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

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

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}

其他回答

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

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

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}

从你的情况来看,听起来你需要每天创建一个“修订#”文件夹,里面有一个“报告”文件夹。如果是这样的话,你只需要知道下一个版本号是什么。编写一个函数来获取下一个修订号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安装。

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

例如,在脚本的文件夹中创建一个“Reports”文件夹。

$ReportsDir = $PSScriptRoot + '\Reports'
$CreateReportsDir = [System.IO.Directory]::CreateDirectory($ReportsDir) 

试试-Force参数:

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

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

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