Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用powershell脚本删除小于x kb的文件_Powershell - Fatal编程技术网

如何使用powershell脚本删除小于x kb的文件

如何使用powershell脚本删除小于x kb的文件,powershell,Powershell,您好,我有1个文件夹,包含许多子文件夹和许多.txt文件。我想删除.txt文件,特别是小于10kb 我试过这个,但每次都会出错 $Dir = "C:\Users\*************\Desktop\test" '$SizeMin' = 10 #KB Get-ChildItem -Path $Dir -Recurse | Where {$_.Length / 10KB -lt $SizeMin} | Remove-Item -Force 表达式或语句中出现

您好,我有1个文件夹,包含许多子文件夹和许多
.txt
文件。我想删除
.txt
文件,特别是小于10
kb

我试过这个,但每次都会出错

$Dir  = "C:\Users\*************\Desktop\test"
'$SizeMin' = 10 #KB

Get-ChildItem -Path $Dir -Recurse | 
    Where {$_.Length / 10KB -lt $SizeMin} | 
        Remove-Item -Force
表达式或语句中出现意外标记“$SizeMin”。 +CategoryInfo:ParserError:(:)[],ParentContainerErrorRecordException +FullyQualifiedErrorId:意外终止“


此代码可以帮助您删除给定目录中小于10kb(10000字节)的文件:

$path = 'C:\Users\*************\Desktop\test'
Get-ChildItem $path -Filter *.stat -recurse |?{$_.PSIsContainer -eq $false -and $_.length -lt 10000}|?{Remove-Item $_.fullname -WhatIf}

无论何时学习新的东西,尤其是编码,我发现最好把所有东西都分解一下,先花时间写一段代码,然后再压缩它。您可以使用并编辑以下绘制的代码,以便更好地了解正在发生的事情:

#Root directory
$dir = "C:\Users\*************\Desktop\test"

#Minimum size for file
$minSize = 10

#Throwing through every item in root directory
Get-ChildItem -Path $dir -Recurse | ForEach-Object{

    #Check if file length if less than 10
    if ($_.Length / 10KB -lt $minSize){
        Remove-Item $_ -Force
    }else{
        #File is too big to remove
    }
}

感谢您的帮助代码正在工作,但文件没有删除。@BatuhanOzoguz删除
-whatif
,以确保代码删除了所需的文件。我将其删除。但仍然将
?{Remove Item
更改为
ForEach对象{Remove Item
。最好使用完整的cmdlet名称,而不是别名,以防止出现类似错误。
?==>Where Object
%=>ForEach Object
。此外,不要试图将所有内容强制放在一行中。谢谢@Theo!如果这对他有帮助,请编辑答案!!您的代码中有两个错误。[grin]//[1]可能导致您列出错误的原因是
$SizeMin
定义周围的单引号,这使其成为字符串而不是变量。删除引号后,该部分将正常工作。//2]您正在除以
10KB
…这会得到
10KB
块…但实际上您需要
1KB
块。[咧嘴笑]将
10KB
更改为
1KB
,您将使该部件正常工作。非常感谢您的努力和各种建议。İt成功了。@BatuhanOzoguz您的欢迎:)请投票并在回答您的问题时标记适当的回答