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)