I made a small Powershell script 'Start.ps1' which launches some websites on Windows startup. When I launch it manually, all configured websites are started in Chrome. However, when I run it with task scheduler, the task runs, but Chrome does not start.
schtasks /create /tn "Start" /sc onstart /delay 0000:30 /rl highest /ru system /tr "powershell.exe -file 'C:\Users\myuser\Google Drive\Home\Start.ps1'"
I've also added some logs in my powershell script so I'm sure the script has started:
Function Write-Log {
Param (
[parameter(Mandatory=$True,HelpMessage='Log output')][string]$Log,
[parameter(Mandatory=$True,HelpMessage='Log severity')][ValidateSet('Debug', 'Info', 'Warning', 'Error', 'Unknown')][string]$Severity,
[parameter(Mandatory=$True,HelpMessage='Log message')][string]$Message
)
$Now = Get-Date -Format 'yyyy-MM-dd HH:mm:ss,fff'
$LocalScriptName = Split-Path -Path $myInvocation.ScriptName -Leaf
If ( $Log -eq 'Verbose' ) {
Write-Verbose -Message ('{0}: {1}: {2}: {3}' -f $Now, $LocalScriptName, $Severity, $Message)
}
ElseIf ( $Log -eq 'Debug' ) {
Write-Debug -Message ('{0}: {1}: {2}: {3}' -f $Now, $LocalScriptName, $Severity, $Message)
}
ElseIf ( $Log -eq 'Output' ) {
Write-Verbose -Message ('{0}: {1}: {2}: {3}' -f $Now, $LocalScriptName, $Severity, $Message)
}
ElseIf ( $Log -match '^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])(?::(?<port>\d+))$' -or $Log -match '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' ) {
$IpOrHost = $log.Split(':')[0]
$Port = $log.Split(':')[1]
If ( $IpOrHost -match '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$' ) {
$Ip = $IpOrHost
}
Else {
$Ip = [Net.Dns]::GetHostAddresses($IpOrHost)[0].IPAddressToString
}
Try {
$LocalHostname = ([Net.Dns]::GetHostByName((& "$env:windir\system32\hostname.exe")).HostName).tolower()
$JsonObject = (New-Object -TypeName PSObject |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue logsource -InputObject $LocalHostname |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue hostname -InputObject $LocalHostname |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue scriptname -InputObject $LocalScriptName |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue logtime -InputObject $Now |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue severity_label -InputObject $Severity |
Add-Member -PassThru -NotePropertyName NoteProperty -NotePropertyValue message -InputObject $Message )
If ( $psversiontable.psversion.major -ge 3 ) {
$JsonString = $JsonObject | ConvertTo-Json
$JsonString = $JsonString -replace "`n",' ' -replace "`r",' '
}
Else {
$JsonString = $JsonObject | ConvertTo-Json2
}
$Socket = New-Object -TypeName System.Net.Sockets.TCPClient -ArgumentList ($Ip,$Port)
$Stream = $Socket.GetStream()
$Writer = New-Object -TypeName System.IO.StreamWriter -ArgumentList ($Stream)
$Writer.WriteLine($JsonString)
$Writer.Flush()
$Stream.Close()
$Socket.Close()
}
Catch {
Write-Verbose -Message ("{0}: {1}: Error: Something went wrong while trying to send message to logserver `"{2}`"." -f $Now, $LocalScriptName, $Log)
}
Write-Verbose -Message ('{0}: {1}: {2}: Ip: {3} Port: {4} JsonString: {5}' -f $Now, $LocalScriptName, $Severity, $Ip, $Port, $JsonString)
}
ElseIf ($Log -match '^((([a-zA-Z]:)|(\\{2}\w+)|(\\{2}(?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(?=\.?\d)\.)){4}))(\\(\w[\w ]*))*)') {
If (Test-Path -Path $Log -pathType container){
Write-Host ('{0}: {1}: Error: Passed Path is a directory. Please provide a file.' -f $Now, $LocalScriptName)
Exit 1
}
ElseIf (!(Test-Path -Path $Log)) {
Try {
$Null = New-Item -Path $Log -ItemType file -Force
}
Catch {
$Now = Get-Date -Format 'yyyy-MM-dd HH:mm:ss,fff'
Write-Host ("{0}: {1}: Error: Write-Log was unable to find or create the path `"{2}`". Please debug.." -f $Now, $LocalScriptName, $Log)
exit 1
}
}
Try {
('{0}: {1}: {2}: {3}' -f $Now, $LocalScriptName, $Severity, $Message) | Out-File -filepath $Log -Append
}
Catch {
Write-Host ("{0}: {1}: Error: Something went wrong while writing to file `"{2}`". It might be locked." -f $Now, $LocalScriptName, $Log)
}
}
}
$Logfile="c:\Tempo\Start.log"
Write-Log $Logfile Info "Initiating Chrome Site Startup"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://outsideit.net"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://psychologischezorgopmaat.be"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://github.com"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "https://gitlab.com"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "http://localhost:9200"
Start-Process -FilePath "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -ArgumentList "http://localhost:5601"
Write-Log $Logfile Info "Finalizing Chrome Site Startup"
How can I make this work in Task Scheduler? I tried running it with SYSTEM and my own user and with the "Run with highest privilege" option.
Always test if the scheduled task is working as intended when you run it manually (Scheduled Tasks - right click your task and Run it). When that works, move on to test if it works as intended when you start up the computer (or whenever, depending on the trigger).
When I imported your task with through cmd with the SYSTEM user account, the default setting was "Run whether user is logged on or not". If I tried to run it manually, the script wouldn't start.
I then changed the user to my account, changed the option to "Run only when the user is logged on", and that fixed the problem for me (many times before, as well). I wasn't able to change this option when using the SYSTEM user.
Related
I'm trying to use this function to monitor BSOD remotely I know I have to add a parameter of computername just not sure where
Function Get-BSODInfo{
try {
Invoke-WebRequest -Uri "https://www.nirsoft.net/utils/bluescreenview.zip" -OutFile "$($ENV:Temp)\bluescreeview.zip"
Expand-Archive "$($ENV:Temp)\bluescreeview.zip" -DestinationPath "$($ENV:Temp)" -Force
Start-Process -FilePath "$($ENV:Temp)\Bluescreenview.exe" -ArgumentList "/scomma `"$($ENV:Temp)\Export.csv`"" -Wait
}
catch {
Write-Host "BSODView Command has Failed: $($_.Exception.Message)"
exit 1
}
$BSODs = get-content "$($ENV:Temp)\Export.csv" | ConvertFrom-Csv -Delimiter ',' -Header Dumpfile, Timestamp, Reason, Errorcode, Parameter1, Parameter2, Parameter3, Parameter4, CausedByDriver | foreach-object { $_.Timestamp = [datetime]::Parse($_.timestamp, [System.Globalization.CultureInfo]::CurrentCulture); $_ }
Remove-item "$($ENV:Temp)\Export.csv" -Force
$BSODFilter = $BSODs | where-object { $_.Timestamp -gt ((get-date).addhours(-24)) }
if (!$BSODFilter) {
write-host "Healthy - No BSODs found in the last 24 hours"
}
else {
write-host "Unhealthy - BSOD found. Check Diagnostics"
$BSODFilter
exit 1
}
}
What i'm trying to do ?
Create four files in local disk in the following order.
Note : In my local machine and not in any server remotely.
Three files to be created
Restart the system
On system startup create another file
Script i have used.
get-job | remove-job -Force
function create-file {
Param ([string] $a)
$p = "D:\" + $a
Write-Host $p
if (!(Test-Path $p))
{
New-Item -path D:\$a -type "file" -value "my new text"
Write-Host "Created new file and text content added"
}
else
{
Add-Content -path D:\$a -value "new text content"
Write-Host "File already exists and new text content added"
}
}
Workflow New-ServerSetup
{
create-file "one.txt"
create-file "two.txt"
create-file "three.txt"
Restart-Computer -ComputerName $env:COMPUTERNAME -Wait
Start-Sleep -Seconds 7
create-file "four.txt"
Unregister-ScheduledJob -Name NewServerSetupResume
}
$adm = "####"
$pwd = ConvertTo-SecureString -String "####" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($adm, $pwd)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name NewServerSetupResume -Credential $cred -Trigger $AtStartup -ScriptBlock {Import-Module PSWorkflow; Get-Job -Name NewSrvSetup -State Suspended | Resume-Job}
New-ServerSetup -JobName NewSrvSetup
Issues i'm facing
The execution returns Cannot wait for local computer to restart
i'm new to powershell things if any mistakes burden me.
Thanks in advance.
Schedule a job first, then reboot without waiting.
Change a value in a winlogbeat.yml as it is passed to serveral remote servers. Here is the value to change > hosts: localhost:5044 and when script kicks off on remote server it is to change to >lp-index-QA.QA.com:9999
Here is the script I wrote.. no failures but does not pass the new value to remote server>>
#ExecutionPolicy
Set-ExecutionPolicy -Force Unrestricted
#DC = (facter datacenter) | Out-String
$DC = 'parpr1'
$QAhost = #("hosts: lp-index-QA.QA.com:9999", "`r`nhosts: localhost:5044")
$PRODhost = #("hosts: lp-index-PROD.PROD.com:9999", "`r`nhosts: localhost:5044")
$file = 'C:\winlogbeat-1.2.3-windows\winlogbeat.yml'
if ($DC -eq "QA")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index-QA.QA.com:9999"
}
if ($DC -eq "PROD")
{
Write-Host "Datacenter is $DC"
Add-Content -PassThru -Path "$file" -Value "hosts: lp-index- PROD.PROD.com:9999"
}
# delete service if it already exists
if (Get-Service winlogbeat -ErrorAction SilentlyContinue) {
$service = Get-WmiObject -Class Win32_Service -Filter "name='winlogbeat'"
$service.StopService()
Start-Sleep -s 1
$service.delete()
}
$workdir = Split-Path $MyInvocation.MyCommand.Path
# create new service
New-Service -name winlogbeat `
-displayName winlogbeat `
-binaryPathName "`"$workdir\\winlogbeat.exe`" -c `"$workdir\\winlogbeat.yml`""
#pause 5s
Start-Sleep -s 10
#Startingserver
Start-service winlogbeat
I am trying to run a perl script whenever there is a service crash. The perl script intends to restart the service and send a mail to all the developers.
I have used windows recovery options for that, where it has an option to run a program . I have filled the required details in the command line option but the script doesn't seem to get executed. Can you please help me by sharing your knowledge on this?
Recovery tab configuration
I have tried with Restart service option and that is working fine but the run a program isn't executing the script. Am I missing something?
Any comment on this will be helpful.
I recently implemented a recovery option to run a powershell script that attempts to restart the service a defined number of times and sends an email notification at the conclusion, it also attaches a txt file with recent relevant logs.
After several attempts (and despite all the other things I have seen) The configuration of fields on the recovery tab in services is as follows:
Program: Powershell.exe
**Not C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe
Command line parameters: -command "& {SomePath\YourScript.ps1 '$args[0]' '$args[1]' '$args[n]'}"
eg: -command "& {C:\PowershellScripts\ServicesRecovery.ps1 'Service Name'}"
**The $args are parameters that will be passed to your script. These are not required.
here is the powershell script:
cd $PSScriptRoot
$n = $args[0]
function CreateLogFile {
$events = Get-EventLog -LogName Application -Source SomeSource -Newest 40
if (!(Test-Path "c:\temp")) {
New-Item -Path "c:\temp" -Type directory}
if (!(Test-Path "c:\temp\ServicesLogs.txt")) {
New-Item -Path "c:\temp" -Type File -Name "ServicesLogs.txt"}
$events | Out-File -width 600 c:\temp\ServicesLogs.txt
}
function SendEmail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service failure" `
-Body "The $n service on server $env:COMPUTERNAME has stopped and was unable to be restarted after $Retrycount attempts." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function SendEmailFail {
$EmailServer = "SMTP Server"
$ToAddress = "Name#domain.com"
$FromAddress = "Name#domain.com"
CreateLogFile
$Retrycount = $Retrycount + 1
send-mailmessage -SmtpServer $EmailServer -Priority High -To $ToAddress -From $FromAddress -Subject "$n Service Restarted" `
-Body "The $n service on server $env:COMPUTERNAME stopped and was successfully restarted after $Retrycount attempts. The relevant system logs are attached." -Attachments c:\temp\ServicesLogs.txt
Remove-Item "c:\temp\ServicesLogs.txt"
}
function StartService {
$Stoploop = $false
do {
if ($Retrycount -gt 3){
$Stoploop = $true
SendEmail
Break
}
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select Name, State, StartMode
if ($i.State -ne "Running" -and $i.StartMode -ne "Disabled") {
sc.exe start $n
Start-Sleep -Seconds 35
$i = Get-WmiObject win32_service | ?{$_.Name -imatch $n} | select State
if ($i.state -eq "Running"){
$Stoploop = $true
SendEmailFail}
else {$Retrycount = $Retrycount + 1}
}
}
While ($Stoploop -eq $false)
}
[int]$Retrycount = "0"
StartService
Currently I have this code -
Set-ExecutionPolicy Unrestricted
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
IF ($oldname -eq $name){Exit}
Else{ Rename-computer -ComputerName $oldname -NewName "$name" -force
Start-Sleep -s 5
Restart-Computer}
And I have it set to run as a scheduled task at logon and without the If Else it works perfectly however I don't want it to run every time a user logs in because it will just be a cycle of rebooting. Any help would be greatly appreciated.
I would suggest some changes:
Set-ExecutionPolicy is unnecessary, because if the machine has started processing the script, then the executionpolicy isn't a problem. So remove that, and specify it in the powershell.exe-call instead, like: powershell.exe -executionpolicy unrestricted
Use if($oldname -ne $name) { rename-computer .... } so you can remove the else part. Much cleaner
Try running the modified script below, and report back with the output in the scriptlog.txt-file.
$logpath = "c:\scriptlog.txt"
$name = (Get-WmiObject win32_bios).SerialNumber.Trim()
$oldname = (Get-WmiObject win32_computersystem).Name.Trim()
"NewName is '$name'" | Out-File $logpath -Append
"OldName is '$oldname'" | Out-File $logpath -Append
IF ($oldname -ne $name){
"If-test TRUE" | Out-File $logpath -Append
Rename-computer -ComputerName $oldname -NewName $name -Force
Start-Sleep -s 5
Restart-Computer
} else { #I've added the else-part just because of logging.
"IF-test FALSE" | Out-File $logpath -Append
}