PowerShell远程删旧日志脚本报错:Cannot index into null array
问题:PowerShell脚本删除远程旧日志时触发空数组索引错误
我写了一段PowerShell脚本,用来遍历远程计算机的指定文件夹,删除15天以上的日志文件:
param( [Parameter(Mandatory=$true)] [string] $remoteHost = $args[0], [boolean] $run = $args[1] ) $rootFolder = '\d$\Projects\'; $folders = 'Folders1\logs\','Folders2\logs\','Folders3\logs\'; foreach($folder in $folders){ $fullPath = ('\\' + $remoteHost + $rootFolder + $folder + '*.log*'); if($run){ Get-ChildItem $fullPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-15)} | Remove-Item -ErrorAction SilentlyContinue; } else{ Get-ChildItem $fullPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-15)} | Remove-Item -ErrorAction SilentlyContinue -WhatIf; } }
运行时出现以下错误:
cmdlet at command pipeline position 1 Supply values for the following parameters: remoteHost: PRLVWEPMSAP04 Cannot index into null array. + CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : NullArray
请问这个报错是因为部分文件夹里没有符合条件的旧日志文件导致的吗?
解答
这个错误不是因为文件夹里没有符合条件的日志文件造成的。
错误原因分析
脚本的参数定义存在冲突:
$remoteHost被设置为Mandatory=$true,意味着运行脚本时如果没通过参数传递,会弹出提示让你输入该值。- 但你同时给
$remoteHost和$run绑定了$args[0]、$args[1],当你通过交互式输入remoteHost时,$args数组是空的,这时候执行$run = $args[1]就会尝试索引一个空数组,直接触发"Cannot index into null array"错误。
如果是文件夹里没有符合条件的文件,Get-ChildItem会返回空集合,后续管道不会执行Remove-Item,但只会触发"找不到文件"的警告,而这个警告已经被-ErrorAction SilentlyContinue忽略了,不会出现空数组索引的错误。
修复方案
修改参数定义,去掉$args的绑定,改用参数默认值或者明确的参数传递:
param( [Parameter(Mandatory=$true)] [string] $remoteHost, # 给run参数设置默认值,未传参时默认执行模拟删除(-WhatIf) [boolean] $run = $false ) $rootFolder = '\d$\Projects\'; $folders = 'Folders1\logs\','Folders2\logs\','Folders3\logs\'; foreach($folder in $folders){ $fullPath = Join-Path -Path "\\$remoteHost$rootFolder" -ChildPath "$folder*.log*" $oldLogs = Get-ChildItem $fullPath -ErrorAction SilentlyContinue | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-15)} if($run){ $oldLogs | Remove-Item -ErrorAction SilentlyContinue } else{ $oldLogs | Remove-Item -ErrorAction SilentlyContinue -WhatIf } }
(额外优化:用Join-Path拼接路径更规范,避免手动拼接时的路径分隔符问题)
内容的提问来源于stack exchange,提问作者B Tran
相关产品推荐
相关产品推荐

