I'm pretty new to Powershell. I have 2 different scripts I'm running that I would like to combine into one script.
Script 1 has 1 line
Stop-Process -ProcessName alcore.* -force
It's purpose is to end any process that begines with "alcore."
Script 2 has 1 line as well
Start-Service -displayname crk*
It starts any service that begins with crk.
How can I combine these into one script? If the processes are running I wish to stop them, if not, I wish to start the services. How can I accomplish this?
I'm trying this but it's not working
$services = Get-Process alcore.*
if($services.Count -qe 1){
Stop-Process -ProcessName alcore.* -force
} else {
Start-Service -displayname crk*
}
How can I do this correctly? Also should I wrap these up in a function and call the function? That seems a bit cleaner. Thanks for any help.
Cheers,
~ck
Use Get-Service to get the service status. The process could be running but the service might be paused:
$services = #(Get-Service alcore.*)
foreach ($service in $services)
{
if ($service.Status -eq 'Running')
{
$service | Stop-Service
}
else
{
Start-Service -DisplayName crk*
}
}
Related
New to Powershell, My goal is to go through a list of remote Computers and check to see if certain services are running on them and starting the services if they are not. what would be the best approach in creating a variable for the services on said servers?
Server1.txt - 'ServiceA ServiceB ServiceC'
Server2.txt - 'ServiceD ServiceE ServiceF'
Server3.txt - 'ServiceG ServiceH'
$services = get-content .\Server1.txt
$services | ForEach {
try {
Write-Host "Attempting to start '$($.DisplayName)'"
Start-Service -Name $.Name -ErrorAction STOP
Write-Host "SUCCESS: '$($.DisplayName)' has been started"
} catch {
Write-output "FAILED to start $($.DisplayName)"
}
}
Thank you.
In your input, you have mentioned one text file for each server which is not advisable. Also there is no computer name in your Start-service Command. Please find my input sample below.
server1-serviceA,ServiceB,ServiceC
server2-serviceD,ServiceE,ServiceF
server3-serviceG,ServiceH,ServiceI
And here is the powershell script, since you have mentioned different services for each server there is a need for using split function.
$textFile = Get-Content C:\temp\servers.txt
foreach ($line in $textFile) {
$computerName = $line.split("-")[0] #Getting computername by using Split
$serviceNames = $line.split("-")[1] #Getting Service names by using split
foreach ($serviceName in $serviceNames.split(",")) {
# Again using split to handle multiple service names
try {
Write-Host " Trying to start $serviceName in $computerName"
Get-Service -ComputerName $computerName -Name $serviceName | Start-Service -ErrorAction Stop
Write-Host "SUCCESS: $serviceName has been started"
}
catch {
Write-Host "Failed to start $serviceName in $computerName"
}
}
}
I haven't tested the script for starting the service, but the loop works properly for multiple servers and their respective services. Thanks!
I have been working on this PowerShell script. I'm still pretty new at this. The way it works is that I give it a list of servers which it goes though and restarts the App Pools 1 by 1. I have been having a problem with the snippet below. I do not use Restart-WebAppPool because it sometimes gives the App Pool a start before it's ready and leaves it stopped. I cannot show the whole script because it's big and has proprietary info. The problem that I'm having is I can't seem to break the do-while loop. In it I'm checking App Pool status to make sure that it's stopped.
What I get appears for $PL_Break appears to be a valid string showing "Stopped". However, even when it shows "Stopped" it doesn't break the loop.
$PL_Timeout = New-TimeSpan -Seconds 95
foreach ($PL_Server in $PL_ServerName)
{
$PL_Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
Write-host "`n`n`nRestarting App Pool : $PL_AppPool"
write-host "Stopping: " $PL_Server -f Green
Invoke-Command -ComputerName $PL_Server -ArgumentList $PL_AppPool -ScriptBlock {param($PL_App) Stop-WebAppPool -Name $PL_App}
do {
sleep 5
$PL_Br = Invoke-Command -ComputerName $PL_Server -ArgumentList $PL_AppPool -ScriptBlock {param($PL_App) Get-IISAppPool $PL_App | Select-Object State}
$PL_Break = [string]$PL_Br.State.value
} while (($PL_Stopwatch.elapsed -lt $PL_Timeout) -or ($PL_Break -ne "Stopped"))
} # Foreach - Server
Is it possible to launch a PowerShell Job that persists after the creating script terminates? So far as I can tell, the Job is tied to the initiating script.
What I have now is this
$name = 'iexplore'
$waitTimeinMinutes = 30
Start-Job -argumentList #($name, $waitTimeinMinutes) -scriptblock {
param (
[string]$name,
[int]$waitTimeinMinutes
)
$cutoff = [DateTime]::Now.AddMinutes($waitTimeinMinutes)
while ([DateTime]::Now -lt $cutoff) {
if (Get-Process -name:$name -errorAction:silentlyContinue) {
Stop-Process -name:$name -force -errorAction:silentlyContinue
}
if (Get-Service $name -errorAction:silentlyContinue | Where-Object {$_.status -eq "running"}) {
Stop-Service $name -force -errorAction:silentlyContinue
}
Start-Sleep -s:10
}
}
It works as intend. For half an hour it watches for a Process or Service called iexplore and kills it if it is found. However, I need to continue processing a calling script, and this job is killed when the calling script terminates. I presume there must be a way to initiate a job separate from the calling script?
I am fairly new to PowerShell and I am wondering why when I run this code it skips everything and then goes straight to the pause?
Once I hit enter it does not display anything and closes the window.
To better explain what I am doing here. I am trying to connect remotely to a server in our network and check to see if specific processes are running. If they are not running the script will make them run.
Any idea what I could be doing wrong in PowerShell v3 on Windows 7 64bit?
$recall = Get-WmiObject win32_service -computername srv-95-obweb | Where {$_.name -eq 'Hyland Sch4'}
$sleeplab = Get-WmiObject win32_service -computername srv-95-obweb | Where {$_.name -eq 'Hyland Sch3'}
$date = Get-Date
if($recall.Status -eq 'Stopped') {
Write-Host "Recall service is currently stopped and will be automatically started"
Get-Service '*Sch4' | Start-Service
Write-Host "Recall service has been started $date"
} Else {
if($recall.Status -eq 'Running') {
Write-Host "Recall service is currently running"
}
}
if($sleeplab.Status -eq 'Stopped') {
Write-Host "Sleep Lab service is currently stopped and will be automatically started"
Get-Service '*Sch3' | Start-Service
Write-Host "Sleep Lab service has been started $date"
} Else {
if($sleeplab.Status -eq 'Running') {
Write-Host "Sleep Lab service is currently running"
}
}
pause
The second if caused it to be false so it didnt post. Also had the wrong propertie. Making it .State instead of .status resolved the issue. Thanks all for your help
Just looking for verification here. Can a job Stop-Job itself? I have a script that creates a job that suppresses a service for as long as the main script is running (by way of passed $PID) and I am currently using this
Start-Job -name:'SuppressAdAppMgrSvc' -argumentList $id -scriptBlock {
param (
$id
)
do {
if ((Get-Service AdAppMgrSvc -errorAction:silentlyContinue).Status -eq 'Running') {
Stop-Service AdAppMgrSvc -force -warningAction:silentlyContinue -errorAction:silentlyContinue
}
Start-Sleep -s 5
$powershellProcess = Get-Process -id:$id -errorAction:silentlyContinue
} while ($powershellProcess)
Stop-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue
Remove-Job 'SuppressAdAppMgrSvc' -warningAction:silentlyContinue -errorAction:silentlyContinue
My thinking is the job will run, and when $PowershellProcess is no longer, then the Stop-Job would run. But I suspect the Remove-Job would not, since this is the very job that just got stopped. In general it probably isn't a problem, as 99% of the time I do a reboot when my script completes, but I am curious if there is a pattern for dealing with this? Or is it something of an edge case?
How do you expect Remove-Job to run inside a stopped job? And why would you want to do that from inside the job in the first place?
The job will automatically enter the Stopped state when the code in the scriptblock terminates, so all you need to do is to wait for that to happen and then remove the job:
Start-Job -Name 'SuppressAdAppMgrSvc' -ArgumentList $id -ScriptBlock {
...
} | Wait-Job | Remove-Job