Differences between two options to run a command - powershell

I tried to run the following command in two different ways:
get-service | where-object {$_.Status -eq 'Running'}
In the upper window I loaded the PowerShell and then the command
and in the lower both steps at once.
Generally the second option works fine,
what was the reason for the difference?
The same command in two different ways

When PowerShell is invoked from a command prompt, use a string:
powershell "get-service | where-object {`$_.Status -eq 'Running'}"
(note the backtick in front of the $)
Or use a script block:
powershell { get-service | where-object {$_.Status -eq 'Running'} }

Put the command after powershell in quotes, then it will run

Related

create a txt file in PowerShell list of all running services

I am trying to create a txt file in PowerShell that provides a list of services that are running. This what I came up with but it keeps on giving me an error message that says its not valid.
Get-Service | Export-txt -path "C:\Windows\Temp\services.txt"
Get-Service | where {$_.Status -eq "Running"} | Export-txt -path "C:\Windows\Temp\services.txt"
There is no commandlet called Export-txt.
One option is to use Out-File. It uses -FilePath as a parameter (or no named flag).
Get-Service | Out-File -FilePath "C:\Windows\Temp\services.txt"
There is no cmdlet by the name of Export-txt. To get a list of cmdlets you can use, you can think logically and apply that to Get-Command. Running Get-Command will get you a list of all available cmdlets you may use in accordance with your Posh version.
Get-Command *out* returns a list of cmdlets you can send out to something. Same logic applies to Get-Command "Export*".
#This gets you all services
Get-Service | Out-File "C:\Windows\Temp\services.txt"
#This gets you only running services
Get-Service | where {$_.Status -eq "Running"} | Out-File "C:\Tmp.txt"
Use Get-Help Out-File to see how the cmdlet is used and what parameters it accepts. It also lists examples you can use.

Pipe sc query output to powershell method?

I'd like to pipe output from sc query to a method in powershell. For example, checking the status of a service and finding the part that says "STOPPED", and performing an action based on that output.
Is there a way to do this right from the output of sc query? Or do I need to output the results to a text file, and then.. I'm not sure, run a for-loop to find the piece I'm looking for to make an if condition true / false.
This is what I have so far:
Function IsStopped {
sc.exe query remoteregistry >> RemoteRegistry.txt
Get-Content -Path C:\RemoteRegistry.txt | Where-Object {$_ -like '*stopped*'} | ForEach-Object {
}
Not sure where to go next?
PowerShell has a cmdlet for examining services. Running Get-Service without parameters gives you all of the running services in the same way sc.exe does (actually while researching this I reminded myself that in PowerShell sc, without .exe, is an alias for Set-Content, so I ended up generating some useless files. This might be another good reason to use Get-Service to avoid confusion with Set-Content).
Running Get-Service | Get-Member gives a list of the properties and methods from the output of the command. Status is the Property of interest, so we run:
Get-Service | Where-Object { $_.Status -eq 'Stopped' }
The output of this command can then be piped into a for each loop as you have suggested, and each service's properties or methods can be accessed using the $_ shorthand:
Get-Service | Where-Object { $_.Status -eq 'Stopped' } | ForEach-Object {
Write-Host "Do something with $($_.ServiceName)"
}
It is possible to restart services in this manner, using $_.Start(), but I would recommend writing some error handling into the process if that's your ultimate aim.'
If you need more information, such as the executable, you might want to look here:
How can I extract "Path to executable" of all services with PowerShell

Redirect powershell in batch file works to file but not to null

The following line of code (in a 'Administrator' cmd window on Windows 10) outputs the title of some open windows to the me.txt file, and not to the screen:
POWERSHELL "Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle" 1>C:\me.txt
But the following line outputs to the screen, even though I say don't:
POWERSHELL "Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle" 1>NUL
Any ideas?
And I know that there is no point to the command if I am not interested in the result...
[Update] The reason for doing this is because the first time the line is run, it takes almost a second longer than subsequent times, so I wanted to run it once up front to make subsequent times more consistent. In those subsequent runs I do look at the results :-)
Does this produce the expect result? Apologies cannot test as no admin
POWERSHELL "Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Select-Object MainWindowTitle | Out-Null"

running powershell via cygwin

Running this command from a cygwin window fails because powershell cant find object, "Get-EventLog":
echo "\n" | powershell.exe Get-EventLog System | Where-Object { $_.EventID -match "6009" }
The Get-EveneLog Systerm query work just fine from a Powershell console so I know it's not a syntax issue. And I have included the powershell path.
Any Ideas?
After a brief trial and error session I discovered that if the query is encased in single quotes it will work :
powershell.exe 'Get-EventLog System | Where-Object { $_.EventID -match "6009" }'
powershell.exe -command 'Get-EventLog System | Where-Object { $_.EventID -match "6009" }'

Kill process by filename

I have 3 instances of application running from different places. All processes have similar names.
How can I kill process that was launched from specific place?
You can get the application path:
Get-Process | Where-Object {$_.Path -like "*something*"} | Stop-Process -WhatIf
That will work for the local machine only. To terminate remote processes:
Get-WmiObject Win32_Process -Filter "ExecutablePath LIKE '%something%'" -ComputerName server1 | Invoke-WmiMethod -Name Terminate
I would like to slightly improve Shay Levy's answer, as it didn't work work well on my setup (version 4 of powershell)
Get-Process | Where-Object {$_.Path -like "*something*"} | Stop-Process -Force -processname {$_.ProcessName}
You can take a look at the MainModule property inside of the Process class (which can be invoked via powershell).
foreach (Process process in Process.GetProcesses())
{
if (process.MainModule.FileName == location)
{
process.Kill();
}
}
I'd also consider the possible exceptions that can occur while calling this code. This might occur if you're trying to access processes that are no longer present (killed since the last time GetProcess was called) or processes for while you do not have permissions.
Try this:
http://technet.microsoft.com/en-us/library/ee177004.aspx
Stop-Process -processname notepad
The below command kills processes wherein "something" is part of the path or is a command line parameter. It also proves useful for terminating powershell scripts such as powershell -command c:\my-place\something.ps1 running something.ps1 from place c:\my-place:
gwmi win32_process | Where-Object {$_.CommandLine -like "*something*"} | % { "$(Stop-Process $_.ProcessID)" }
The solution works locally on my 64bit Windows 10 machine.