Naigel
Naigel

Reputation: 9644

Print in a log file the line number

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

Upvotes: 0

Views: 839

Answers (2)

jbockle
jbockle

Reputation: 643

try wrapping in $(). For example:

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

Upvotes: 1

Musaab Al-Okaidi
Musaab Al-Okaidi

Reputation: 3784

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.

Upvotes: 1

Related Questions