I have a powershell script that provides SQL Agent Job information. The script is meant to monitor the jobs and tell me if they failed the last time they ran. However i also want to know which was the last run step. and i can't seem to figure out how.
I am querying the Sql server mangement object, because it needs to be usable on multiple remote servers (remote connections) and i wish to avoid running SQL scripts.
Keep in mind i'm rather new to powershell.
This is the code i have so far: And i have loaded the SMO libraries, i just didn't show it the copied script.
## Get Jobstep Class SMO
Push-Location; Import-Module SQLPS -DisableNameChecking; Pop-Location;
$JobStep = New-Object microsoft.sqlserver.management.smo.agent.jobstep
## Run the select from the local SQL server management objects
$SQLSvr = "."
$MySQLObject = new-object Microsoft.SqlServer.Management.Smo.Server `
$SQLSvr;;
$Select = ($MySQLObject.JobServer.jobs) `
| Select Name, isEnabled, `
lastRunDate, lastRunOutCome, NextRunDate `
| Where-Object {$_.LastRunDate -ge ((Get-Date).adddays(-2)) } `
| ft -AutoSize;
$Select
The push-location section is meant to get the correct smo class for selecting the job step (unsure if it is right), however i haven't added anything from it.
Now the script does work, i get no errors and i get returned the overall information i want, but i cannot figure out how to add the jobstep - and i have consulted google. I'm well aware that i need to add more to the select, but what is the issue for me. So, how do i extract the last run job step from SQL Agent job, using the SMO, and add it to the above script?
You can use the SqlServer module from the PowerShell Gallery (Install-Module SqlServer), and then something like:
$h = Get-SqlAgentJobHistory -ServerInstance servername -JobName jobname
$h[0] will give you the last step ran.
This will give you the result in the format you wanted:
Get-SqlAgentJob -ServerInstance servername |
Where-Object {$_.LastRunDate -ge ((Get-Date).AddDays(-2))} | ForEach-Object {
$h = Get-SqlAgentJobHistory -ServerInstance servername -JobName $_.Name
[PSCustomObject]#{
Name = $_.Name
IsEnabled = $_.IsEnabled
LastRunDate = $_.LastRunDate
LastRunOutcome = $_.LastRunOutcome
NextRunDate = $_.NextRunDate
LastRunStep = $h[0].StepName
}
}
Related
I have to following part of my script:
$active_processes = (Get-WmiObject -Class Win32_Process | where path -like $path | Select-Object -ExpandProperty Path | split-path -leaf | Select-Object -Unique)
It's working fine but I need to check if the process I get after all the script is running with elevated rights to launch another process with elevated rights if neccesary so it can interact with said process. I don't see any information about elevated rights with Get-WmiObject, I was wondering if I'm missing it or if there's another way to get that information
I don't need to run the powershell script as administrator. What I need is to find ff any executable requires elevated rights when launched and I need to find this information via powershell.
After some research on how windows knows if it needs admin to run an executable, I concluded that there are a couple ways but the most recommended and reliable is reading the executable manifest, so I wrote the following function:
function Get-ManifestFromExe{
Param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Path")]
[ValidateScript({Test-Path $_ -IsValid})]
[String]$FullName
)
begin{
$stringStart = '<assembly'
$stringEnd = 'assembly>'
}
process{
$content = Get-Content $FullName -Raw
$indexStart = $content.IndexOf($stringStart)
$content = $content.Substring($indexStart)
$indexEnd = ($content.IndexOf($stringEnd)) + $stringEnd.Length
$content = $content.Substring(0,$indexEnd)
if($content -match "$stringStart(.|\s)+(?=$stringEnd)$stringEnd"){
return [XML]$Matches[0]
}
}
}
function Test-IsAdminRequired{
Param(
[Parameter(Mandatory=$true,Position=0)]
[XML]$xml
)
$value = $xml.assembly.trustInfo.security.requestedPrivileges.requestedExecutionLevel.level
if(-not [String]::IsNullOrEmpty($value)){
return ($value -eq "requireAdministrator" -or $value -eq "highestAvailable")
}else{
Write-Error "Provided xml does not contain requestedExecutionLevel node or level property"
}
}
$exe = '.\Firefox Installer.exe'
Get-ManifestFromExe -Path $exe
Test-IsAdminRequired -xml $exeManifest
It works by extracting the manifest XML from the executable and checking requestedExecutionLevel node's level property, the values accepted for this property are in this page, and quoted here:
asInvoker, requesting no additional permissions. This level requires
no additional trust prompts.
highestAvailable, requesting the highest permissions available to the
parent process.
requireAdministrator, requesting full administrator permissions.
So from this we can conclude that only highestAvailable and requireAdministrator would need admin privileges, so I check those, with that we will be done EXCEPT that some executables I tested (mostly installers) don't require admin to run but instead they prompt the UAC when they ruin their child executable, I don't really see a way to check this.. sorry.
BTW I really enjoyed this question (specially the research), hope this can help you.
SOURCES
What is the difference between "asInvoker" and "highestAvailable" execution levels?
reading an application's manifest file?
https://learn.microsoft.com/en-us/visualstudio/deployment/trustinfo-element-clickonce-application?view=vs-2019#requestedexecutionlevel
It's in the System.Security.Principal classes. This returns $true if the current user is elevated to local Administrator:
(New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
I have some problems getting EventLog and save data. I am able to get my EventLogs but not logs from network computers.
Here is the code I am running:
$logFileName = "Application"
$path = $MyInvocation.MyCommand.Path +"\Output\"
$path = $PSScriptRoot+"\Output\"
new-item $path -ItemType directory
$array = ("System", "Security")
$file = $PSScriptRoot +"\computers.txt"
$users = ForEach ($machine in $(Get-Content $file)) {
$pathMachine = $path+$machine
new-item $pathMachine -ItemType directory
ForEach ($logFileName in $array){
# do not edit
$logFileName
$exportFileName = (get-date -f yyyyMMdd) + "_" + $logFileName + ".evt"
$logFile = Get-WmiObject Win32_NTEventlogFile -ComputerName $machine | Where-Object {$_.logfilename -eq $logFileName}
$logFile
$exportFileName
$pathMachine
$temp = $pathMachine + "\"+ $exportFileName
$temp
$fff = $logFile.BackupEventLog($temp)
}
}
This could e considered a duplicate of this.
Reading event log remotely with Get-EventLog in Powershell
# swapped from this command
get-eventlog -LogName System -computername <ServerName>
# to this
invoke-command {get-eventlog -LogName System} -ComputerName <ServerName>
Don't struggle with writing this from scratch. Well, unless it's a learning exercise. There are pre-built script for you to leverage as is and or tweak as needed.
Running commands on Remote host require using the Invoke cmdlet, and or an established PSRemoting session to that host.
Get Remote Event Logs With Powershell
Gather the remote event log information for one or more systems using wmi, alternate credentials, and multiple runspaces. Function supports custom timeout parameters in case of wmi problems and returns Event Log information for the specified number of past hours.
Download: Get-RemoteEventLogs.ps1
The script is too long (it's 100+ lines) to post here, but here in the Synopsis of it.
Function Get-RemoteEventLogs
{
<#
.SYNOPSIS
Retrieves event logs via WMI in multiple runspaces.
.DESCRIPTION
Retrieves event logs via WMI and, if needed, alternate credentials. This function utilizes multiple runspaces.
.PARAMETER ComputerName
Specifies the target computer or comptuers for data query.
.PARAMETER Hours
Gather event logs from the last number of hourse specified here.
.PARAMETER ThrottleLimit
Specifies the maximum number of systems to inventory simultaneously
.PARAMETER Timeout
Specifies the maximum time in second command can run in background before terminating this thread.
.PARAMETER ShowProgress
Show progress bar information
.EXAMPLE
PS > (Get-RemoteEventLogs).EventLogs
Description
-----------
Lists all of the event logs found on the localhost in the last 24 hours.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Requires: Powershell 2.0
Version History
1.0.0 - 08/28/2013
- Initial release
#>
Or this one.
PowerShell To Get Event Log of local or Remote Computers in .csv file
This script is handy when you want to extract the eventlog from remote or local machine. It has multiple filters which will help to filter the data. You can filter by logname,event type, source etc. This also have facility to get the data based on date range. You can change th
Download : eventLogFromRemoteSystem.ps1
Again, too big to post here because the length is like the other one.
I am working on some assumptions but maybe this will help.
When I Ran your Code I got
Get-Content : Cannot find path 'C:\computers.txt' because it does not exist.
I had to make the C:\computers.txt file, then I ran your code again and got this error.
Get-Content : Cannot find path 'C:\Output\computers.txt' because it does not exist.
I made that file in that location, then I ran your code again and I got the event log file. Maybe try creating these two missing files with a command like
Get-WmiObject Win32_NTEventlogFile -ComputerName $machine
mkdir C:\Output\$machine
$env:computername | Out-File -FilePath c:\Output\Computers.txt
You may also want to setup a Network share and output to that location so you can access the event logs from a single computer. Once the share is setup and the permissions just drop the unc path in.
Good evening
I have this Problem with this Version
PS C:\temp> $PSVersionTable.PSVersion.Major
4
This is a really strange problem...
despite of initialized variables, PowerShell script is somehow able to reuse variable values from previous invocations.
The script is simple; to show the problem, I work with a list of virtual machines:
Read all Virtual Machines into an Array
Select the 1st Element in the Array
Add a new Property to the Object from step 2
The Problem: if I run the script a second time, the new Property is already there - despite all Variables are initialized. If I start the Script in a new session, the new Property is missing on the 1st run, afterwards it is already there.
Here is the simple Code:
Set-StrictMode -Version 2.0
# Read all Virtual Machines into an Array
$AllVMs = #()
$AllVMs = Get-VM
# Get the 1st Virtual Machine
$VM = $null
$VM = $AllVMs[0]
# Prepare my Property
$MyList = #()
$MyList += "Test"
# If the Property already exists, just add my List
if ($VM.PSobject.Properties.Name -match "MyList") {
$VM.MyList += $MyList
} else {
# My Property does not exist: create it
$VM | Add-Member –MemberType NoteProperty –Name MyList –Value ($MyList)
}
# Give Back my VM Object
$VM
To test the script, I just count the number of MyList-Elements:
PS C:\temp> $result = c:\temp\testvar.ps1
PS C:\temp> $result.MyList.Count
1
PS C:\temp> $result = c:\temp\testvar.ps1
PS C:\temp> $result.MyList.Count
2
…
Does somone can help me with this Problem?
Thanks a lot for any help!!
Kind regards,
Tom
I have asked this question to 'the scripting guy' Forum, too.
I've got two great answers:
From jrv:
You are not exiting from PowerShell. The VM object is dynamic to the session. It persists until you close PowerShell. Some objects are like this. The code base drags them I to PowerShell and they remain cached. I suspect this is what is happening here.
From Evgenij Smirnov:
Hi,
this appears to be specific to the VM object. If I substitute Get-VM by Get-Process or Get-ChildItem c:\ I do not experience this behaviour. If I select a new VM every time I run the script, it does not retain the property. On the other hand, if I do (Get-VM)[0].MyList after running the script four times, I get four entries.
So this persistence is obviously built into the Hyper-V module, the custom property getting added to the instance of the VM object itself. So you could initialize MyTest to empty on the whole VM collection like this:
$AllVMs | foreach {
if ($_.PSobject.Properties.Name -match "MyList") {
$_.MyList = #()
}
}
Kind regards, Tom
For a website my team are currently working on we're trying to write some PowerShell automation to temporarily override a connection string which is otherwise usually in Web.config, and then at a later point delete it.
However, using both the PowerShell cmdlets and the Azure REST APIs, we don't seem to be able to ever reset the connection strings set to be empty. Whenever we try to delete it either the command says it succeeds but doesn't delete it, or the requests is rejected as invalid.
It's possible to delete all the connection strings using the Management Portal, so what are we missing that means we can't do it programmatically?
Here's an example PowerShell command we're using that isn't doing what we want:
$website = Get-AzureWebsite $websiteName -slot $websiteSlot
$connectionStrings = $website.ConnectionStrings
$result = $connectionStrings.Remove(($connectionStrings | Where-Object {$_.Name -eq $connectionStringName}))
Set-AzureWebsite $websiteName -slot $websiteSlot -ConnectionStrings $connectionStrings
I know this is really late.
I have faced the same situation.We are able to update the App settings but not the connection strings.I found the solution.Since it doesn't have an answer, I thought it would be good to update it..
As per the git-hub source, the hash-table(nested) needs to be in the format of
#{ KeyName = #{ Type = "MySql"; Value = "MySql Connection string"}};
after which I ran the code to update the App, it worked. Below is the whole code
$list = #{ ConnectionString1 = #{ Type = "MySql"; Value = "MySql Connection string"}};
set-AzureRMWebAppSlot -ResourceGroupName "resourceGroup" -Name "devTest" -ConnectionStrings $list -slot "production"
I have created a log-on script based on Active-Directory Module, that queries the user group membership in order to map his drives etc.
I have compiled it with PowerGui, and created an EXE file.
the problem is, the module doesn't exist on the users computers.
Is there a way to do this without the module, or add the module to the compilation?
For group memberships, you could also get it without connecting to AD, and parse the output of the WHOAMI utility
$groups = WHOAMI /GROUPS /FO CSV | ConvertFrom-Csv | Select-Object -ExpandProperty 'Group Name'
if($groups -contains 'group1')
{
do something
}
One way is using Active-Directory Service Interface (ADSI).
you can find in another SO post (Can I match a user to a group accross different domains?) one way to find all the groups a user belongs to, using ADSI, in the post it's a C# code, but it's easy to translate.
Here is a small example of a simple search to begin.
Clear-Host
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://WM2008R2ENT:389/dc=dom,dc=fr","jpb#dom.fr","Pwd")
# Look for a user
$user2Find = "user1"
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
$rc = $Rech.filter = "((sAMAccountName=$user2Find))"
$rc = $Rech.SearchScope = "subtree"
$rc = $Rech.PropertiesToLoad.Add("mail");
$theUser = $Rech.FindOne()
if ($theUser -ne $null)
{
Write-Host $theUser.Properties["mail"]
}
Another way is to use System.DirectoryServices.AccountManagement Namespace.
This way is also using ADSI, but it's encapsulated, and you need the Framework .NET 3.5. You will also find in the same post but in the Edited (2011-10-18 13:25) part, a C# code using this way.
You can also use WMI :
$user2Find = "user1"
$query = "SELECT * FROM ds_user where ds_sAMAccountName='$user2find'"
$user = Get-WmiObject -Query $query -Namespace "root\Directory\LDAP"
$user.DS_mail
You can use this solution localy on your server or from a computer inside the domain, but it's a bit more complicated to authenticate to WMI from outside the domain.