如果它们不存在,我正在编写一个 PowerShell 脚本来创建几个目录。
文件系统看起来与此类似
D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
每个项目文件夹都有多个修订版。
每个修订文件夹都需要一个 Reports 文件夹。
一些“修订”文件夹已经包含一个报告文件夹;但是,大多数都没有。
我需要编写一个每天运行的脚本来为每个目录创建这些文件夹。
我能够编写脚本来创建一个文件夹,但是创建多个文件夹是有问题的。
试试 -Force
参数:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
您可以先使用 Test-Path -PathType Container
进行检查。
有关详细信息,请参阅 New-Item MSDN 帮助文章。
$path = "C:\temp\NewFolder"
If(!(test-path -PathType container $path))
{
New-Item -ItemType Directory -Path $path
}
Test-Path -PathType container
检查路径是否存在且是否为目录。如果没有,它将创建一个新目录。如果路径存在但是是文件,New-Item 将引发错误(如果有风险,可以使用 -force
参数覆盖文件)。
test-path
),这会使输出静音。
-Force
?
[System.IO.Directory]::CreateDirectory('full path to directory')
这在内部检查目录是否存在,如果没有目录,则创建一个。只需一行和本地 .NET 方法即可完美运行。
利用:
$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
md "C:\first\second\third
全部创建。
以下代码片段可帮助您创建完整路径。
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"
我有同样的问题。你可以使用这样的东西:
$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)
}
}
当您指定 -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。
我知道使用 PowerShell 创建目录的三种方法:
Method 1: PS C:\> New-Item -ItemType Directory -path "C:\livingston"
https://i.stack.imgur.com/rtvCV.jpg
Method 2: PS C:\> [system.io.directory]::CreateDirectory("C:\livingston")
https://i.stack.imgur.com/a2TA2.jpg
Method 3: PS C:\> md "C:\livingston"
https://i.stack.imgur.com/tBN1V.jpg
从您的情况来看,您需要每天创建一个“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.
}
这是一个对我有用的简单方法。它检查路径是否存在,如果不存在,它不仅会创建根路径,还会创建所有子目录:
$rptpath = "C:\temp\reports\exchange"
if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}
我希望能够轻松地让用户为 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";
};
$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\")
不定期副业成功案例分享