0

将数据写入新文件时遇到一个奇怪的问题。我在一个目录中有一个文件列表,其中包含我正在解析的数据并使用 Create-VMwareconf() 函数返回数据。这将返回我分配给 $t 的哈希表中的数据。我已经从 $t 函数中提取了所需的文件夹和文件名,但是每次我开始循环时,我都会收到以下初始文件夹创建错误,第二个和第三个工作正常。有趣的是,应该在第一个文件中的数据存在于第二个文件夹中。

如果我再次运行脚本,它会生成所有三个对象,但是文件中与文件名匹配的数据的顺序不正确。

对于如何停止以下错误,我们将不胜感激;

$e = (Get-Childitem ".\a\*\*.ini")
Set-Location "C:\WindowsRoot\vmwareconfigfiles\"
ForEach($d in $e){
$vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
$vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
$t = Create-VMwareconf($d)
$dd = $t.Value["0"]

#Write contents to new file
$t | Out-File $vmwarefile
}

初次运行时收到错误;

新项目:拒绝访问路径“C:\WindowsRoot\vmwareconfigfiles”。在 C:\WindowsRoot\parsedisrec.ps1:93 char:15 + $vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force + ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: ( C:\WindowsRoot\vmwareconfigfiles:String) [New- Item], UnauthorizedAccessException + FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

Out-File:无法将参数绑定到参数“FilePath”,因为它为空。在 C:\WindowsRoot\parsedisrec.ps1:97 char:15 + $t | 输出文件 $vmwarefile + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Out-File], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand

4

1 回答 1

1

New-Item -Type file在第一次迭代期间失败,因为$dd那时还没有初始化,所以你试图创建一个与当前目录同名的文件。如果您使用$null(甚至.)作为名称,您将得到相同的结果:

PS C:\> New-Item -Type file -Path 'C:\some\where' -Name $null -Force
New-Item : Access to the path 'C:\some\where' is denied.
At line:1 char:1
+ New-Item -Type file -Path 'C:\some\where' -Name $null -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\some\where:String) [New-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

PS C:\> New-Item -Type file -Path 'C:\some\where' -Name '.' -Force
New-Item : Access to the path 'C:\some\where' is denied.
At line:1 char:1
+ New-Item -Type file -Path 'C:\some\where' -name '.' -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\some\where\.:String) [New-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : NewItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

改变这个:

ForEach($d in $e){
  $vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
  $vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
  $t = Create-VMwareconf($d)
  $dd = $t.Value["0"]

进入这个:

ForEach($d in $e){
  $t = Create-VMwareconf($d)
  $dd = $t.Value["0"]
  $vmwaredirectory = New-item -type directory -path .\ -name $dd -Force
  $vmwarefile = New-Item -type file -path $vmwaredirectory -name $dd -Force
于 2013-08-27T18:06:50.270 回答