Harish
Harish

Reputation: 11

Powershell script to check subfolders exist or not

I'm trying to write a script in PowerShell. There will be the main folder like eg: movies. Inside I will have a subfolder of which language of movie it is and another subfolder inside it for the movie name. I will be giving only the main folder path ie: F:\Movies, And I will be taking the language of the movie folder and movie name folder as parameters I want to verify if the folder is available inside the main folder or not. I wrote the below script but it's not working. Could you please help me to figure it out?

Function Folder_Check {
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory=$true)]$Languageofmovie,
        [Parameter(Mandatory=$true)]$nameofmovie)
   
    $Foldertocheck = 'F:\Movies'

    if ($result = Get-childitem -path $Foldertocheck -Recurse -Directory) {
        Write-Host "Folder found in $($result)"  
    }
    else {
        Write-Host "No it is not available"
    }
}

Upvotes: 0

Views: 1559

Answers (2)

MMNandM
MMNandM

Reputation: 1

Did I understand correctly?

Function Folder_Check {
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory=$true)]$Languageofmovie,
        [Parameter(Mandatory=$true)]$nameofmovie)
   
    $Foldertocheck = $Foldertocheck = 'F:\Movies' + '$($Languageofthemovie)'

    if ((Get-childitem -path $Foldertocheck -Directory).name -match '$($nameofmovie)') {
        Write-Host "Folder found in $($Foldertocheck)"  
    }
    else {
        Write-Host "No it is not available"
    }
}

Upvotes: 0

Alex Korobchevsky
Alex Korobchevsky

Reputation: 165

You can fix this by leveraging the parameters passed to the function. Since you know the folder structure you can create a variable that combines the root folder, the language and the movie name:

Function Folder_Check {
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(Mandatory=$true)]$Languageofmovie,
        [Parameter(Mandatory=$true)]$nameofmovie)
   
    $Foldertocheck = '~\Documents\Movies'
    $MovieFolder = "$Foldertocheck\$Languageofmovie\$nameofmovie"

    if (Test-Path $MovieFolder -PathType Container) {
        Write-Host "$MovieFolder found"  
    }
    else {
        Write-Host "$MovieFolder is not available"
    }
}

Using -PathType Container to make sure the movie name is a folder and not a file.

Then you can call the function - something like:

Folder_Check English Godfather

Folder_Check English Armageddon

Folder_Check Russian TheIdiot

Upvotes: 1

Related Questions