33// ReSharper disable UnusedAutoPropertyAccessor.Global
44// ReSharper disable UnusedMember.Global
55
6+ using System;
7+ using System.IO;
8+ using System.Linq;
9+
10+
611namespace PSLogging.Commands
712{
813 using System.Management.Automation;
9-
14+
1015 [Cmdlet(VerbsLifecycle.Enable, "LogFile")]
1116 public class EnableLogFileCommand : PSCmdlet
1217 {
@@ -34,7 +39,7 @@ public ScriptBlock OnError
3439 set { errorCallback = value; }
3540 }
3641
37- [Parameter(Mandatory = true ,
42+ [Parameter(Mandatory = false ,
3843 Position = 0,
3944 ParameterSetName = "New")]
4045 public string Path
@@ -61,17 +66,42 @@ protected override void EndProcessing()
6166
6267 if (ParameterSetName == "New")
6368 {
64- logFile = new LogFile(path, streams, errorCallback);
69+
70+ logFile = new LogFile(string.IsNullOrEmpty(path) ? GetDefaultLogFileName() : path, streams, errorCallback);
6571 WriteObject(logFile);
6672 }
6773 else
6874 {
6975 logFile = inputObject;
7076 }
7177
78+ // Initiate a log file
79+ logFile.CheckDirectory();
80+ if (!File.Exists(logFile.Path) && !string.IsNullOrEmpty(MyInvocation.ScriptName))
81+ {
82+ File.AppendAllText(logFile.Path, $"******************\r\nScript Location: {MyInvocation.ScriptName} \r\n******************\r\n");
83+ }
7284 HostIOInterceptor.Instance.AttachToHost(Host);
7385 HostIOInterceptor.Instance.AddSubscriber(logFile);
7486 }
87+
88+ private string GetDefaultLogFileName()
89+ {
90+ var dateString = DateTime.Now.ToString(@"yyyy-MM-dd_HHmm");
91+
92+ var scriptName = string.Empty;
93+ var directoryName = ".\\Log";
94+
95+ if (!string.IsNullOrEmpty(this.MyInvocation.ScriptName))
96+ {
97+ var directoryInfo = new DirectoryInfo(MyInvocation.ScriptName);
98+ scriptName = directoryInfo.Name.Remove(directoryInfo.Name.IndexOf(".", StringComparison.Ordinal));
99+ directoryName = directoryInfo.Parent?.FullName;
100+ }
101+ directoryName = $@"{directoryName}\Log\{scriptName}_Log_{dateString}.txt";
102+
103+ return directoryName;
104+ }
75105 } // End AddLogFileCommand class
76106}
77107
0 commit comments