когда я пытался запустить скрипт срабатывает только первое и второе условие когда я пытался использовать "например, D:\random", где случайная папка не существует, я получил сообщение об ошибке вместо запуска третьего условного "иначе"
function listChildFolder($folderPath)
{
#write your script here
$folderPath = Read-Host "input"
if ((Get-ChildItem $folderPath) -ne $null)
{ $folderPath| Get-ChildItem |Sort-Object -Property LastWriteTime -Descending |Format-Table name }
elseif ((Get-ChildItem $folderPath) -eq $null)
{ "Folder Empty" }
else {"Error: <Error message>"}
return
}
Поскольку Get-ChildItem выдает завершающую ошибку, когда путь к папке не существует, функция завершается на этом, а остальные условия elseif или else никогда не выполняются.
Я бы предложил сделать это в try{..} catch{..}
, чтобы вы могли фиксировать такие исключения:
Что-то вроде
function listChildFolder {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$folderPath
)
# capture the terminating error message when the path does not exist
# by specifying -ErrorAction Stop
try {
# since we do not add switch '-File' or '-Directory',
# the Get-ChildItem cmdlet will return both types
$filesAndFolders = Get-ChildItem -Path $folderPath -ErrorAction Stop
# next, find out if we found any files or folders in the path
# the '@()' forces the $filesAndFolders variable into an array, so we can use the .Count property
if (@($filesAndFolders).Count) {
$filesAndFolders | Sort-Object LastWriteTime -Descending | Select-Object Name
}
else {
Write-Host "No files or subfolders found in '$folderPath'"
}
}
catch {
Write-Warning "Error: $($_.Exception.Message)"
}
}
$folderPath = Read-Host "Please enter a folder path"
# call the function
listChildFolder $folderPath
Another recommendation is that you use the PowerShell Verb-Noun naming convention for your function
Согласно вашему комментарию, в котором вы говорите, что не можете использовать try{..} catch{..}
, конечно, есть и другие способы.
Как насчет этого:
function listChildFolder {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$folderPath
)
# test if the given folder path exists
if (Test-Path -Path $folderPath -PathType Container) {
# since we do not add switch '-File' or '-Directory',
# the Get-ChildItem cmdlet will return both types
$filesAndFolders = Get-ChildItem -Path $folderPath
# next, find out if we found any files or folders in the path
# the '@()' forces the $filesAndFolders variable into an array, so we can use the .Count property
if (@($filesAndFolders).Count) {
$filesAndFolders | Sort-Object LastWriteTime -Descending | Select-Object Name
}
else {
Write-Host "No files or subfolders found in '$folderPath'"
}
}
else {
Write-Warning "Error: '$folderPath' does not exist"
}
}
$folderPath = Read-Host "Please enter a folder path"
# call the function
listChildFolder $folderPath
хорошо, ваше решение идеально, но моя проблема заключается в том, что мне нужно использовать этот тип шаблона, чтобы решить его: #Script template function listChildFolder($folderPath) { #напишите здесь свой скрипт return ... }
@bobmar Хорошо, я добавил для вас еще одно решение без использования try{..} catch{..}
«срабатывает только первое и второе условие» —
Get-ChildItem $folderPath
либо-eq $null
, либо-ne $null
; (за исключением условий гонки) нет третьей возможности, в которой вашelse
будет выполнен. "когда я попробовал... я получил сообщение об ошибке" — Что это за ошибка и откуда она возникла? Было бы лучше присвоитьGet-ChildItem $folderPath
переменной потом test, если она пуста при принятии решения о том, что выводить. Кроме того, см. Как проверить массив $null в PowerShell, почему вы хотите записать это сравнение как$null -ne (gci $folderPath)
.