0

I'm trying to manage some non-standard error in my functions (like a wrong input text), and I want to track those errors by writing a sort of log in a variable. I'm trying to write also the line number, and this is my code

$someVar = "line $($MyInvocation.ScriptLineNumber): at least 2 arguments needed, function has been called with only $args.Count arguments"

Sometimes it returns the correct number and sometimes it doesn't. Is this the correct way? Is there another method?

EDIT: I found that this problem could be related to an unconventional way to execute scripts that I use in order to bypass a permission problem on a specific the machine. I'll post a more detailed example as soon as I can

Naigel
  • 9,086
  • 16
  • 65
  • 106
  • Can you give more context? As far as I know this should work, and I can't reproduce a situation where it doesn't... – Poorkenny Feb 15 '13 at 13:24

2 Answers2

1

Any reason why you're not using param in your functions and making them mandatory?

Function A()
{
   Param
   (
      [Parameter(Mandatory=$true)][String]$Arg1,
      [Parameter(Mandatory=$true)][String]$Arg2
   )
   Write-Host "$Arg1 $Arg2"
}

If you run this function without any arguments then it will throw an error asking for the mandatory arguments.

Musaab Al-Okaidi
  • 3,734
  • 22
  • 21
  • this is only a stupid example, please focus only on printing the correct line number – Naigel Feb 15 '13 at 11:52
  • The powershell error that is thrown will include a line number, but if you need it to be in the specific format outlined above then that's different. – Musaab Al-Okaidi Feb 15 '13 at 11:57
1

try wrapping in $(). For example:

$someVar = "line $($MyInvocation.ScriptLineNumber): at least 2 arguments needed, function has been called with only $($args.Count) arguments"
jbockle
  • 633
  • 5
  • 11