为每个文件创建零字节文件并在末尾附加一个扩展名

问题描述:

我希望这样做能够递归每个目录,并为每个使用与添加扩展名.xxx的文件名称相同的文件创建一个零字节文件。我在想New-Item在这里会很好用,但我似乎无法让它正常工作。为每个文件创建零字节文件并在末尾附加一个扩展名

以下是我在PS 2版本没有成功尝试:

$drivesArray = Get-PSDrive -PSProvider 'FileSystem' | select -Expand Root 
foreach ($drive in $drivesArray) { 
    ls "$drive" | where { 
    $_.FullName -notlike "${Env:WinDir}*" -and 
    $_.FullName -notlike "${Env:ProgramFiles}*" 
    } | ls -ErrorAction SilentlyContinue -recurse | where { 
    -not $_.PSIsContainer -and 
    $_.Extension -notmatch '\.xxx|\.exe|\.html' 
    } | New-Item -Path { $_.BaseName } -Name ($_.FullName+".xxx") -Type File -Force 
} 

这种错误了与

位置参数无法找到接受的说法“+ XXX”。

+0

' “$($ _全名).XXX”'我肯定有可能是其他改进。我不知道这段代码是否会让你想要你想要的。 – Matt

你需要用两个第二Get-ChildItemls)和ForEach-Object报表New-Item。此外,不要通过$_.Basename作为到New-Item的路径。做到这一点无论是这样的:

New-Item -Path ($_.FullName + '.xxx') -Type File -Force 

或像这样:

New-Item -Path $_.Directory -Name ($_.Name + '.xxx') -Type File -Force 

修改后的代码:

foreach ($drive in $drivesArray) { 
    Get-ChildItem $drive | Where-Object { 
    $_.FullName -notlike "${Env:WinDir}*" -and 
    $_.FullName -notlike "${Env:ProgramFiles}*" 
    } | ForEach-Object { 
    Get-ChildItem $_.FullName -Recurse -ErrorAction SilentlyContinue 
    } | Where-Object { 
    -not $_.PSIsContainer -and 
    $_.Extension -notmatch '^\.(xxx|exe|html)$' 
    } | ForEach-Object { 
    New-Item -Path ($_.FullName + '.xxx') -Type File -Force 
    } 
} 
+0

有了这段代码,我得到了一堆'访问被拒绝',这似乎主要是在Windows \ system文件夹中。另外,不会创建零字节文件。 新项目:访问路径'C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ .. \ MSFT_GroupResource.schema.mfl.xxx'被拒绝。 –

+0

@shadw_it对不起,我的错。我忘了将路径添加到第二个“Get-ChildItem”。固定。 –

+0

照顾它。谢谢您的帮助! –