Creating a log for a powershell command - powershell

I have a simple command to create a CSV file in powershell. Is there a way to log this information separate from the file? I will be needing to manipulate the CSV file, so I don't want to rely on it being my only way of logging the data.

You can also export the output of commands by using the > and >> operators.
example:
You can write all of the Adobe services and their information to a file with this code:
get-service -DisplayName Adobe* > C:\services.txt
if you wanted to append to that with Windows services:
get-service -DisplayName Windows* >> C:\services.txt
so if you wanted to export your CSV to a file you can easily do so by adding a > at the end of the command pointing to the filename you wish to export it to:
> C:\Log_$date.csv
and if you ever needed to append more logs you can simply do so by using the >>
>> C:\Log_$date.csv
if you use > it will overwrite and existing data in the file with new data. >> appends.

If you need a log for people who are in charge of the production you can add your own application log using dedicated Cmdlets. A the moment I create and use one PowerShell log for all my scripts to publish details of the execution (information) and errors (in coordination with good exception handling) for people who are in charge of the production. You can dedicate a log for one script (as it exists a log for DNS etc.)
Here is an example :
# List of logs
Get-EventLog -list
# Creating your own log
New-EventLog -LogName "SlxScripting" -Source "MaSource"
# List of logs
Get-EventLog -list
# Writting in your own log
Write-EventLog -LogName "SlxScripting" -EventId 12 `
-Message "Mon Message"
-Source "MaSource" -EntryType Warning
# Reading in your own log
Get-EventLog -LogName "SlxScripting"
# Suppressing your log
Remove-EventLog -LogName "SlxScripting"

Related

How can I read analytical Windows events from 'Applications and Services Logs' using PowerShell?

I use Get-EventLog to read events. Using this cmdlet, I can successfully read the System and the Security event logs for example. I can also list all available logs by issuing the following command:
Get-EventLog -LogName * | Select-Object -Property Log
Output:
Log
---
Application
HardwareEvents
Internet Explorer
Key Management Service
OAlerts
Parameters
Security
State
System
Windows PowerShell
But this list does not contain all of the logs you can find under Applications and Services logs, e. g.: I'd like to read the events from this path that can be traversed inside the Event Viewer:
Applications and Services Logs > Microsoft > Windows > DNS-Server > Analytical
I'm doing this on a Windows DNS-Server with Show Analytic and Debug Logs enabled under View and also a configured and enabled Analytical log for DNS-Server.
Tl;dr:
Use Get-WinEvent instead and add the -Oldest parameter:
Get-WinEvent -LogName Microsoft-Windows-DNSServer/Analytical -Oldest
Get-EventLog is a legacy cmdlet to read the Windows event log and it cannot be used to read all available event logs (look for the note in the documentation of this cmdlet):
Get-EventLog uses a Win32 API that is deprecated. The results may not be accurate. Use the Get-WinEvent cmdlet instead.
With Get-WinEvent you can list all available logs using Get-WinEvent -ListLog * or you can filter for all DNS related logs:
Get-WinEvent -ListLog *DNS* | Select-Object -Property LogName
Output:
LogName
-------
DNS Server
Microsoft-Windows-DNS-Client/Operational
Microsoft-Windows-DNSServer/Audit
Add the -Force parameter to also see Debug and Analytical events:
LogName
-------
DNS Server
Microsoft-Windows-DNS-Client/Operational
Microsoft-Windows-DNSServer/Analytical
Microsoft-Windows-DNSServer/Audit
You can read the events by passing those names to the -LogName parameter:
Get-WinEvent -LogName Microsoft-Windows-DNSServer/Audit
You'll get an error when trying to read the Microsoft-Windows-DNSServer/Analytical log:
Get-WinEvent : The Microsoft-Windows-DNSServer/Analytical event log can be read only in the forward chronological order because it is an analytical or a debug log. To see events from the Microsoft-Windows-DNSServer/Analytical event log, use the Oldest parameter in the command.
So just add -Oldest and you are good to go:
Get-WinEvent -LogName Microsoft-Windows-DNSServer/Analytical -Oldest

Check if last created file exists and create an event log entry with PowerShell

I'm writing files with PowerShell to store specific information in it.
I also want to create windows event log entries to check if the file which was "newly" created is really there.
New-EventLog -LogName System -Source "Files I store information in"
Write-EventLog -LogName System -Source "Files I store information in" -EntryType Information -EventId 1 -Message "Information written to file script started"
$FilePath = "C:\Path\Files"
command.exe -Out-File $FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm).file
Basically I'm searching for a way to verify if the above command.exe created a file. I'm not sure how to do that when I'm using the "get-date" option to append this to the file name.
If the file was created I want to create a successful event log entry. If it wasn't created I want to create a non successful event log entry.
Anyone a hint on this ?
Try catch, would work
try{
$FilePath = "C:\Path\Files"
command.exe -Out-File $FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm).file
--write below successfull log entry
you also could add more checks like below
if (test-path "$FilePath\${env:computername}_$(get-date -f dd-MM-yyyy-hhmm)"){
write here successfull log entry
}
else
{
---write here unsuccessfull log entry
}
catch{
---write here unsuccessfull log entry
}

Forward application log to windows Event log

I want to create a new EventLog for an application running on my server and the log should be taken from the default log file of the application.
Any idea on how to achieve this??.
Do you mean event source?
PowerShell would be
New-EventLog command found here
MSDM New-eventLog
Edit after more detail supplied.
Basic principle of what you want is to query the log file and write the lines found into a event log. This is done like the below:
#Get the content of the error log, gets the top 10 lines ONLY!!
$GetLog = Get-Content -Path D:\Errorlog.txt -totalcount 10
#Now take the data found and write it to the event log under the source and log below
Write-EventLog -LogName "Application" -Source "My Application" -Eventid 1001
-EntryType Error -Message "$Getlog" -Category 1

SCCM Compliance state always 'Compliant' when remediation script runs

We're trying to use SCCM 2012 R2 to run some checks on clients and fix problems when needed. For this we use the PowerShell 'Script' option.
Problem description:
When a 'Discovery script' reports ‘Non-Compliant’ the ‘Remediation script’ is launched. Regardless of the output of the ‘Remediation script’, the result in the report on the client in ‘Configuration Manager > Configurations’ is always ‘Compliant’ even when the ‘Remediation script’ failed to fix the issue and as a result has different output then defined in the ‘Rules for compliance conditions’.
It seems that from the moment a ‘Remediation script’ is selected, the output of the SCCM Compliance State is always ‘Compliant’.
Example:
- Situation:
When there are files or folders in the folder ‘C:\Users\me\Downloads\Input_Test’ the ‘Discovery script’ reports ‘Not compliant to anything’ and kicks of the ‘Remediation script’. The remediation script takes action and can’t fix the problem so it reports back something else then ‘Compliant’, like ‘Non-Compliant’. The SCCM Compliance State should say after execution of the ‘Remediation script’: ‘Non-Compliant’ (which is not the case).
- PowerShell Discovery script:
$Paths = Get-ChildItem -Path 'C:\Users\me\Downloads\Input_Test' | Select -ExpandProperty FullName
New-EventLog -LogName Application -Source SCCMCompliance
if ($Paths) {
$Compliance = 'Non-Compliant'
Write-EventLog -LogName Application -Source SCCMCompliance -EntryType Warning -EventID 1 -Message “Discovery script: Non-Compliant”
}
else {
$Compliance = 'Compliant'
Write-EventLog -LogName Application -Source SCCMCompliance -EntryType Information -EventID 0 -Message “Discovery script: Compliant”
}
$Compliance
- PowerShell Remediation script:
Write-Output 'Non-Compliant'
Write-EventLog -LogName Application -Source SCCMCompliance -EntryType Warning -EventID 1 -Message “Remediation script: Non-Compliant $Paths”
- SCCM Rules for compliance conditions:
- SCCM Compliance State in the Configuration Manager:
In the Windows event viewer all steps can be tracked easily. Am I missing something super obvious here?
After much pain and hurt myself and #DarkLite1 have found that SCCM does not check compliance state after it has performed remediation
From the moment you use a 'Remediation script' the only 2 possible Compliance statusses are: 'Compliant' or 'Exit with error code'. This is done in PowerShell with 'Exit 1'.
For more information please see.
https://social.technet.microsoft.com/Forums/en-US/0f0f3e6f-7e9f-4376-a926-fc0b6aef5bf1/sccm-compliance-state-always-compliant-when-remediation-script-runs?forum=configmanagersecurity

How should I create a reusable "log" object in Powershell?

I'm new to PowerShell and am writing my first application. The application will check the state of a Windows service and (depending on a number of factors) can do a number of things, such as stop it, start it or restart it. I need to produce a log showing what it's done. I'm wanting to use modules so my code will be reusable and also flexible (for example, if I schedule it to run automatically, the log will need to be sent by e-mail or written to a text file, if I run it manually, I will want it outputting with something like Write-Host).
My question is, how do I create the log? In Java for example, I would use a log class with public void addToLog(String log) and public String getLog() methods which just deal with strings and leave it up to e-mail/display it etc.
I have a quite complex set of scripts for installing our platform (relying on BizTalk, SQL Server, Enterprise Single Sign-on, IIS, Enterprise Library and a few other things). These scripts start and stop services, BizTalk orchestrations, create or update databases and so on. I tried several things for logging and, finally, I picked log4net for its ease of use and flexibility. Using it from PowerShell is a breeze.
Refer to a similar question which I had asked on SO few days ago. Might help. I am using the same Logging Module referred there in the ANSWER - Powershell: Debug in Production / Good Exception Handling
If you need a log for people who are in charge of the production you can add your own application log using dedicated Cmdlets. A the moment I create and use one PowerShell log for all my scripts to publish details of the execution (information) and errors (in coordination with good exception handling) for people who are in charge of the production. You can dedicate a log for one script (as it exists a log for DNS etc.)
Here is an example :
# List of logs
Get-EventLog -list
# Creating your own log
New-EventLog -LogName "SlxScripting" -Source "MaSource"
# List of logs
Get-EventLog -list
# Writting in your own log
Write-EventLog -LogName "SlxScripting" -EventId 12 `
-Message "Mon Message"
-Source "MaSource" -EntryType Warning
# Reading in your own log
Get-EventLog -LogName "SlxScripting"
# Suppressing your log
Remove-EventLog -LogName "SlxScripting"