Restart-Service output to file - windows

Using Task Scheduler I am running a PS script to restart selected Windows Services using Restart-Service. For troubleshooting issues I'd like to write the output to a log file so we can make sure the service did restart. For the life of me I can't get the output file to write anything just creates the file in date format, but no contents.
THank you
Edit:
OG Script
Restart-Service Printer Spooler -Force | Out-File c:\scripts\test3.txt
If I add -PassThru I get an output but the output is pretty bare bones. Would like to log steps of the Service Controller.
Restart-Service Printer Spooler -Force -PassThru | Out-File c:\scripts\test3.txt

$logFile = "C:\Windows\Temp\out.txt"
$serviceName = "serviceName"
Restart-Service $serviceName -Verbose *> $logFile
The -Verbose switch gives you detailed start/stop attempt information
*> Redirects all command output to the log file.

Provided the service you're restarting talks to the eventlogs, I'd grab the data from there and log it. Or leave it in there and grab it as needed. If you want to output it, this is one approach:
$date = (get-date).AddMinutes(-5)
$serviceData = Get-Service wersvc
restart-service $serviceData
$eventData = Get-Winevent -FilterHashtable #{ LogName = 'System'; StartTime = $date; ID = 7036} | ? {$_.message -match $serviceData.DisplayName}
$eventData | Out-File C:\logs\filename.txt

Related

Install Offline Windows Updates(.msu) to remote servers

I'm trying to get a script together to remotely install some windows updates on some remote servers that are connected in an offline domain.
I have tried regular PS Remoting and after some research, I think what I am trying to do isnt supported by microsoft. When checking my event logs I have a bunch of these errors.
Edit
I wanted to add that I have tried running the .\Install2012R2.ps1 script from my local computer, modified to have the Invoke-Command in that and have it run the update portion of the original Install2012R2.ps1 and I would get the same errors.
I was hoping that by placing the script on each server that it would like that more.
End Edit
Windows update could not be installed because of error 2147942405 "Access is denied."
(Command line: ""C:\Windows\System32\wusa.exe" "C:\Updates\windows8.1-kb4556853-x64.msu" /quiet /norestart")
I have tried running Invoke-Command as credentialed to an administrator account on the servers but I have been having no luck and was looking for some advice if someone has maybe tried/done this before.
$Servers = #("V101-Test1","V101-Test2")
$Username = 'admin'
$Password = 'Password'#not actual password
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Get-PSSession | Remove-PSSession
New-PSSession -ComputerName $Servers
foreach($Server in $Servers){
Get-ChildItem -Path C:\Source\Temp -Recurse | Copy-Item -Destination "\\$Server\c$\Updates\" -Force
}
Invoke-Command $Servers -Credential $Cred -ScriptBlock{
& "C:\Updates\Install2012R2.ps1"
}
EDIT 2
Here is the actual install code of the Install2012R2.ps1 script
$updatedir= "./"
$files = Get-ChildItem $updatedir -Recurse
$msus = $files | ? {$_.extension -eq ".msu"}
$exes = $files | ? {$_.extension -eq ".exe"}
foreach ($file in $msus){
$KBCtr++
$fullname = $file.fullname
# Need to wrap in quotes as folder path may contain space
$fullname = "`"" + $fullname + "`""
$KBN = $fullname.split('-')[1]
# Need to wrap in quotes as folder path may contain space
$fullname = "`"" + $fullname + "`""
# Specify the command line parameters for wusa.exe
$parameters = $fullname + " /quiet /norestart"
# Start services and pass in the parameters
$install = [System.Diagnostics.Process]::Start( "wusa",$parameters )
$install.WaitForExit()
}
I'm not sure why wusa.exe is failing here with Access Denied, but here is a PowerShell-native approach you can try. If nothing else, it should give you a clearer indication via the captured error information as to what the underlying issue is:
Add-WindowsPackage -Path C:\Updates\OurHeroicUpdate.msu -Online -PreventPending -NoRestart
-Path is the path to the msu file
-Online tells Add-WindowsPackage to modify the currently "mounted image" (the running version) of Windows (as opposed to an offline disk image you could also apply it to)
-PreventPending prevents installing the msu if there is already a pending change, like needing to reboot for updates.
Add-WindowsPackage is part of the DISM module available under Windows PowerShell, and is the functional equivalent of dism /packagepath:"cabfile", although it can take an msu where dism.exe only allows a cab.

Powershell - how to show which computers from a list are running a specific process?

Powershell beginner here working in an air-gapped, Win7 environment with Powershell 4.0 so unable to import any modules or do anything sophisticated but wondering how I can achieve generating a txt file of computers on the network that are running a specific process, say wusa.exe for Windows Updates?
I have a txt list of all the computer names already and so far have this:
$computers = gc "C:\PCList.txt"
foreach ($computer in $computers) {Get-process | out-file -Path "C:\TheseAreRunningWusa.txt"}
But obviously that displays ALL processes, any way to cut out everything aside from a specific one but also only list the ones running said process?
Thanks in advance.
The Get-Process command allows you to specify both a remote computer to run on, and what service you are looking for.
$computers = Get-Content "C:\PCList.txt"
$output = #()
foreach ($computer in $computers) {
if(Get-Process "myProcessName" -ComputerName $computer -ErrorAction SilentlyContinue) {
$output += $computer
}
}
$output | Set-Content "C:\TheseAreRunningMyProcess.txt"
Note: I used -ErrorAction SilentlyContinue as Get-Process throws an error if the process is not found.

Script Powershell delete keys Windows registry, vault and add network printer

I want a Powershell script that will allow:
Deletion of keys in the Windows registry corresponding to 10.x.x.x (if not present proceed to step 2)
Delete an entry in the Windows Vault : 10.x.x.x (if not present proceed to step 3)
Add a printer by name \ 10.x.x.x \ Printer + Authentication on print server (Domain \ User with password by memorizing the information in the Windows Vault)
For my part I tried this :
Write-Output "===========Deleting entry Windows Vault==========="
cmdkey /delete:10.x.x.x
Start-Sleep -s 5
Write-Output "===========Deleting printer==========="
Remove-Printer -Name "\10.x.x.x\PrinterName"
Start-Sleep -s 5
Write-Output "===========Deleting old entries Windows registry==========="
Get-Childitem -path hkcu:\ -recurse -ErrorAction SilentlyContinue |
Where-Object {$.Name -like "*10.x.x.x*"} |
ForEach-Object {Remove-Item $.FullName}
Start-Sleep -s 5
Write-Verbose "===========Configuration printer==========="
$cred = get-credential "DomainName\" $domain = "."
$user = $cred.UserName
$PrinterPath = "\10.x.x.x\PrinterName"
$net = new-Object -com WScript.Network
$pwd = $cred.Password
$net.AddWindowsPrinterConnection($PrinterPath)
Start-Sleep -s 5
It is not very conclusive...
In the example above, is it possible to adapt the script ?
For example, if you want to delete the registry keys and the Windows Vault entry, if the executed command does not find the requested information, make sure you do nothing and proceed to the next step.
Would it be possible to have help please ?
Thank you !
Have a good day.

Powershell output doesn't log properly when called from Task Scheduler

I need to log my powershell output. My ps file is something like this:
#Set-ExecutionPolicy Unrestricted
$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
$date = (Get-Date).tostring("MMddyy HHmmss")
$filename = 'C:\apierror\logs\' + $date + '.txt'
Start-Transcript -path $filename -append
$python = "C:\Python34\python.exe"
$python_path = "C:\script.py"
cd (split-path $python_path)
& $python $python_path
Stop-Transcript
Now, when I run this file directly from powershell, the output is logged correctly. But when I try to run it from taskscheduler - only some portion of the console output is stored in the file.
Any ideas why that might be?
Using transcript only stored partial output for some reason. I ended up using logs directly into the python file as opposed to powershell. Seems to be working correctly.

PowerShell: Restart Service By Executable Name

all
I implemented my first PowerShell script, that does some setup, sets registry keys and at then end needs to restart services. The problem is that I have only have name of the executable, but not service name. Restart-Service can work only with name of the service. Googling (well Binging also) around didn't give me much result.
I was wondering whether there is a way to restart service by executable name?
I know that I can get process by executable name, but just killing the process and starting it again is NOT good choice, since service Start/Stop functions are not called and it may not work properly.
Thanks.
You can try using wmi and do something like this:
(gwmi win32_service | ?{$_.pathname -match "\\executable.exe "}) | Restart-Service
Get-WmiObject -Class Win32_Service -Filter "PathName LIKE '%PartOfTheName%'" -ComputerName PC1 | Foreach-Object{
$_.StopService()
$_.StartService()
}
You can do this using WMI:
$process = Get-Process sqlservr| select -ExpandProperty Id
Get-WmiObject win32_Service|
where {$process -contains $_.ProcessId}|
foreach {Restart-Service $_.Name}
Edit: Changed script to restart service, not just stop it.
#set by logic to determine if the service will restart or not
$global:ServerWillRestart=$true
#can be found using the name column of Get-services cmdlet
$serviceName="Set name of the service"
if($global:ServerWillRestart){
$service =Get-Service | where{ $_.Name -eq $serviceName}
do{
Write-output "The service $ServiceName will is being stopped"
Stop-Service $service
Start-Sleep -s 2
}
while($service.WaitForStatus("Stopped"))
do{
Write-Output "The service $ServiceName will is being started"
Start-Service $service
Start-Sleep -s 2
}
while($service.WaitForStatus("Running"))

Resources