1

How can i change this string format into a callable function?

[string]::Format("param {0} param {1}, param {2} ",$param0, $param1, $param2)

So for example, I don't need to use [string]::format() each time i want to write-host

Something like the below.

logMessage("param {0} param {1}, param {2}", ,$param0, $param1, $param2)

Just not sure how to turn the [string]::format into a function.

1 Answer 1

1

How about something like:

function Log-Message {
    param(
        [string]$Format,
        [Array]$Params = ""
    )

    $msg = [string]::Format( $Format, $Params )
    # Do something to actually log it, instead of just printing it back out
    # like I do on the next line...
    $msg
}

# For Testing Above Function...
$param0 = "foo"
$param1 = "bar"
$param2 = 42

# Using Parameter Names (cleaner)
Log-Message -Format "param {0} param {1} param {2}" -Params ( $param0, $param1, $param2 )
# Closer to what you were asking for...
Log-Message "param {0} param {1} param {2}" $param0, $param1, $param2

Note: in the second example, there is no comma between the format string and the first parameter.

Running the above will give you something like the following:

param foo param bar param 42  
param foo param bar param 42
Sign up to request clarification or add additional context in comments.

6 Comments

So i did what you suggested, and I am just doing a simple Write-Host($msg); And it's throwing an error. ERROR: Log-Message : The term 'Log-Message' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or ERROR: if a path was included, verify that the path is correct and try again.
Which part of the above did you do? Somehow the above function isn't getting defined. If you saved it to a file and ran it, did you load it with . -- For instance . .\log-message.ps1?
The Log-Message is being called within the program to write to the host. I am not specifically calling Log-message from the command line.
function Log-Message { param ( [string]$Format, [Array]$Params ) $msg = [string]::Format($Format, $Params); Write-Host($msg); }
Ok so it seems to be working now. The only issue is what if I don't have any params? I kind wanted params to be optional.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.