Parse LogFile Using PowerShell
Hello,
I am new to PowerShell, and trying to parse Log file for the most recent [ERROR] keyword .
Content of my log file is as follows
[ERROR] 2013-12-23 19:46:32
[ERROR] 2013-12-24 19:46:35
[ERROR] 2013-12-24 19:48:56
[ERROR] 2013-12-24 20:13:07
Function CheckLogs()
param ([string] $logfile)
if(!$logfile) {write-host "Usage: ""<Log file path>"""; exit}
cat $logfile | Select-String "ERROR" -SimpleMatch | select -expand line |
foreach {
$_ -match '(.+)\s\[(ERROR)\]\s(.+)'| Out-Null
new-object psobject -Property @{Timestamp = [datetime]$matches[1];Error
= $matches[2]} |
where {$_.timestamp -gt (get-date).AddDays(-1)}
$error_time = [datetime]($matches[1])
if ($error_time -gt (Get-Date).AddDays(-1) )
write-output "CRITICAL: There is
an error in the log file $logfile around
$($error_time.ToShortTimeString())"; exit(2)
write-output "OK: There was no errors in the past 24 hours."
CheckLogs "C:\Log.txt" #Function Call
After executing above script, I am getting the below error, please advise.
$error_time = [datetime]($matches[1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Cannot index into a null array.
At C:\PS\LogTest.ps1:10 char:21
+ new-object psobject -Property @{Timestamp =
[datetime]$match ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Cannot index into a null array.
At C:\Test\LogTest.ps1:12 char:21
+ $error_time = [datetime]($matches[1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Thanks for your replies, unfortunately this is not working. Kindly provide the full script if possible.
Function CheckLogs()
param ([string] $logfile)
if(!$logfile) {write-host "Usage: ""<Log file path>"""; exit}
cat $logfile | Select-String "ERROR" -SimpleMatch | select -expand line |
foreach {
if($_ -match '(.+)\s\[(ERROR)\]\s(.+)')
new-object psobject -Property @{Timestamp = [datetime]$matches[1];Error = $matches[2]} |
where {$_.timestamp -gt (get-date).AddDays(-1)}
$error_time = [datetime]($matches[1])
if ($error_time -gt (Get-Date).AddDays(-1))
write-output "CRITICAL: There is an error in the log file $logfile around
$($error_time.ToShortTimeString())"; exit(2)
write-output "OK: There was no errors in the past 24 hours."
CheckLogs "C:\Log.txt"
Similar Messages
-
Parse log file using powershell
Hi,
Am pretty new to Powershell and would require anyone of your assistance in setting up a script which parse thru a log file and provide me output for my requirements below.
I would like to parse the Main log file for Barra Aegis application(shown below) using powershell.
Main log = C:\BARRALIN\barralin.log
Model specific log = C:\BARRALIN\log\WG*.log
Requirements :
1. scroll to the bottom of the log file and look for name called "GL Daily" and see the latest date which in the example log below is "20150203"
note : Name "GL Daily" and date keep changing in log file
2. Once entry is found i would like to have a check to see all 3 entries PREPROCESS, TRANSFER, POSTPROCESS are sucess.
3. If all 3 are success i would like to the script to identify the respective Model specific log number and print it out.
E.g if you see the sample log below for "GL Daily", it is preceded by number "1718" hence script should append the model log path with "WG00" along with 1718, finally it should look something like this C:\BARRALIN\log\WG001718.log.
4. If all 3 items or anyone of them are in "failed" state then print the same log file info with WG001718.log
Any help on this would be much appreciated.
Thank You.
Main log file :
START BARRALINK Check Auto Update 1716
43006 20150203
Trgt/Arch c:\barralin
PREPROCESS success 0 preprocessor: no error
TRANSFER success 1 Host success: files received
POSTPROCESS success 0 Postprocessor: no error
CONFIRMATION success 2 No Confirm needed
STOP 43105 20150203
START Aegis GL Monthly
1716 43117 20150203
Trgt/Arch K:\barraeqr\aegis\qnt\gleqty
PREPROCESS success 0 preprocessor: no error
TRANSFER success 1 Host success: files received
POSTPROCESS success 0 Postprocessor: no error
CONFIRMATION success 2 No Confirm needed
STOP 44435 20150203
START Aegis UB Daily
1717 43107 20150203
Trgt/Arch K:\barraeqr\aegis\qnt\gleqty
PREPROCESS success 0 preprocessor: no error
TRANSFER success 1 Host success: files received
POSTPROCESS success 0 Postprocessor: no error
CONFIRMATION success 2 No Confirm needed
STOP 44435 20150203
START Aegis GL Daily
1718 44437 20150203
Trgt/Arch K:\barraeqr\aegis\qnt\gleqty
PREPROCESS success 0 preprocessor: no error
TRANSFER success 1 Host success: files received
POSTPROCESS success 0 Postprocessor: no error
CONFIRMATION success 2 No Confirm needed
STOP 50309 20150203
Hi All,
I was writing a function in power shell to send email and i was looking to attach lines as and when required to the body of the email. but am not able to get this done..Here's my code
Function Email ()
$MailMessage = New-Object System.Net.Mail.MailMessage
$SMTPClient = New-Object System.Net.Mail.SmtpClient -ArgumentList "mailhost.xxx.com"
$Recipient = "[email protected]"
If ($MessageBody -ne $null)
$MessageBody = "The details of Barra $strsessionProduct model is listed below
`rHostName : $localhost
`r Model Run Date : $Date
`r Model Data Date : $DateList1
`r`n Click for full job log"+ "\\"+$localhost+"\E$\Local\Scripts\Logs "
$MailMessage.Body = $MessageBody
If ($Subject -ne $null) {
$MailMessage.Subject = $Subject
$Sender = "[email protected]"
$MailMessage.Sender = $Sender
$MailMessage.From = $Sender
$MailMessage.to.Add($Recipient)
If ($AttachmentFile -ne $null) { $MailMessage.Attachments.add($AttachmentFile)}
$SMTPClient.Send($MailMessage)
$Subject = "Hello"
$AttachmentFile = ".\barralin.log"
$MessageBody = "Add this line to Body of email along with existing"
Email -Recipient "" -Subject $Subject -MessageBody $MessageBody -AttachmentFile $AttachmentFile
as you can see before calling Email function i did add some lines to $MessageBody and was expecting that it would print the lines for $MessageBody in Email Function along with the new line. But thats not the case.
I have tried to make $MessageBody as an Array and then add contents to array
$MessageBody += "Add this line to Body of email along with existing"
$MessageBody = $MessageBody | out-string
Even this didnt work for me. Please suggest me any other means to get this done.
THank You -
How to Create Windows Firewall Predefined rules using Powershell
Windows Firewall Predefined rules using Powershell
Following commands are working some time however sometimes it's giving errors. Any help would be appreciated
WORKING ==> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True
Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Inbound
NOT WORKING
PS C:\Windows\system32> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Outbound
Set-NetFirewallRule : One of the port keywords is invalid.
At line:1 char:1
+ Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Dire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Se
t-NetFirewallRule], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule
PS C:\Windows\system32> Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Direction Outbound
Set-NetFirewallRule : One of the port keywords is invalid.
At line:1 char:1
+ Set-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Enabled True -Dire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Se
t-NetFirewallRule], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule
Anoop C Nair (My Blog www.AnoopCNair.com)
- Twitter @anoopmannur -
FaceBook Forum For SCCMThe command:
Get-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Direction Outbound
produces the output:
Name : FPS-NB_Session-In-TCP
DisplayName : File and Printer Sharing (NB-Session-In)
Description : Inbound rule for File and Printer Sharing to allow NetBIOS Session Service connections. [TCP 139]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-NB_Session-Out-TCP
DisplayName : File and Printer Sharing (NB-Session-Out)
Description : Outbound rule for File and Printer Sharing to allow NetBIOS Session Service connections. [TCP 139]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-SMB-In-TCP
DisplayName : File and Printer Sharing (SMB-In)
Description : Inbound rule for File and Printer Sharing to allow Server Message Block transmission and reception via Named Pipes. [TCP 445]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-SMB-Out-TCP
DisplayName : File and Printer Sharing (SMB-Out)
Description : Outbound rule for File and Printer Sharing to allow Server Message Block transmission and reception via Named Pipes. [TCP 445]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-NB_Name-In-UDP
DisplayName : File and Printer Sharing (NB-Name-In)
Description : Inbound rule for File and Printer Sharing to allow NetBIOS Name Resolution. [UDP 137]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-NB_Name-Out-UDP
DisplayName : File and Printer Sharing (NB-Name-Out)
Description : Outbound rule for File and Printer Sharing to allow NetBIOS Name Resolution. [UDP 137]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-NB_Datagram-In-UDP
DisplayName : File and Printer Sharing (NB-Datagram-In)
Description : Inbound rule for File and Printer Sharing to allow NetBIOS Datagram transmission and reception. [UDP 138]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-NB_Datagram-Out-UDP
DisplayName : File and Printer Sharing (NB-Datagram-Out)
Description : Outbound rule for File and Printer Sharing to allow NetBIOS Datagram transmission and reception. [UDP 138]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-ICMP4-ERQ-In
DisplayName : File and Printer Sharing (Echo Request - ICMPv4-In)
Description : Echo Request messages are sent as ping requests to other nodes.
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-ICMP4-ERQ-Out
DisplayName : File and Printer Sharing (Echo Request - ICMPv4-Out)
Description : Echo Request messages are sent as ping requests to other nodes.
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-ICMP6-ERQ-In
DisplayName : File and Printer Sharing (Echo Request - ICMPv6-In)
Description : Echo Request messages are sent as ping requests to other nodes.
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-ICMP6-ERQ-Out
DisplayName : File and Printer Sharing (Echo Request - ICMPv6-Out)
Description : Echo Request messages are sent as ping requests to other nodes.
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-LLMNR-In-UDP
DisplayName : File and Printer Sharing (LLMNR-UDP-In)
Description : Inbound rule for File and Printer Sharing to allow Link Local Multicast Name Resolution. [UDP 5355]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : FPS-LLMNR-Out-UDP
DisplayName : File and Printer Sharing (LLMNR-UDP-Out)
Description : Outbound rule for File and Printer Sharing to allow Link Local Multicast Name Resolution. [UDP 5355]
DisplayGroup : File and Printer Sharing
Group : @FirewallAPI.dll,-28502
Enabled : True
Profile : Any
Platform : {}
Direction : Outbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
The command:
(Get-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Direction Outbound).DisplayName
shows the display names of the 14 outbound rules in the FPS group:
File and Printer Sharing (NB-Session-In)
File and Printer Sharing (NB-Session-Out)
File and Printer Sharing (SMB-In)
File and Printer Sharing (SMB-Out)
File and Printer Sharing (NB-Name-In)
File and Printer Sharing (NB-Name-Out)
File and Printer Sharing (NB-Datagram-In)
File and Printer Sharing (NB-Datagram-Out)
File and Printer Sharing (Echo Request - ICMPv4-In)
File and Printer Sharing (Echo Request - ICMPv4-Out)
File and Printer Sharing (Echo Request - ICMPv6-In)
File and Printer Sharing (Echo Request - ICMPv6-Out)
File and Printer Sharing (LLMNR-UDP-In)
File and Printer Sharing (LLMNR-UDP-Out)
If your output is different than this, it means rules have been removed (or added) to the File and Print Sharing group.
For example, if you run the command:
New-NetFirewallRule -DisplayName "My test rule 2" -group "File and Printer Sharing" -Enabled True -Protocol tcp -LocalPort 12346 -Direction Inbound
This adds a new inbound firewall rule to the FPS group. Output looks like:
Name : {06449724-944b-4048-834f-8870b9dce4f6}
DisplayName : My test rule 2
Description :
DisplayGroup : File and Printer Sharing
Group : File and Printer Sharing
Enabled : True
Profile : Any
Platform : {}
Direction : Inbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
This test rule is of course useless because there's no listener on TCP port 12346 on this particular machine..
The new rule can also be viewed in Windows Firewall with Advanced Security:
Now if you run the command:
(Get-NetFirewallRule -DisplayGroup "File and Printer Sharing" -Direction Inbound).DisplayName
the output will look like:
File and Printer Sharing (Spooler Service - RPC)
File and Printer Sharing (Spooler Service - RPC-EPMAP)
My test rule 2
Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) -
Use powershell to read Environment tab checkbox from ADUC
Hello all,
In ADUC, when you pull up a user, you can see an "Environment" tab, which contains a checkbox for "Start the following program at logon:". Here's a picture:
What I would like to do is use PowerShell to see if this checkbox is checked for a user. In my Google searches however, I have found that this checkbox is contained in the infamous "UserParameters" attribute.
My question is, what is the best way to see if this checkbox is checked for a user using PowerShell? Is this checkbox contained in any other attribute that PowerShell can read, or will I need to parse the UserParameters attribute to see if it's checked?Hi Kent,
As a workaround, the script below can help you to get the option "Program file name" and "Start in", if the option "Start the following program at logon" hasn't been checked, the script below will occur error "the property
can't be found":
$user = [adsi]"LDAP://CN=username,CN=Users,DC=domain,DC=domain,DC=com"
$user.PSBase.Invokeget("TerminalServicesInitialProgram")
$user.PSBase.Invokeget("TerminalServicesWorkDirectory")
If there is anything else regarding this script, please feel free to post back.
Best Regards,
Anna Wang -
Using Powershell Script Run simple query in MS Access 2007 and export the results of query to Excel
Hi Experts,
I have a Access 2007 DB file and 2 Big tables inside that (bigger than the size that can be easily handled by MS Excel 2007).
My requirement is automate using powershell scripts the below things.
1. Create a SQL query in Access DB and save that in access DB
2. Run the saved query and export the result in excel sheet where I can create the charts and Pivots. Thanks in advance
PrajeshDo you have to use the Access query, couldn't you just recreate the query in Powershell? Here's a link with good info that references an existing script for querying an Access database:
http://blogs.technet.com/b/heyscriptingguy/archive/2009/08/13/hey-scripting-guy-can-i-query-a-microsoft-access-database-with-a-windows-powershell-script.aspx
Once you have your dataset you can pipe it to
Export-Csv -NoType c:\pathtofile\output.csv -
Create SharePoint 2010 Search Service Application Using Powershell
Hi Team,
Could you please assist me in completing the search service application for
two server using powershell. Both the servers will be running all the component
Version SharePoint 2010
# 1.Setting up some initial variables.
write-host 1.Setting up some initial variables.
$SSAName = "Search Service Application"
$SVCAcct = "Domain\ServiceAccount"
$SearchAppPoolName ="DefaultAppPool"
$SSI = get-spenterprisesearchserviceinstance -local
$err = $null
$SSADBName="Search_AdminDB"
$SSADBServer="DBServer"
$host1="Server1"
$host2="Server2"
# Start Services search services for SSI
write-host Start Services search services for SSI
Start-SPEnterpriseSearchServiceInstance -Identity $SSI
# 2.Create an Application Pool.
write-host 2.Create an Application Pool.
#$AppPool = new-SPServiceApplicationPool -name $SSAName"-AppPool" -account $SVCAcct
$AppPool = Get-SPServiceApplicationPool -Identity $SearchAppPoolName -ErrorAction SilentlyContinue
# 3.Create the SearchApplication and set it to a variable
write-host 3.Create the SearchApplication and set it to a variable
$SearchApp = New-SPEnterpriseSearchServiceApplication -DatabaseServer $SSADBServer -Name $SSAName -applicationpool $AppPool -databasename $SSADBName
#4 Create search service application proxy
write-host 4 Create search service application proxy
$SSAProxy = new-spenterprisesearchserviceapplicationproxy -name $SSAName"ApplicationProxy" -Uri $SearchApp.Uri.AbsoluteURI
# 5.Provision Search Admin Component.
write-host 5.Provision Search Admin Component.
set-SPenterprisesearchadministrationcomponent -searchapplication $SearchApp -searchserviceinstance $SSI
# 6.Create a new Crawl Topology.
write-host 6.Create a new Crawl Topology.
$CrawlTopo = $SearchApp | New-SPEnterpriseSearchCrawlTopology
New-SPEnterpriseSearchCrawlComponent -SearchTopology $newTopology -SearchServiceInstance $hostA
Source:blog.MSDN Author- Russ Maxwell
Thanks BasvaCould you please assist me in completing the search service application for
two server using powershell. Both the servers will be running all the component
Hi Basva,
Do you want to provision two search service applications in single farm?
Commonly, only one search service application is needed in a farm for Search function.
Here are articles for detail information about how to provision search service application using powershell:
http://blogs.msdn.com/b/jjameson/archive/2011/02/28/powershell-script-to-configure-search-in-sharepoint-server-2010.aspx
http://blogs.msdn.com/b/russmax/archive/2009/10/20/sharepoint-2010-configuring-search-service-application-using-powershell.aspx
Regards,
Rebecca Tu
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected] -
not able to set security group without mail enabled as site collection admin using powershell in sharepoint online site - office 365?
Any idea?after few days test in my lab, I can see that only email enabled group can be added as site collection admin using POWERSHELL.
hope this helps who stuck like me!! :-) -
Changing a SQL Report server Database to a new One Using Powershell script
Hi,
I have an existing report server (Native Mode) and a pre-configured report server database. I have created a new database and want to assign it new report server database. How can i automate this process using powershell?
Here is the detail requirement
If there is a Report Server database seeded on the xxxxx server, follow the below steps:
◾Click the Database button on the left. Click on the Change Database button, choose option Choose an existing report server database. Enter the RPT server name (e.g. xxxxxx) in Server Name text box and click Next.
◾In the Report Server Database selection, select the ReportServer database. Then click next button to complete the process.
Any help in this regard will be very much helpfull.
Sushruta BanerjeeHi Sushruta,
To query export from Report server Database, the scripts below may be helpful for you:
Export RDL Files from ReportServer Database with PowerShell
SQL Database Reports with PowerShell
I hope this helps. -
Automation of SPLA Report using PowerShell
Hi,
I am reposting this question in this forum on the suggestion of an experienced exchange mvp, earlied posted in Exchange 2013 forum.
We want to automate SPLA report creation using PowerShell for Exchange 2010 and 2013, I mean
the report for Microsoft Service Providers License Agreement Program, which Service providers have to generate every month and have to submit to Microsoft.
Can somebody guide us, as we could not find any helpful online resource.
Thanks in anticipation.
Regards, David JohnsonThat reads like a hosting question to me, and hosters know best about that. If I were a moderator, I'd move this thread for you, but I'm not so I recommend you post in the Exchange for Hosters forum:
http://social.technet.microsoft.com/Forums/en-US/exchange2010hosters/threads
Ed Crowley MVP "There are seldom good technological solutions to behavioral problems." -
Creating a Scheduled Task using PowerShell v4
So here is my question. I'm trying/wanting to create a scheduled task using PowerShell v4 on Server 2012R2. I want to task to run on the 1st day of every month. The parameter for -Monthly -Day is not available. I need to use PowerShell
to create the Scheduled Task because the Task will be running with a group Managed Service Account credentials so the Scheduled Task can not be created via the Task Scheduler GUI.
Thanks in AdvanceHere is a functioning task It can be easily edited in PowerShell or in notepad to alter the timing
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.1" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Author>W8TEST\user01</Author>
</RegistrationInfo>
<Triggers>
<CalendarTrigger>
<StartBoundary>2014-06-04T21:31:32.0459499</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByMonth>
<DaysOfMonth>
<Day>1</Day>
<Day>12</Day>
<Day>24</Day>
</DaysOfMonth>
<Months>
<January />
<February />
<March />
<April />
<May />
<June />
<July />
<August /
<September />
<October />
<November />
<December />
</Months>
</ScheduleByMonth>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<RunLevel>LeastPrivilege</RunLevel>
<UserId>W8TEST\jvierra</UserId>
<LogonType>InteractiveToken</LogonType>
</Principal>
</Principals>
<Settings>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>P3D</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>notepad.exe</Command>
<Arguments>test.txt</Arguments>
<WorkingDirectory>c:\temp</WorkingDirectory>
</Exec>
</Actions>
</Task>
I have edited and reloaded the XML many, many times. It works very nicely.
¯\_(ツ)_/¯ -
How to add a certificate to IIS global "Server Certificates" list using PowerShell?
Hi, been surfing the web for an example on how to add a certificate to the "global" IIS "Server Certificates" list using PowerShell but to no luck. I already have code in place on how to tie / associate a specific website with a specific cert but not how
to add the new .cer file using the "Complete Certificate Request..." wizard using PowerShell.... I dont expect the final code to become published but if someone had an idea on howto integrate / get an entry point on where to interact between the "Server Certificate"
list in IIS and POSH I would be super happy! :|
I am runnign IIS on a Windows 2008R2 x64 Standard Edition if that helps..... of course, I would saddle for an CLI if there is no other way, but POSH is of course the way to go! :)
Thanks for the help in advance guys, take care!
br4tt3Hi and thanks for the suggestions!
Although it comes close, the suggested code example points on howto import / incorporate .pfx files - I am getting fed by .cer files which I need to add into the IIS console using POSH.
I tried explore the IIS.CertObj object but was not able to work out if this one could be used for importing / adding .cer files into IIS! However, launching the following command from a POSH console with Import-Module Webadministration already
loaded into that shell;
$certMgr = New-Object -ComObject IIS.CertObj returns the following error message:
New-Object : Cannot load COM type IIS.CertObj
From an IIS perspective I have the following components installed;
[X] Web Server (IIS) Web-Server
[X] Web Server Web-WebServer
[ ] Common HTTP Features Web-Common-Http
[ ] Static Content Web-Static-Content
[ ] Default Document Web-Default-Doc
[ ] Directory Browsing Web-Dir-Browsing
[ ] HTTP Errors Web-Http-Errors
[ ] HTTP Redirection Web-Http-Redirect
[ ] WebDAV Publishing Web-DAV-Publishing
[X] Application Development Web-App-Dev
[ ] ASP.NET
Web-Asp-Net
[X] .NET Extensibility Web-Net-Ext
[ ] ASP
Web-ASP
[ ] CGI
Web-CGI
[ ] ISAPI Extensions Web-ISAPI-Ext
[ ] ISAPI Filters Web-ISAPI-Filter
[ ] Server Side Includes Web-Includes
[ ] Health and Diagnostics Web-Health
[ ] HTTP Logging Web-Http-Logging
[ ] Logging Tools Web-Log-Libraries
[ ] Request Monitor Web-Request-Monitor
[ ] Tracing
Web-Http-Tracing
[ ] Custom Logging Web-Custom-Logging
[ ] ODBC Logging Web-ODBC-Logging
[X] Security
Web-Security
[ ] Basic Authentication Web-Basic-Auth
[ ] Windows Authentication Web-Windows-Auth
[ ] Digest Authentication Web-Digest-Auth
[ ] Client Certificate Mapping Authentic... Web-Client-Auth
[ ] IIS Client Certificate Mapping Authe... Web-Cert-Auth
[ ] URL Authorization Web-Url-Auth
[X] Request Filtering Web-Filtering
[ ] IP and Domain Restrictions Web-IP-Security
[ ] Performance Web-Performance
[ ] Static Content Compression Web-Stat-Compression
[ ] Dynamic Content Compression Web-Dyn-Compression
[X] Management Tools Web-Mgmt-Tools
[X] IIS Management Console Web-Mgmt-Console
[X] IIS Management Scripts and Tools Web-Scripting-Tools
[ ] Management Service Web-Mgmt-Service
[ ] IIS 6 Management Compatibility Web-Mgmt-Compat
[ ] IIS 6 Metabase Compatibility Web-Metabase
[ ] IIS 6 WMI Compatibility Web-WMI
[ ] IIS 6 Scripting Tools Web-Lgcy-Scripting
[ ] IIS 6 Management Console Web-Lgcy-Mgmt-Console
[X] FTP Server Web-Ftp-Server
[X] FTP Service Web-Ftp-Service
[X] FTP Extensibility Web-Ftp-Ext
[ ] IIS Hostable Web Core Web-WHC
More or less the one thing that I am trying to get up and running is an automated FTPS solution - I just use the IIS console to be able to troubleshoot / compare how things scripted from POSH interacts in the MMC representation. The error I am getting
might be that I am lacking some IIS components to be in place to be able to automate some parts of the IIS - as suggested by the IIS.CertObj object listed in the example..... I will get back if I can track down which component needs to be added to be
able to reference the IIS.CertObj object.
Br4tt3 signing out...
br4tt3 -
How can I assign an icon to a folder using Powershell?
How can I assign an icon to a folder using Powershell?
I'm trying to make a script that goes through a folder recursively, checks for every folder if it's name is "template", and if so it changes the icon of that folder to an icon
I chose.
I searched for an answer here, and I've only managed to find a way to assign an icon to a shortcut, but not to an existing file.
Thanks in advance (: -
How can I query a https website used to display the status of an application using Powershell?
Need assistance on querying the status of an application using Powershell. The status of the application is displayed in a https website. I want to receive a notification when one of the listed applications fails.
Below is an example the failures I need to capture.
h-t-t-p-::://xpps2.xxcom/ssol/sSOLStatus.asp?autorun
SSOL Status
Current App Server: xpps2.xx.com
SQL Server Details:
SSS_MyAccount DB Connection: PASS
SSS_MyAccount DB Query: PASS
CAGWEB DB Connection: FAIL - Unable to Connect
CAGWEB DB Query: FAIL - Pay location not found
DB2 Server Details:
DB2 D Connection: PASS
DB2 Q Query: FAIL -Acct not found
DB2 X Query: PASS
DB2 N Query: PASS
DB2 S Query: PASS
DB2 K Query: PASS
DB2 I Query: PASS
Mitem Server Details:
MITEM server: MITEMP2
MITEM Total Devices: 10
MITEM Devices Lines Up: 10
MITEM Devices Logged In: 10
MITEM Devices In Use: 0
Mitem Server Status: PASS
Web Service Details:
SAW Web Service Status: FAIL
Maximo Vizcainothats where you are going to check what it is supposed to be.
lets say your page shows as SSOL Status : running you
probably want to use "if($totalstrng.ToLower().contains("ssqlL status
: running"))". its
checking if the html page contains the string you are looking for.
you might want to print $totalstrng
and see what you need to look for.
usign XMLHttp
or XML object as mentioned by JRV might be easier and faster way. -
How can I find what scom group a specific server belongs to using powershell?
Environment: SCOM 2007 r2
Server in question: Running Windows 2003 Std. (yes I know this sounds crazy)
Why do I need this: I noticed at the console level we have had server unexpected shutdown events which are not generating email notifications.
Source shows: Windows 2003 Server Standard Edition
Alert Rule: Windows Shutdown Unexpectedly
From what I see these are all windows 2003 server Std edition systems. I did a track and trace using our exchange tracking system which confirmed the alerts were not being emailed. Not sure if there is a better approach for this, but not being a sql
expert (however I do have someone I can leverage) I am trying to see if I can somehow extract this information using powershell.
Secondary general question: How can I find out the current size of our scom 2007 database and the number of objkects\servers being monitored? This is prep work for a migration over to 2012.
Thanks in advance for the help!1. what scom group a specific server belongs to
function Get-GroupNames {
[cmdletbinding()]
param($computerFQDN)
$containmentRel = Get-RelationshipClass -name:’Microsoft.SystemCenter.InstanceGroupContainsEntities’
$computerClass = Get-MonitoringClass -name:”Microsoft.Windows.Computer”
$criteria = [string]::Format(“PrincipalName = ‘{0}’”,$computerFQDN)
try {
$computer = Get-MonitoringObject -monitoringClass:$computerClass -criteria:$criteria
$relatedObjects = $computer.GetMonitoringRelationshipObjectsWhereTarget($containmentRel,[Microsoft.EnterpriseManagement.Configuration.DerivedClassTraversalDepth]::Recursive,[Microsoft.EnterpriseManagement.Common.TraversalDepth]::Recursive)
catch {
$_
write-host “An error occurred while querying groups of $computerFQDN”
foreach($group in $relatedObjects)
[array]$Groups = $groups + $group.SourceMonitoringObject.DisplayName
if($groups) {
return $groups
} else {
write-host “No groups available for $computerFQDN”
Usage:
Get-GroupName -ComputerFQDN myserver1
for detail, pls. refer to
http://techibee.com/powershell/powershell-get-scom-groups-of-a-computer-account/1129
Roger -
How to get Document Set property values in a SharePoint library in to a CSV file using Powershell
Hi,
How to get Document Set property values in a SharePoint library into a CSV file using Powershell?
Any help would be greatly appreciated.
Thank you.
AA.Hi,
According to your description, my understanding is that you want to you want to get document set property value in a SharePoint library and then export into a CSV file using PowerShell.
I suggest you can get the document sets properties like the PowerShell Command below:
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$siteurl="http://sp2013sps/sites/test"
$listname="Documents"
$mysite=new-object microsoft.sharepoint.spsite($siteurl)
$myweb=$mysite.openweb()
$list=$myweb.lists[$listname]
foreach($item in $list.items)
if($item.contenttype.name -eq "Document Set")
if($item.folder.itemcount -eq 0)
write-host $item.title
Then you can use Export-Csv PowerShell Command to export to a CSV file.
More information:
Powershell for document sets
How to export data to CSV in PowerShell?
Using the Export-Csv Cmdlet
Thanks
Best Regards
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected]
Maybe you are looking for
-
Asset Year End (Urgent) -Undo Year END
Please advice the following 1) Run AJAB (Year End Closing) - For Year 2007 2) Change Fiscal Year to Year 2008 3) Already input Asset for the Period 1 and Period 2 of Year 2008 4) Depreciation also run for the Period 1 and Period 2 of Year 2008 Howeve
-
As I have said before, this is my first go-round with a tablet device. So far, I like it, but there are some rally frustrating learning curves that I have right now. Here is the newest...help! Yesterday, the tablet informed me that I needed a neces
-
I am undered the impression that events 4656 and 4658 are created when the subcategory "Handle Manipulation" is enabled and that Microsoft recommends not to enabled this because these are very noisey events with very little worth. I believe that Micr
-
No customize toolbar in bridge cs5
I need the rotate tool and the new folder tool at least, and there is no "customize toolbar" under the view menu or anywhere else I can find. At least I had those shortcuts automatically in Bridge cs4. Anyone have any idea what the problem is? Thank
-
I am using the CAS as an authenication server against AD for my wireless network. I have a WISM as my WLC and some of my users are getting a certifate error when I enable WPA. The error is coming from the ACS. I get an invalid cert error or cert not