Search code examples
powershellffmpegpermission-deniedget-childitem

Permission Denied error with Get-ChildItem in PowerShell script


Whenever I try to run my PowerShell script, I get an error. Please note that I don't have much programming knowledge.

Here is the code (with some folder names replaced)

cd -Path "F:\****\folder1"
$files = Get-ChildItem
foreach ($file in $files) {
  $newName = $file.BaseName + ".mp3"
  ffmpeg -i $file.FullName -codec:a libmp3lame -b:a 320k $newName
}

Inside of folder1, there is folder2, which has the files I want to get. I'm not running in folder2, because in the future there will be a folder3 inside of folder1 and I want to get files from both. I am getting the error:

F:\****\folder1\folder2: Permission denied

I believe the error is with Get-ChildItem. How can I fix this? I am running the script as administrator.


Solution

  • If I understand the question properly, you have a source folder "F:\****\folder1 where files are kept inside subfolder(s) that need to be processed.

    In order to do that you need to add the -File aswell as the -Recurse switch on the Get-ChildItem cmdlet.

    Something like this:

    $sourceFolder = "F:\Somewhere\folder1"
    $files = Get-ChildItem -Path $sourceFolder -File -Recurse
    foreach ($file in $files) {
        $newName = [System.IO.Path]::ChangeExtension($file.FullName, ".mp3")
        # since the output file should go into the same directory, you can do
        # $newName = [System.IO.Path]::ChangeExtension($file.Name, ".mp3")
        ffmpeg -i "$($file.FullName)" -codec:a libmp3lame -b:a 320k "$newName"
    }
    

    Of course you need to have permission to create new files inside the source folder and its subdirectories