RayofCommand
RayofCommand

Reputation: 4244

Script working in PS3 but not in PS2 , I can't find the exact error "Bad Argument to operator '-gt'

my script to find files bigger than x works fine for me and my powershell 3.0. But on our server we just have powershell 2.0 and I can't make it work correctly.

The error is the following :

Bad Argument to Operator '-gt' Could not compare "3841" to "10MB". Error cannot convert "10MB" to type "System.Int64" Error: "Input string was not in a correct format."".

My script is here, I tried to change the 10MB value to just "10" but than it compares to kb I guess. that's not what i wanted! Any ideas?

Param(
  [ValidateScript({test-path -path $_ -pathtype container})]
  [string]$targetfolder,
  [string]$size
)

function getfilesbigger 
{
$colItems =  (get-childitem  "$targetfolder" -recurse | where {$_.length -gt "$size" } | tee-object -variable allfiles | measure-object -property length -sum)
$allfiles | foreach-object {write-host $_.FullName ("{0:N2}" -f ($_.Length / 1MB)) "MB" -ForegroundColor "green" }
write-host "Collected all files bigger than $size from folder $targetfolder " -foregroundcolor "darkgreen"
"Number of files: "+ $colItems.count + [Environment]::NewLine + "Size of all files "+"{0:N2}" -f ($colItems.sum / 1MB) + " MB" 
}

getfilesbigger

Upvotes: 0

Views: 763

Answers (1)

vonPryz
vonPryz

Reputation: 24071

The reason is that size has been defined explicitly as a string:

Param(  ...   
[string]$size)

Thus, Powershell won't convert 10mb automatically to integer 10485760 as usual, but instead uses it as a string. For working version, just use int like so,

Param(
  [ValidateScript({test-path -path $_ -pathtype container})]
  [string]$targetfolder,
  [int]$size
)

Edit:

It works on my 2.0 environment well. Try adding a .GetType() call to see what's going on. Like so,

function getfilesbigger 
{
$size.gettype()
$colItems = ...

The result for gettype call ought to be

IsPublic IsSerial Name                BaseType
-------- -------- ----                --------
True     True     Int32               System.ValueType

What do you get?

Upvotes: 2

Related Questions