powershell search a certain line in a log file and create an event in event viewer - powershell-4.0

I have a problem; I would like to automatize something:
I have a *.log file which contains lines of the logged data;
I need to know how to create a script in powershell to search for a certain line, and if that line equals 0, to create an event in the windows event viewer. can somebody please help?
my log looks like this:
data = 1
test = 5
com = 5
connections = 1
When connection = 0 in the *.log file, it should create an event in the event viewer.
If possible as a secondary task I would like to run this script two times a day; at 15:00 and at 00.
Thank you!
tried to find the = 0 with powershell
Select-String -Path C:\Users\user\test.log -Pattern '= 0'
IF (Pattern '= 0')
{
Write-EventLog –LogName Application –Source “My Script” –EntryType
Information –EventID 30000
}
error received:
Pattern : The term 'Pattern' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or
if a path was included, verify that the path is correct and try again.
At line:2 char:5
+ IF (Pattern '= 0')
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (Pattern:String) [],
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

I managed to solve this :) :
Make sure you run Powershell as admin and
you have rights with the command:
set-executionpolicy remotesigned
in powershell, and then:
$EVENT_SOURCE="verificare.ps1"
if ([System.Diagnostics.EventLog]::SourceExists($EVENT_SOURCE) -eq $false) {
New-EventLog -LogName Application -Source ‘$EVENT_SOURCE’
}
$SEL = Select-String -Path C:\Users\user\test.log -Pattern "test =0"
if ($SEL -ne $null)
{
Write-EventLog -LogName Application -Source $EVENT_SOURCE -Message “found xxxxx in
log” -EventId 30000 -EntryType information
}
else
{
echo Not Contains String
}

Related

Remove-Item : Cannot remove item because it is being used by another process

The problem is very easy to understand.
Yesterday I have installed en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso and the file is hanging on my Desktop.
When I try to delete it through Remove-Item .\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso the Terminal fires back with the error:
Remove-Item : Cannot remove item C:\Users\franc\OneDrive\Desktop\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso: The process cannot access the file
'C:\Users\franc\OneDrive\Desktop\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso' because it is being used by another process.
At line:1 char:1
+ Remove-Item .\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.i ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Users\franc\...vd_9fda4a05.iso:FileInfo) [Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
So I tried to find out what is handling that file:
$handleOut = handle
foreach ($line in $handleOut) {
if ($line -match '\S+\spid:') {
$exe = $line
}
elseif ($line -match 'C:\\Users\\franc\\OneDrive\\Desktop\\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso') {
"$exe - $line"
}
}
But the answer was:
System pid: 4 \<unable to open process> - 7540: File (R--) C:\Users\franc\OneDrive\Desktop\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso
System pid: 4 \<unable to open process> - 7B18: File (RW-) C:\Users\franc\OneDrive\Desktop\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso
I ultimately used Process Explorer and I found out that what is handling the file is OneDrive.
I stopped OneDrive but the problem persists.
Any suggestion?
This is sheerly speculation, but it sounds like you need to unmount the iso: https://www.digitalcitizen.life/mount-unmount-iso-file-explorer/
Have you tried running the command with the -Force parameter?
Remove-Item .\en_visual_studio_2015_shell_isolated_x86_dvd_9fda4a05.iso -Force

Powershell - Export users Member Of.. groups according to csv users list

Trying to import a csv file with list of users and export a csv file with these users + the groups they are member of..
I tried the script from this Topic:
Import list of users - Export List of users and Groups
But it didn't work.
Example of my user list file (test_alex.csv):
Name
----
Alex Alex
Test Test
You Me
That's the error i get:
Get-AdUser : The search filter cannot be recognized At line:2 char:29 + ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)' ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Maybe not the best solution from a powershell expert, but it do exactly what i was needed.
First Download this script:
https://gallery.technet.microsoft.com/PowerShell-Get-All-Group-167a9ce7#content
Then open powershell ISE and use this script with the the script you
downloaded.
My File name: userlist.csv
$user = "userlist.csv"
$content = Get-Content $user
$content | Foreach {$_.TrimEnd()} | Set-Content $user
C:\temp\TheActualScripts\Multiple_UserGroup_InputFile.ps1 -CSVFile "C:\temp\copy\$user"
Rename-Item -Path "C:\temp\TheActualScripts\ReportFile.txt" -NewName "$user"
Then you will get the output file named "ReportFile.txt" inside the folder where is the script located, for me it was:
C:\temp\TheActualScripts\ReportFile.txt
The last line of the script change the name of the file "ReportFile.txt" to the name of the "userlist" file.
IMPORTANT
Pay attention that there is no blank spaces inside the users files that you are working with them, because if there are, the script won't work, it will just give you an empty "ReportFile.txt" file.

Why is AWS-ConfigureWindowsUpdate SSM Run Command Failing?

Enabling or Disabling Windows Updates with SSM Run Command
AWS-ConfigureWindowsUpdate
When running the command, it downloads a PowerShell script to my EC2 at "C:\ProgramData\Amazon\Ec2Config\Downloads\aws_psModule\" with a random name
When the PowerShell script executes, it downloads "Amazon.ConfigureWindowsUpdate-1.2.zip" to "%Temp%" and then unzips it to "%WinDir%\System32\WindowsPowerShell\v1.0\Modules"
The script looks to be failing at Line 32 with the .CopyHere function where it is unzipping
Pastebin of Powershell Script: 1b3hh3oy.k51.ps1
(New-Object -Com Shell.Application).namespace($powerShellModuleLocation).CopyHere((New-Object -Com Shell.Application).namespace($tempLocation).Items(), 16)
Output:
Obtaining instance region from instance metadata.
Downloading ConfigureWindowsUpdate PowerShell module from S3.
Verifying SHA 256 of the ConfigureWindowsUpdate PowerShell module zip file.
ExtractingConfigureWindowsUpdate zip file contents to the Windows PowerShell module folder.
--------------ERROR-------------- C:\ProgramData\Amazon\Ec2Config\Downloads\aws_psModule\1b3hh3oy.k51.ps1 :
Exception thrown while downloading ConfigureWindowsUpdate
PowerShell module with message: Exception has been thrown by the target of an invocation.
At line:1 char:1
+ . &apos;C:\ProgramData\Amazon\Ec2Config\Downloads\aws_psModule\1b3hh3oy.k51.ps1&apos; ; ex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,1b3hh3oy.k51.ps1
Other Details:
- I have micro EC2 of Windows Server Core 2012 R2 running
- I have successfully used AWS-RunPowerShellScript command a few times from AWS Console
- I ran AWS-ConfigureWindowsUpdate through the AWS Console and it fails
- I remote connected to server and ran the powershell script with administrator privileges and get same error
You are correct, the exception is occurring on the call out to the Shell namespace for extracting the cmdlet payload. The COM namespace for Shell access is not included in the Core release so the ConfigureWindowsUpdate script fails when extracting the cmdlet.
Currently there is a workaround available for Windows Server Core AMIs and a more complete fix is currently being investigated. The workaround involves creating a custom ConfigureWindowsUpdate document with a tweak to fix the extraction process.
Below is a function that would replace the call to
(New-Object -Com Shell.Application).namespace($powerShellModuleLocation).CopyHere((New-Object -Com Shell.Application).namespace($tempLocation).Items(), 16)
function ExtractZipCoreOs($zipFilePath, $destPath) {
try
{
[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
$zip = [System.IO.Compression.ZipFile]::OpenRead($zipFilePath)
foreach ($item in $zip.Entries) {
$extractedPath = Join-Path $destPath $item.FullName
if ($item.Length -eq 0) {
if ((Test-Path $extractedPath) -eq 0) {
mkdir $extractedPath | Out-Null
}
} else {
$fileParent = Split-Path $extractedPath
if ((Test-Path $fileParent) -eq 0) {
mkdir $fileParent | Out-Null
}
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($item,(Join-Path -Path $powerShellModuleLocation -ChildPath $item.FullName), $true)
}
}
}
catch
{
throw "Error encountered when extracting ConfigureWindowsUpdate zip file.`n$($_.Exception.Message)"
}
finally
{
$zip.Dispose()
}
}

Importing Scheduled Tasks with Powershell in Windows 2012 R2

I am very new to Powershell scripting but have attempted to modify a script that I found here to import some XML Scheduled Tasks using Powershell in Windows 2012 R2.
I have been successful in importing the Scheduled Tasks into the root [Task Scheduler Library] using this script.
The problem seems to be that the Schedule Tasks need to be imported into a subfolder under Task Scheduler Library, let's say "SubTasks"
$task_path = "C:\Users\me\Desktop\ST Testing\exported ST's\scheduledTask.xml"
$task_user = "usr"
$task_pass = "pwd"
$schedule = new-object -com("Schedule.Service")
$schedule.Connect("server") # servername
#$folder = $schedule.GetFolder("\") <===This works fine
$folder = $schedule.GetFolder("\SubTasks") #<===This does not work
Write-Host $folder
Get-Item $task_path | % {
$task_name = $_.Name.Replace('.xml', '')
$task_xml = Get-Content $_.FullName
$task = $schedule.NewTask($null)
$task.XmlText = $task_xml
$folder.RegisterTaskDefinition($task_name, $task, 6, $task_user, $task_pass, 1, $null)
}
When I run the above Powershell Script I receive this error:
Exception calling "RegisterTaskDefinition" with "7" argument(s): "The
specified path is invalid. (Exception from HRESULT: 0x800700A1)"
At C:\Users\me\Desktop\ST Testing\ImportSTs.ps1:22 char:5
+ $folder.RegisterTaskDefinition($task_name, $task, 6, $task_user,
$task_pass, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Thanks in advance.
Register-ScheduledTask supports using XML to define the task:
Register-ScheduledTask `
-User $task_user `
-Password $task_pass `
-TaskName ([IO.Path]::GetFileNameWithoutExtension($task_path)) `
-TaskPath '\SubTasks' `
-Xml (Get-Content $task_path -Raw)
Note that you need to fetch the actual XML content. The -Raw flag prevents Get-Content from returning a String[], which also makes Register-ScheduledTask unhappy.
Also note that Register-ScheduledTask has a -TaskPath argument, allowing you specify a subfolder to put the task in if desired.
I'm not fond of using the grave mark for line continuation, so I prefer splatting to spread things out over multiple lines:
$taskArgs = #{
User='usr';
Password='pwd';
TaskName=([IO.Path]::GetFileNameWithoutExtension($task_path));
TaskPath='\SubTasks';
Xml=(Get-Content $task_path -Raw)
}
Register-ScheduledTask #taskArgs
if you're on powershell 3 (win2k12 - so you are) and above, there is a whole module for task scheduling.
see: gcm -Module PSScheduledJob
however, it does not seem to come with an easy way to import tasks from xml.
there are modules for that, this particular module deserializes the xml file and tests for all settings, seems more cumbersome than schtasks solution listed below.
for powershell 2 (win2k8) I found it easier to use schtasks - full ref here:
https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx
for example (scheduling a task from an xmlfile, the task will run under a particular user creds:
schtasks /Create /XML $xmlfile /RU $creds.UserName /RP $creds.GetNetworkCredential().Password /TN "My Task Name"
I got my xml file by manually creating the task and exporting to xml (I removed credential and info nodes from xml)
Was able to get this to work for our needs.
$task_user="username"
$task_pass="password"
$schedule=new-object -ComObject ("Schedule.Service")
$schedule.Connect("server")
$folder=$schedule.GetFolder("\tasks")
$path="\\server\c$\temp\Tasks\"
Get-ChildItem $path -Filter "*.xml"| foreach {
$task_conf=Get-Item -Path $_.FullName
$taskname=$task_conf.Name
$task_xml=$task_conf.FullName
$task=$schedule.NewTask(0)
$task.XmlText=(Get-Content $task_xml).Replace('Task version="1.1" xmlns','Task version="1.2" xmlns')
$folder.RegisterTaskDefinition($taskname,$task,6,$task_user,$task_pass,1,$null)
}

Remove-Item doesn't work, Delete does

Does anyone have any idea why Remove-Item would fail while Delete works?
In below script, I get a list of files I'd like to delete.
Using Remove-Item I get following error message:
VERBOSE: Performing the operation "Remove File" on target
"\\UncPath\Folder\test.rtf". Remove-Item : Cannot remove item
\\UncPath\Folder\test.rtf: Access to the path is denied.
but using Delete is deleting those files as we speak.
Script
$files = gci \\UncPath\Folder| ?{ $_.LastWriteTime -le (Get-Date).addDays(-28) }
# This doesn't work
$files | Remove-Item -force -verbose
# But this does
$files | % { $_.Delete() }
powershell may act strange with UNC path, I think it prepends the UNC Path with the current provider you can verify this with :
cd c:
test-path \\127.0.0.1\c$
returns TRUE
cd HKCU:
test-path \\127.0.0.1\c$
returns FALSE
when specifying the fullpath we're telling powershell to use the filesystem provider, that solves the problem. you could also specify the provider like remove-item filesystem::\\uncpath\folder
I can finally repro this and IMO it appears to be a bug. The repro is to have an open share like C$ but to set Deny Modify perms for the user on the file. When I do that, I observe this:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
ri : Cannot remove item \\Keith-PC\C$\Users\Keith\foo.txt: Access to the path is denied.
At line:1 char:43
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | ri -for
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (\\Keith-PC\C$\Users\Keith\foo.txt:FileInfo) [Remove-Item], ArgumentExc
eption
+ FullyQualifiedErrorId : RemoveFileSystemItemArgumentError,Microsoft.PowerShell.Commands.RemoveItemCommand
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Delete()} # <== this works!
I also observe that removing the -Force parameter deletes the file without error as well. The deny perms still allow me to delete the file from Windows Explorer so that leads me to believe that the file should delete. So what is up with using the -Force parameter? When I delve into the ErrorRecord I see this:
Message : Access to the path is denied.
ParamName :
Data : {}
InnerException :
TargetSite : Void set_Attributes(System.IO.FileAttributes)
StackTrace : at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at Microsoft.PowerShell.Commands.FileSystemProvider.RemoveFileSystemItem(FileSystemInfo
fileSystemInfo, Boolean force)
It seems that the -Force parameter is trying to set (more likely reset) attributes and the permissions on the file don't allow it e.g.:
PS> gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
Exception setting "Attributes": "Access to the path is denied."
At line:1 char:45
+ gci '\\Keith-PC\C$\Users\Keith\foo.txt' | %{$_.Attributes = 'Normal'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
So it seems to me that PowerShell should first try as if the -Force weren't present and if that fails, then try resetting attributes.

Resources