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
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
took up coding a small card game in PowerShell to familiarize myself with the software for work and it grew with more things I wanted to add. I thought about doing Multiplayer and stumbled across SSH. have been fiddling around with it for a while and it got me doubting myself a bit that it is even possible to do a multiplayer "game" in PowerShell. I have tried looking for anything related to multiplayer games in PowerShell and found little to none.
so here is my question.
Im setting up an ability to either Host/Join a game in the multiplayer section. selecting host checks if you have OpenSSH installed. installs it if you don't. sets a firewall exception. then pulls your user and IP together and gives that to the host to give to others to join off.
then with that ip the joiners enter it and get connected to the host and their files get shared.
problems I am facing:
Can only connect in LAN though this method. if port forwarding is required to be done in the router and it cant be scripted in PowerShell then that cant be done because the user cant be expected to do it.
When connected through SSH the script stops. this is due to the SSH opening a new command prompt that needs to be put back into PowerShell. how do I overcome this?
When transferring files Data between the computers starts. I need to make a check every interval for updates in the data to see if the other players have done anything. like finished their turn and its now mine. how would I make a check like that?
I'm very new to PowerShell and I understand that its intended purpose is not to make games. this is all for the sake of me learning its abilities in a fun way. if it cant be done it cant be done. and I know I'm asking allot right now. I just need some pointers cause I have no-one else to talk to about this cause no-one understands PowerShell where I work. Thank you all in advance
Here is the code I have so far regarding the SSH. keep in mind I'm not the best at all in this
new-Item -Path 'C:\Program Files' -Name "CardZdata" -ItemType directory
$path = 'C:\Program Files\CardZdata'
$hostippath = ($path + '\' + 'hostip' + '.xml')
#Main Menu
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Singleplayer [s]'
Write-Output 'Multiplayer SSH [m]'
Write-output 'Multiplayer LAN [l]'
$gamemode = read-host
if ($gamemode -eq 's')
{
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Blackjack [b]'
Write-Output 'Poker [p]'
}
elseif ($gamemode -eq 'm')
{
clear
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
if ($test.State -eq "NotPresent")
{
Write-Output 'SSH (Client) is not installed on your PC. it is needed to connect to the server.'
Write-Output 'do you wish to install it? [y/n]'
$SSHchoice = Read-Host
if ($SSHchoice = 'y')
{
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
}
else
{
Write-Output 'Sorry, you cant play Multiplayer without SSH.'
break
}
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
if ($test.State -eq "NotPresent")
{
Write-Output "Error - Installation Failed"
break
}
}
clear
Write-Output 'Multiplayer SSH connects you to games hosted by others. or you can host them yourself.'
Write-Output 'Uninstall SHH client [u] !Warning!- You wont be able to connect to Multiplayer servers'
Write-Output ''
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Host [h]'
Write-Output 'Join [j]'
$hj = Read-Host
if ($hj -eq 'h')
{
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
if ($test.State -eq "NotPresent")
{
Write-Output 'SSH (Server) is not installed on your PC. it is needed to connect to the server.'
Write-Output 'do you wish to install it? [y/n]'
$SSHchoice = Read-Host
if ($SSHchoice = 'y')
{
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
}
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
if ($test.State -eq "NotPresent")
{
Write-Output "Error - Installation Failed"
break
}
else
{
Write-Output 'Sorry, you cant Host Multiplayer without the SSH Server.'
break
}
}
#StartMultiplayer
Write-Output '!Starting Multiplayer Server On Local Host!'
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
$test = Get-NetFirewallRule -Name sshd
if ($test.Name -ne "sshd")
{
Write-Output 'Setting Port'
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
}
Restart-Service sshd
Write-Output 'Server Set Up Successfully!'
$userip = (Get-NetIPAddress -AddressFamily IPv4 -SuffixOrigin Dhcp).IPAddress
Write-Output 'Give this to users:'
$hostip = ($env:UserName + "#" + $userip)
$hostip
$hostip | export-clixml $hostippath -force
Read-Host
}
if ($hj -eq 'j')
{
Write-Output 'Join Server'
Write-Output '-------------------'
Write-Output 'Server list [s] - WorkInProgress'
Write-Output 'Direct Connect [d]'
$sd = Read-Host
if ($sd -eq 's')
{
Write-Output 'why?'
Read-Host
}
if ($sd -eq 'd')
{
Write-Output 'Enter a code that is given by the Host'
Write-Output 'Example: [username#ipaddress]'
$hostip = read-host
$hostip | export-clixml $hostippath -force
}
}
Read-Host
}
elseif ($gamemode -eq 'l')
{
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
}
Here is the main area:
#StartMultiplayer
Write-Output '!Starting Multiplayer Server On Local Host!'
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
$test = Get-NetFirewallRule -Name sshd
if ($test.Name -ne "sshd")
{
Write-Output 'Setting Port'
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
}
Restart-Service sshd
Write-Output 'Server Set Up Successfully!'
$userip = (Get-NetIPAddress -AddressFamily IPv4 -SuffixOrigin Dhcp).IPAddress
Write-Output 'Give this to users:'
$hostip = ($env:UserName + "#" + $userip)
$hostip
$hostip | export-clixml $hostippath -force
Read-Host
Yet another PowerShell/BizTalk question, but first some background:
We have a lot of (8 inprocess, 2 isolated) Host Instances on one developer environment. One of the instances has gone corrupt ("Installation Failed" as status in Admin Console). I saw that it was lacking password and tried to update it manually. No luck, the password I had was wrong and it was also the same password stored for the account in our CMDB... Oh, well. Just to reset it and change it on all host instances.
Well, I wanted to try out to do it the PowerShell way. It kind of works, but only if the instances is in ServiceState 8? ServiceState 4 (started) of course gives an error. But so does ServiceState 1 (stopped)?
Very annoying. It is the method Install that fails:
Exception calling "Install" : "A failure occurred while installing the Windows NT
service BTSSvc$Test_host.
Please verify the following:
1) The credentials supplied are correct and the specified user name has the "log
on as service" privilege enabled.
2) All Microsoft Management Console (MMC) Service windows are closed. The Window
s Service Control Manager will not allow the creation of a service if the service
has been deleted but is still referenced by an open MMC window. "
Code:
$hosts = Get-WmiObject MSBTS_HostInstance -namespace 'root/MicrosoftBizTalkServer'
foreach($hostinst in $hosts)
{
if ($hostinst.Logon -eq $acc)
{
if($hostinst.ServiceState -eq 1 -or 8)
{
write-host "Hostinstans" $hostinst.HostName "har ServiceState" $hostinst.ServiceState
$hostinst.Install($acc, $pw, "True")
Start-Sleep -Seconds 30
write-host "Hostinstans" $hostinst.HostName "har nytt lösenord och ServiceState" $hostinst.ServiceState
}
}
}
Anyone got ideas? It is annoying the cr*p out of me!
Best regards,
Joakim
$hostinst.ServiceState -eq 1 -or 8
should be rewritten
($hostinst.ServiceState -eq 1) -or ($hostinst.ServiceState -eq 8)
Try out in your PowerShell console:
3 -eq 1 -or 8
Found the answer!
If the instance is in ServiceState 1 I have to uninstall it before making any changes to it! My code for this should be like this (for example):
$hosts = Get-WmiObject MSBTS_HostInstance -namespace 'root/MicrosoftBizTalkServer'
foreach($hostinst in $hosts)
{
if ($hostinst.Logon -eq $acc)
{
if(($hostinst.ServiceState -eq 1) -or ($hostinst.ServiceState -eq 8))
{
if($hostinst.ServiceState -eq 1)
{
$hostinst.Uninstall()
}
write-host "Hostinstans" $hostinst.HostName "har ServiceState" $hostinst.ServiceState
$hostinst.Install($acc, $pw, "True")
Start-Sleep -Seconds 30
write-host "Hostinstans" $hostinst.HostName "har nytt lösenord och ServiceState" $hostinst.ServiceState
}
}
}
I have prepared below script to change sql server service account. But the service is not stopping and starting when i run below script. Any diea? is there any beeter way to do this. is there any alternative for Sleep. We don't know how much service takes to stop and start. Is there a way to keep powershell to wait until service completely
stops/starts.
$Services = Get-WmiObject Win32_Service -ComputerName "." | Where { $_.name -eq 'MSSQLSERVER' }
ForEach($Service in $Services)
{
$StopStatus = $Service.StopService()
Sleep 15
If ($StopStatus.ReturnValue -eq "0")
{write-host "$Service -> Service Stopped Successfully"}
$ChangeStatus = $Service.change($null,$null,$null,$null,$null,$null,$ServiceAccount,$Password,$null,$null,$null)
If ($ChangeStatus.ReturnValue -eq "0")
{write-host "$Service -> Sucessfully Changed Service Account"}
$StartStatus = $Service.StartService()
Sleep 25
If ($ChangeStatus.ReturnValue -eq "0")
{write-host "$Service -> Service Started Successfully"}
}
You can see if the service is stopped ( or started ) in a loop and then proceed:
$sleepCounter = 1
While((Get-Service $serviceName).status -ne "Stopped" ){
Write-Host "Waiting for service to stop. Attempt $sleepCounter of 20"
sleep 1
if($sleepCounter -eq 20) { break }
$sleepCounter++
}
Also, you can do the following to get the service instead of using where-object
$svc=gwmi win32_service -filter "name='$serviceName'"