简体   繁体   English

如何使用动态名称在Powershell中创建CSV文件?

[英]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. 我正在尝试编写一个PowerShell函数,该函数基本上将在文件夹中创建一个文件,该文件的名称作为$fileName参数传递给该函数。

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)

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). 您错误地调用了函数,Powershell不使用function($param1, $param2)格式,而是使用function $param1 $param2 (使用位置参数)或function -Param1 $param1 -Param2 $param2 (使用命名参数)参数)。

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. Join-Path可用于创建文件的完整路径,然后对其进行测试,仅在文件不存在时创建该路径。

If you want to add a data sub-folder, just pass it into the function with the param. 如果要添加data子文件夹,只需将其与参数一起传递给函数。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM