[英]How to create M365 dynamic groups from CSV file using powershell
[英]How to create csv file in powershell with dynamic name?
我正在尝试编写一个PowerShell函数,该函数基本上将在文件夹中创建一个文件,该文件的名称作为$fileName
参数传递给该函数。
这是函数:
$mainFolder = "C:\testFolder\"
function checkIfExist($path, $fName) {
if (!(Test-Path $path)) {
$path = $mainFolder + "data"
new-item -name $fName -type "file" -path $path -force
}
else {}
}
错误:
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
但是由于某种原因,如果我切换:
New-Item -Name $fileName -Type "file" -Path $path -Force
至:
New-Item -Name "static name.csv" -Type "file" -Path $path -Force
它工作得很好。
我以管理员身份运行该脚本,但仍然得到相同的结果。
更新:
我通过使用以下行来运行函数:
checkIfExist($fullPath, $fileName)
您错误地调用了函数,Powershell不使用function($param1, $param2)
格式,而是使用function $param1 $param2
(使用位置参数)或function -Param1 $param1 -Param2 $param2
(使用命名参数)参数)。
您似乎只是在测试文件夹路径,而不是文件本身。
Join-Path
可用于创建文件的完整路径,然后对其进行测试,仅在文件不存在时创建该路径。
如果要添加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.