Home > database >  Is there a way to do a check if a command is run from a script or in the host directly?
Is there a way to do a check if a command is run from a script or in the host directly?

Time:11-26

Afternoon and Happy Thanksgiving,

I have a logging function (that is part of a custom module) that uses the name of the script it's run from as the log file name. That all works fine, but if I wanted to use the logging function outside of a script, it errors out as it's creating a too long file name.

Is there a way to run a check so that if the function is called within a script it will use the script name, or if it's run direct in the console it either prompts for a name, or uses a default naming scheme.

Here's how I currently pull the script name from the function

(Get-ChildItem $MyInvocation.PSCommandPath | Select -Expand Name).Replace(".ps1",".log")

When run in a script

PS> .test.ps1
Write-Log "Hello World"

Outputs a log file named test.log

but if I run the same command direct to the console

Write-log "hello world"

you get the following error as it's collecting all the file names from the current directory

New-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260
characters, and the directory name must be less than 248 characters.

CodePudding user response:

I believe you could do it this way, checking the invocation's CommandOrigin, if it's internal, return the $PSCommandPath else, return the current location, in both cases changing the extension. I truly believe you should not go this route, your function should take a log path as argument.

function Write-Thing {
    # assume `CommandOrigin` is Runspace,
    # use current location if ran from host? your choice
    $Path = [IO.Path]::ChangeExtension($pwd.Path, 'log')

    # check if it's being called internally
    if($MyInvocation.CommandOrigin -eq 'Internal') {
        $Path = [IO.Path]::ChangeExtension($PSCommandPath, 'log')
    }

    # output the path for testing
    $Path
}

Write-Thing
  • Related