powershellpermissionspermission-deniednew-item

How to create csv file in powershell with dynamic name?


I am trying to write a PowerShell function that will basically create a file in the folder with a name that was passed to that function as $fileName argument.

Here is the function:

$mainFolder = "C:\testFolder\"
function checkIfExist($path, $fName) {
    if (!(Test-Path $path)) {
        $path = $mainFolder + "data"
        new-item -name $fName -type "file" -path $path -force   
    }
    else {}
}

The error:

New-Item : Access to the path 'C:\testFolder\data' is denied.
At C:\testFolder\test.ps1:9 char:3
+         New-Item -Name $fileName -Type "file" -Path $path -Force
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\testFolder\data:String) [New-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

But for some reason if I switch:

New-Item -Name $fileName -Type "file" -Path $path -Force

to:

New-Item -Name "static name.csv" -Type "file" -Path $path -Force

it works perfectly fine.

I run that script as an administrator but still get the same results.

Update:

I run function by using this line:

checkIfExist($fullPath, $fileName)

Solution

  • You're calling the function incorrectly, Powershell doesn't use the function($param1, $param2) format, instead it uses function $param1 $param2 (using positional parameters) or function -Param1 $param1 -Param2 $param2 (using named parameters).

    You only seem to be testing for the folder path, rather than the file itself.

    Join-Path can be used to create the full path to the file, which you then test for and only create the file if it doesn't exist.

    If you want to add a data sub-folder, just pass it into the function with the param.

    function checkIfExist($path, $fileName) {
        $fullpath = Join-Path $path $fileName
        if (!(Test-Path $fullpath)) {
            New-Item -Path $path -Name $fileName -ItemType File -Force
        }
    }
    
    #example 1
    checkIfExist "C:\folder" "file.csv"
    
    #example 2
    checkIfExist "C:\folder\data" "anotherfile.csv"