PowerShell output results to text file

May 18, 2011 at 03:08:19
Specs: Windows XP
Hi; I have the following script that runs through a txt file called Computers.txt (containing 3 PCs to check - pc1, pc2, pc3) and checks if the service - 'uvnc_service' is running, if it isn't - start it. I'd like to pipe to a text file the machine(s) that have have this service restarted. Can anyone help me? I've tried to do this in simple batch file, but that brought me even more headaches...

# Setup trap to catch exceptions
trap [Exception]
{
write-error $("TRAPPED: " + $_.Exception.Message);
}

# read computers from text file
$computers = Get-Content C:\Computers.txt;
$start = $true;

# Setup the Service array with the service names we want to check are running
$serviceArray = 'uvnc_service';

# Powershell knows it's an array so working with it is simple
foreach($computer in $computers)
{
Write-Host "Checking $computer";
$objWMIService = Get-WmiObject -Class win32_service -computer $computer

foreach($service in $objWMIService)
{
# Check each service specicfied in the $serviceArray
foreach($srv in $serviceArray)
{
if($service.name -eq $srv)
{
Write-Host "$srv is present on $computer.";
if($service.state -eq "running")
{
Write-Host "$srv is running on $computer";
}
else
{
Write-Host "$srv is not running on $computer";
# If $start is true the script will attempt to start the service if it is stopped
if($start -eq $true)
{
# Attempt to start the current service on the current computer
$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
$name = $serviceInstance.Name;
Write-Host "Attempting to start $name on $computer."
$serviceInstance.StartService() | Out-Null;
# Refresh the object instance so we get new data
$serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
$state = $serviceInstance.State;
Write-Host "$name is ""$state"" on $computer.";
}
}
}
}
}
}


See More: PowerShell output results to text file

Report •

#1
May 18, 2011 at 09:08:33
Logging a PS script is something of an . . . issue. If you wanted to just save your output, you can use Write-FIle, and/or use the > or >> redirectors like you would with a batch script.

How To Ask Questions The Smart Way


Report •

#2
May 18, 2011 at 09:12:39
I used the file-out command (set the $file variable as the path to where the output txt file is) and that works fine. Thank you

Report •
Related Solutions


Ask Question