Get-Eventlog - To monitor specific event ID - get-eventlog

I have requirement to monitor specific event ID for specific set of workstations.
Event ID Monitor : To monitor Specific event ID for specific set of workstations
$Workstations = gc c:\NotBackedUp\Workstation.txt
foreach ($Workstation in $Workstations)
{
$events = Get-EventLog -ComputerName $Workstation -LogName "Application" | Where-Object {$_.EventID -eq "2"} | Format-List
}
$events >> C:\NotBackedUp\Test.txt
But I can get error as below,
Get-EventLog : The network path was not found. At line:6 char:15
+ ... $events = Get-EventLog -ComputerName $Workstation -LogName "Applica ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-EventLog], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.GetEventLogCommand

$Workstations = gc c:\NotBackedUp\Workstation.txt
foreach ($Workstation in $Workstations)
{
$events = Get-WinEvent -ComputerName $Workstation -LogName "Application" | Where-Object {$_.EventID -eq "2"} | Format-List
}
$events >> C:\NotBackedUp\Test.txt
By doing above script, this will not give any error, but takes longer time than usual.
Now, any suggestion to filter this option and give output in short time. Your suggestions are really appreciated.

Related

Powershell 2.0 Get users for a local group

How can I get user list from a local group? I only have PS 2.0 and it does not have Get-ADGroup command.
I can get local groups:
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$groups = $adsi.Children | Where { $_.SchemaClassName -eq 'Group' }
$group | ft Name
What I need is to list all the members for each group.
You can try the following
$obj = [ADSI]"WinNT://$env:COMPUTERNAME"
$admingroup = $obj.Children | Where { $_.SchemaClassName -eq 'group'} | where {$_.name -eq 'Administrators'}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}
Here are the common properties
String :
Description, FullName, HomeDirectory, HomeDirDrive, Profile, LoginScript, ObjectSID
Integer :
UserFlags, PasswordExpired, PrimaryGroupID
Time :
PasswordAge
You'll find more in Microsoft documentation.
Try this
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"
$computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | foreach {
write-host $_.name
write-host "------"
$group =[ADSI]$_.psbase.Path
$group.psbase.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
write-host
}
This doesn't give the domain though, hence i had to look for other ways, like:
If you want to see members of a local group quickly:
PS C:\> net localgroup USERS
Alias name USERS
Comment Users are prevented from making accidental or intentional system-wide changes and can run most applications
Members
-------------------------------------------------------------------------------
NT AUTHORITY\Authenticated Users
NT AUTHORITY\INTERACTIVE
The command completed successfully.
Now you can manipulate this output a bit to get what you need:
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"
$groups = $computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | select -ExpandProperty Name
Foreach($group in $groups)
{
write-host $group
write-host "------"
net localgroup $group | where {$_ -notmatch "command completed successfully"} | select -skip 6
Write-host
}

exception calling "Parse" with 1 argument: Input string was not in a correct format

I have a script that works properly when run as an administrator but gives a Parse error when run as a normal user. Any Ideas?;
SCRIPT
`NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(4);
$ExpireMax = (Get-Date).AddDays(9);
$Userlist = Get-ADUser -Filter * -Properties name, samaccountname, accountexpirationdate, enabled, distinguishedname, accountExpires | Where-object {($_.DistinguishedName -notlike "*OU=Terminated,OU=Users,OU=Home Office,DC=Domain,DC=com")} |
Where-Object {$_.accountExpires -ne $NeverExpires `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
$Userlist | select name, samaccountname, accountexpirationdate, enabled, distinguishedname | export-csv $ReportName -notypeinformation
Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -SMTPServer $SMTPServer -Attachments $ReportName
Get-ADUser -Filter * -Properties accountExpires |
Where-Object {$_.accountExpires -ne $NeverExpires `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin } | ForEach {
$account = $_
$manager = Get-ADUser -Identity $account -Properties EmailAddress,Manager | %{(Get-AdUser $_.Manager -Properties EmailAddress).EmailAddress}`
I would say that $_.accountExpires is null either because the property could not be retrieved or $_ is itself null. Powershell will quietly convert null to the empty string resulting an invalid format for parsing. Note that the Parse call is completely unnecessary because powershell will automatically try to coerce the string for you and will likely give you a much better error message. Although null will be coerced to 0 as a long.

Powershell: Parse a structured text file and save to .CSV

I'm very new to Powershell. Only have been using it for about 2 weeks.
I have a file that is structured like this:
Service name: WSDL
Service ID: 14234321885
Service resolution path: /gman/wsdlUpdte
Serivce endpoints:
--------------------------------------------------------------------------------
Service name: DataService
Service ID: 419434324305
Service resolution path: /widgetDate_serv/WidgetDateServ
Serivce endpoints:
http://servername.company.com:1012/widgetDate_serv/WidgetDateServ
--------------------------------------------------------------------------------
Service name: SearchService
Service ID: 393234543546
Service resolution path: /ProxyServices/SearchService
Serivce endpoints:
http://servername.company.com:13010/Services/SearchService_5_0
http://servername2.company.com:13010/Services/SearchService_5_0
--------------------------------------------------------------------------------
Service name: Worker
Service ID: 14187898547
Service resolution path: /ProxyServices/Worker
Serivce endpoints:
http://servername.company.com:131009/Services/Worker/v9
--------------------------------------------------------------------------------
I'd like to parse the file and have Service name, Service ID, Service Resolution Path and Service Endpoints (which sometimes contain multiple or no values) in individual columms (CSV).
Beyond using Get-Content and looping through the file, I have no idea even where to start.
Any help will be appreciated.
Thanks
with PowerShell 5 you can use the fabulous command 'convertfrom-string'
$template=#'
Service name: {ServiceName*:SearchService}
Service ID: {serviceID:393234543546}
Service resolution path: {ServicePath:/ProxyServices/SearchService}
Serivce endpoints:
http://{ServiceEP*:servername.company.com:13010/Services/SearchService_5_0}
http://{ServiceEP*:servername2.tcompany.tcom:13011/testServices/SearchService_45_0}
--------------------------------------------------------------------------------
Service name: {ServiceName*:Worker}
Service ID: {serviceID:14187898547}
Service resolution path: {ServicePath:/ProxyServices/Worker}
Serivce endpoints:
http://{ServiceEP*:servername3.company.com:13010/Services/SearchService}
--------------------------------------------------------------------------------
Service name: {ServiceName*:WSDL}
Service ID: {serviceID:14234321885}
Service resolution path: {ServicePath:/gman/wsdlUpdte}
Serivce endpoints:
http://{ServiceEP*:servername4.company.com:13010/Services/SearchService_5_0}
--------------------------------------------------------------------------------
'#
#explode file with template
$listexploded=Get-Content -Path "c:\temp\file1.txt" | ConvertFrom-String -TemplateContent $template
#export csv
$listexploded |select *, #{N="ServiceEP";E={$_.ServiceEP.Value -join ","}} -ExcludeProperty ServiceEP | Export-Csv -Path "C:\temp\res.csv" -NoTypeInformation
Give this a try:
Read the file content as one string
Split it by 81 hyphens
Split each splited item on the colon char and take the last array item
Create new object for each item
$pattern = '-'*81
$content = Get-Content D:\Scripts\Temp\p.txt | Out-String
$content.Split($pattern,[System.StringSplitOptions]::RemoveEmptyEntries) | Where-Object {$_ -match '\S'} | ForEach-Object {
$item = $_ -split "\s+`n" | Where-Object {$_}
New-Object PSobject -Property #{
Name=$item[0].Split(':')[-1].Trim()
Id = $item[1].Split(':')[-1].Trim()
ResolutionPath=$item[2].Split(':')[-1].Trim()
Endpoints=$item[4..($item.Count)]
} | Select-Object Name,Id,ResolutionPath,Endpoints
}
Try this:
Get-Content | ? { $_ -match ': ' } | % { $_ -split ': ' } | Export-Csv Test.csv;
Basically it boils down to:
Get all text content as an array
Filter for lines that contain ': '
For each line left over, split it on ': '
Export object arrays to a CSV file named test.csv
Hope this points you in the right direction.
Note: Code is untested.
Here is a general way parsing files with records and records of records (and so on), it use the powerfull PowerShell switch instruction with regular expressions and the begin(), Process(), end() function template.
Load it, debug it, correct it ...
function Parse-Text
{
[CmdletBinding()]
Param
(
[Parameter(mandatory=$true,ValueFromPipeline=$true)]
[string]$ficIn,
[Parameter(mandatory=$true,ValueFromPipeline=$false)]
[string]$ficOut
)
begin
{
$svcNumber = 0
$urlnum = 0
$Service = #()
$Service += #{}
}
Process
{
switch -regex -file $ficIn
{
# End of a service
"^-+"
{
$svcNumber +=1
$urlnum = 0
$Service += #{}
}
# URL, n ones can exist
"(http://.+)"
{
$urlnum += 1
$url = $matches[1]
$Service[$svcNumber]["Url$urlnum"] = $url
}
# Fields
"(.+) (.+): (.+)"
{
$name,$value = $matches[2,3]
$Service[$svcNumber][$name] = $value
}
}
}
end
{
#$service[3..0] | % {New-Object -Property $_ -TypeName psobject} | Export-Csv c:\Temp\ws.csv
# Get all the services except the last one (empty -> the file2Parse is teerminated by ----...----)
$tmp = $service[0..($service.count-2)] | Sort-Object #{Expression={$_.keys.count };Descending=$true}
$tmp | % {New-Object -Property $_ -TypeName psobject} | Export-Csv $ficOut
}
}
Clear-Host
Parse-Text -ficIn "c:\Développements\Pgdvlp_Powershell\Apprentissage\data\Text2Parse.txt" -ficOut "c:\Temp\ws.csc"
cat "c:\Temp\ws.csv"

Powershell - Query firewall list of servers export to csv

I'm using the following to query the firewall rules of a list of servers.
$servers = Get-Content fw_servers.txt
foreach($serv in $servers) {
$fw = New-Object -ComObject hnetcfg.fwpolicy2
$fw.rules |
Where-Object { $_.enabled -and $_.LocalPorts -like 3389 } |
Select-Object -Property direction,protocol, localports,name
}
I would like to export this information to a csv file. Can someone please let me know how I can use Export-CSV for this? I've tried making it into an array but it's not working for me. I'm using 2.0
I'd also like the exported data to look like the following
Server Direction Protocol LocalPorts Name
testsrv1 1 6 3389 Remote Desktop (TCP-In)
testsrv2 1 6 3389 Research Remote Desktop Policy
Thank you for your help.
Amelia
I had an epiphany and somehow figured it out. The following, although not pretty, works for me.
$servers = Import-CSV fw_servers.csv
$servers | Foreach {
$serv = $_.serv
foreach-object {
$name = $_."Server"
$fw = New-Object -ComObject hnetcfg.fwpolicy2
$fw.rules |
Where-Object { $_.enabled -and $_.LocalPorts -like 3389 } |
Select-Object #{Name="Server"; Expression={$name}}, direction, protocol, localports, name
}
} | Export-CSV C:\Users\trankaa\desktop\fw_res.csv -NoTypeInformation -Force

Using System.Drawing.Image to Export-Csv with $imageFile.Width and $_.Fullname

I wonder if there is a betterr way to write this script to gather image dimensions and filepaths. The script works great on small to medium size directories, but I'm not positive that 100,000+ files/folders is possible.
Measure-Command {
[Void][System.Reflection.Assembly]::LoadFile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
$path = "\\servername.corp.company.com\top_directory"
$data = Get-ChildItem -Recurse $path | % {
$imageFile = [System.Drawing.Image]::FromFile($_.FullName) ;
New-Object PSObject -Property #{
name = $_.Name
fullname = $_.Fullname
width = $imageFile.Width
height = $imageFile.Height
length = $_.Length
}
}
$data | Where-Object {$_.width -eq 500 -or $_.width -eq 250 -or $_.width -eq 1250 } |
Export-Csv \\servername.corp.company.com\top_directory\some_directory\log_file.csv -NoTypeInformation }
I don't actually use the Where-Object filter right now.
When running the above script on a remote directory with appx. 20,000 files + folders the script takes appx. 26 minutes, before creating a .csv.
I am running the script from Powershell V2 ISE on Windows 7 and I belive the remote server is on Windows Server 2003.
Would running the script directly from the remote server be faster?
Is the process of exoprting the csv slow since all data is collected in "cache" before being written to the csv?
If all I had to go through was 20,000 files, I'd wait the 26 minutes, but 500,000 files and folders is a long wait.
I'm testing out the below method since I think my real issue is not the speed, but storing too much data in the memory. Thanks to a post from George Howarth for this, and to PoSherLife for the top script -http://powershellcommunity.org/tabid/54/aft/4844/Default.aspx
Measure-Command {
[System.Reflection.Assembly]::LoadFile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
"Name|SizeInBytes|Width|Height|FullName" >> C:\Users\fcool\Documents\JPGInfo.txt
$path = "C:\Users\fcool\Documents"
$images = Get-ChildItem -Recurse $path -Include *.jpg
foreach ($image in $images)
{
$name = $image.Name
$length = $image.Length
$imageFile = [System.Drawing.Image]::FromFile($image.FullName)
$width = $imageFile.Width
$height = $imageFile.Height
$FullName = $image.Fullname
"$name|$length|$width|$height|$FullName" >> C:\Users\fcool\Documents\JPGInfo.txt
$imageFile.Dispose()
}
}
Is there any risk/loss of performance when running these scripts on non-image filetypes?
when I don't exclude non-images, I get this error:
Exception calling "FromFile" with "1" argument(s): "Out of memory."
At C:\scripts\directory_contents_IMAGE_DIMS_ALT_method.ps1:13 char:46
+ $imageFile = [System.Drawing.Image]::FromFile <<<< ($image.FullName)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
thanks for any advice!
and thanks again to George Howarth and to PoSherLife for the scripts!
Using -Filter with Get-ChildItem is much faster than -Include however you can only apply one filter string. So if you only want to match *.jpg you can use filter. In my testing using filter was close to 5 times faster than include.
Get-ChildItem -Recurse \\server\Photos -Filter *.jpg | % {
$image = [System.Drawing.Image]::FromFile($_.FullName)
if ($image.width -eq 500 -or $image.width -eq 250 -or $image.width -eq 1250) {
New-Object PSObject -Property #{
name = $_.Name
fullname = $_.Fullname
width = $image.Width
height = $image.Height
length = $_.Length
}
}
} | Export-Csv 'C:\log.csv' -NoTypeInformation

Resources