为每个文件创建零字节文件并在末尾附加扩展名
Creating zero-byte file for every file and appending an extension to the end
我希望它递归每个目录并使用与添加了扩展名 .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
}
此错误与
A positional parameter cannot be found that accepts argument "+xxx".
您需要将第二个 Get-ChildItem
(ls
) 和 New-Item
包装在 ForEach-Object
语句中。另外,不要将 $_.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
}
}
我希望它递归每个目录并使用与添加了扩展名 .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
}
此错误与
A positional parameter cannot be found that accepts argument "+xxx".
您需要将第二个 Get-ChildItem
(ls
) 和 New-Item
包装在 ForEach-Object
语句中。另外,不要将 $_.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
}
}