检测文件夹是否包含日志文件夹和ps1文件

时间:2019-09-02 03:43:41

标签: powershell

我正在为支持团队的脚本创建一个菜单,该菜单大部分都在工作。但是,当它找到同时包含一个名为“ Logs”的文件夹和一个脚本(.ps1)的文件夹时,我希望它启动脚本,而不是将其作为菜单列出。我创建了2条if语句来尝试检测它,但是我无法弄清为什么它们不起作用。

$Directories正确填充,其中项目0和1的Write-Host打印正确的项目(日志文件夹和脚本)。但是,if语句始终为假,因此它跳过了if。有什么想法我做错了吗?

$Directories = Get-ChildItem

Write-Host $Directories[0]
Write-Host $Directories[1]
if ($Directories[0] -eq 'Logs' -or $Directories[0] -like '*.ps1') {
    Write-Host "first if"
    if ($Directories[1] -eq 'Logs' -or $Directories[1] -like '*.ps1') {
        Write-Host "Second If"
    }
} else {
    foreach ($Item in $Directories) {
        $ItemName = $Item -replace "-"," "
        if ($Item -like '*.ps1') {
            $ItemName = [IO.Path]::GetFileNameWithoutExtension($ItemName)
            Write-Host $MenuNum": "$ItemName -ForegroundColor Green
        } else {
            Write-Host $MenuNum": "$ItemName -ForegroundColor Yellow
        }
        $MenuNum ++
    }

预期结果是,当没有日志文件夹且没有.ps1文件时,它将进一步执行脚本并创建菜单。如果有一个日志文件夹和一个.ps1文件,它将启动.ps1。目前,我只是在测试,所以现在有了Write-Host

3 个答案:

答案 0 :(得分:0)

虽然您不清楚要尝试执行的操作,但我想您要递归某个根文件夹并列出其中的所有目录。
如果发现其中包含(至少)一个.ps1脚本文件的目录,则获取该脚本文件并启动它(或现在以绿色写出)。否则,只需将找到的目录写成黄色即可。

尝试一下:

$MenuNum = 0
Get-ChildItem -Path 'D:\test' -Recurse -Directory | ForEach-Object {
    $MenuNum++
    $scriptFile = if ($_.Name -eq 'Logs') {
        # we've found a directory called 'Logs'
        # test if it has at least one .ps1 file in it
        # emit the first (or only) found ps1 FileInfo object. $null if nothing there.
        @(Get-ChildItem -Path $_.FullName -Filter '*.ps1' -File)[0]
    }
    if ($scriptFile) {
        # launch the (first or only) script file or whatever you want to do with it
        Write-Host ('{0}: {1}' -f $MenuNum, $scriptFile.FullName) -ForegroundColor Green
    }
    else {
        # just write the directory name
        Write-Host ('{0}: {1}' -f $MenuNum, $_.FullName) -ForegroundColor Yellow
    }
}

输出将如下所示:

enter image description here

答案 1 :(得分:0)

Get-ChildItem返回对象列表而不是字符串列表,因此您需要使用属性名称来检查是否相等。

$Directories[0].Name -eq 'Logs'

如果只想使用文件名,则可以使用以下内容:

Get-ChildItem | Select-Object -ExpandProperty Name

答案 2 :(得分:0)

如果我理解正确,您想从名为LOGS的文件夹中收集所有* .ps1文件并执行它们吗?

如果我理解正确,那么我想首先开始声明,我将不鼓励在没有任何控制或安全的情况下从文件夹运行脚本!

仍然可以为您提供答案,您可以尝试以下操作:

$FileList = Get-ChildItem -Path *LOGS* -Include *.ps1 -Recurse
foreach ($file in $FileList) {
    & ($File.fullname)
}

这会将所有文件收集到一个变量中,然后您可以循环执行它们, 但要自行承担风险!

希望有帮助!

最好的问候, 伊万