我正在完成将批处理文件升级到PowerShell的任务。我必须执行需要检查文件夹结构是否存在的任务。如果不是从它丢失的地方创建它。还需要使用smtp发送关于状态的邮件......
example:
D:\folder\folder1\folder2\folder3
E:\folder\folder1\folder2\folder3
E:\folderA\folderB\FolderC\FolderD\FolderE
如果仅缺少FolderC
,则从FolderC\FolderD\FolderE
如果从FolderB
丢失,则从FolderB\FolderC\FolderD\FolderE
答案 0 :(得分:0)
这可能会更漂亮但是......在这里,有很多方法可以做到这一点,具体取决于你想要如何使用它。
$SmtpServer = '192.168.1.2' #Replace this with IP adress to your SMTP-server
$Body='' #Two single quotation marks
$path = Read-Host 'Enter Path (Type Exit to quit)'
While ($path -ne 'Exit') {
IF (Test-Path $path) {
$Body += "$path already exists `n" #Adds $path to $Body and breaks line
}
ELSE {
New-Item $path -ItemType directory
$Body += "$path was created `n" #Adds $path to $Body and breaks line
}
$path = Read-Host 'Enter Path (Type Exit to quit)'
}
IF($Body -ne '') {
Send-Mailmessage -SmtpServer $SmtpServer -Subject "Folder status" -Body $Body
}
答案 1 :(得分:0)
此功能可以满足您的需要,包括详细的日志。复制粘贴或与脚本一起保存Test-DirectoryTree.ps1
并使用点源加载:
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
. (Join-Path -Path $ScriptDir -ChildPath 'Test-DirectoryTree.ps1')
用法:
# Array of paths to check
$Paths = @(
'D:\folder\folder1\folder2\folder3',
'E:\folder\folder1\folder2\folder',
'E:\folderA\folderB\FolderC\FolderD\FolderE'
)
# Store function output in $Log variable
# W\o "Create" switch function will only report missing directories
$Log = $Paths | Test-DirectoryTree -Create
# Send email
Send-MailMessage -SmtpServer 'mail.company.com' -From 'script@company.com' -To 'admin@company.com' -Subject 'Folder status' -Body $Log
Test-DirectoryTree
功能:
function Test-DirectoryTree
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[string[]]$Paths,
[switch]$Create
)
Begin
{
# Set path separator
$Separator = '\'
# Init array to hold log
$Log = @()
}
Process
{
# For every path in array
foreach ($Path in $Paths){
# Init array to store existing paths
$Tree = @()
# Split path
foreach ($Dir in $Path.Split($Separator)){
# If not first element
if($Tree)
{
# Build path for current dir to check
$CurrDir = Join-Path -Path ($Tree -join $Separator) -ChildPath $Dir
}
else # If not first element
{
# Check if root dir exist
if(!(Test-Path -LiteralPath $Dir -PathType Container) -and [System.IO.Path]::IsPathRooted($Dir))
{
Write-Error "Root folder '$Dir' is not valid!"
break
}
else
{
# Build path for current dir to check
$CurrDir = $Dir
}
}
# If current dir not exist
if(!(Test-Path -LiteralPath $CurrDir -PathType Container))
{
# Write message to log
$Log += "Folder doesn't exist: $CurrDir"
# If we asked to create missing dirs
if($Create)
{
# Try to create dir
try
{
New-Item -ItemType Directory -Path $CurrDir -ErrorAction Stop | Out-Null
$Log += "Folder created: $CurrDir"
}
catch
{
$Log += "Failed to create folder: $CurrDir"
}
}
}
# If current dir exist, do nothing and add it to existing paths
$Tree += $Dir
}
}
}
End
{
# Return log
return $Log
}
}