0

I am totally new to PowerShell, and trying to write a simple script to produce log file. I searched forums and could not find the answer for my question. I found the example in the net, that I thought would be useful, and applied it to my script:

## Get current date and time. In return, you’ll get back something similar to this: Sat January 25 10:07:25 2014
$curDateTime = Get-Date
$logDate = Get-Date -format "MM-dd-yyyy HH:mm:ss"
$LogPath = "C:\Temp\Log"
$LogName = "log_file_" + $logDate + ".log"
$sFullPath = $LogPath + "\" + $LogName

<#
    param(
    ## The path to individual location files
    $Path,

    ## The target path of the merged file
    $Destination, 

    ## Log path
    $LogPath,

    ## Log name   
    $LogName

    ## Full LogFile Path
    ## $sFullPath = $LogPath + "\" + $LogName
)
#>

Function Log-Start {
    <#
    .SYNOPSIS
        Creates log file
    .DESCRIPTION
        Creates log file with path and name that is passed. 
        Once created, writes initial logging data
    .PARAMETER LogPath
        Mandatory. Path of where log is to be created. Example: C:\Windows\Temp
    .PARAMETER LogName
        Mandatory. Name of log file to be created. Example: Test_Script.log
    .INPUTS
        Parameters above
    .OUTPUTS
        Log file created
    #>

    [CmdletBinding()]
    Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName)

    Process {        
        ## $sFullPath = $LogPath + "\" + $LogName

        # Create file and start logging
        New-Item -Path $LogPath -Value $LogName –ItemType File

        Add-Content -Path $sFullPath -Value "***************************************************************************************************"
        Add-Content -Path $sFullPath -Value "Started processing at [$([DateTime]::Now)]."
        Add-Content -Path $sFullPath -Value "***************************************************************************************************"
        Add-Content -Path $sFullPath -Value ""
    }       
}

Set-StrictMode -Version "Latest"

Log-Start
....

The question is how can I make the Log_Start function to use variables I assigned in the beginning of the script, or it is not possible with declaration of [CmdletBinding()] and function itself. If I try to run it the way it is coded it is prompting me to enter the path and logname, I thought it should have used what I already defined. Apparently I am missing the concept. I surely can just assign the values I need right in the param declaration for the function, but I am planning to use couple of more functions like log-write and log-finish,and would not want to duplicate the same values. What am I missing?

2 Answers 2

1

You defined your custom parameters at the top of your script and now you must pass them them to the function by changing

Log-Start

line to read

Log-Start $LogPath $LogName

Though you would be better off naming your parameters differently to avoid confussion. You don't really need CmdletBinding() declaration unless you plan to utilise common parameters like -Verbose or -Debug with your function so you could get rid of the following 2 lines:

[CmdletBinding()]
Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName)

and your script would still work.

Sign up to request clarification or add additional context in comments.

4 Comments

Should not it be like that? Log-Start -LogPath $LogPath -LogName $LogName not just $logpath and $logname?
it does not ask for the input anymore, but gives the following error:New-Item : The given path's format is not supported. At zzz.ps1:82 char:17 + New-Item <<<< -Path $LogPath -Name $LogName –ItemType File + CategoryInfo : NotSpecified: (:) [New-Item], NotSupportedException + FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.NewItemCommand
You are trying to create a file with ":" in it, change $logDate = Get-Date -format "MM-dd-yyyy HH-mm-ss". As to the input, it is positional so you don't have to use -LogPath and -LogName as long as your parameters are passed in the right order.
Ye, totally forgot that Windows does not like ':' in file names, changed the format and it worked.But let me ask you another question. What would be the best command to use, if I want to run the script in two different environments, and would like to create the file with all the parameters and do kind of "include" in my script and pull all of the parms from there? Appreciate your suggestions.
0

If you want to include settings from a config file, one approach is hashtables. Your config file would look like this:

logpath=c:\somepath\
server=server.domain

Then your script would have an extra var pointing to a config file and a function to import it:

$configFile = "c:\some.config";  
function GetConfig(){  
    $tempConfig = @{};  
    $configLines = cat $configFile -ErrorAction Stop;  
    foreach($line in $configLines){         
        $lineArray = $line -split "=";          
        $tempConfig.Add($lineArray[0].Trim(), $lineArray[1].Trim());        
    }  
    return $tempConfig;
}  
$config = GetConfig  

You can then assign config values to variables:

$LogPath = $conifg.Item("logpath")  
$server = $conifg.Item("server")  

Or use them access directly

$conifg.Item("server")  

7 Comments

I defined the configfile exactly like you suggested,copied the function into my code, and very first line after all function definitions read: $config = GetConfig $configFile. And the error I received was [DBG]>>> You cannot call a method on a null-valued expression. At xxx.ps1:73 char:87 + $tempConfig.Add($lineArray[0].Trim(), $lineArray[1].Trim(), $lineArray[2].Trim <<<< ()); + CategoryInfo : InvalidOperation: (Trim:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
You must have not used my code exactly as your error: $tempConfig.Add($lineArray[0].Trim(), $lineArray[1].Trim(), $lineArray[2].Trim shows you added $lineArray[2].Trim I presume you amended the code to account for more than 2 key/value pairs in the config file but the function of that code line is to split each config line on = character. Just add more key/value pairs to your config file and they will be imported ok ;)
they do not. have another name/value pair in my config, file, and it gives me the error. when I use only two variables works just fine. I guess I am doing something wrong
I'm not sure I understand your answer, can you be more specific? Above code works without a need for change no matter how many key/value pairs you have in your config as long as keys are unique(and no blank lines). The error you attached shows extra code being executed $lineArray[2].Trim which is causing the problem.
Yes it does, I did not have to add another $lineArray item 2. Thanks for your help
|

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.