Welcome › Forums › General PowerShell Q&A › Issues with outputing
- This topic has 4 replies, 2 voices, and was last updated 1 month, 1 week ago by
Participant.
Viewing 4 reply threads
-
AuthorPosts
-
-
December 7, 2020 at 2:37 pm #277353I’m trying to output to a text file if a user receives an error while typing in a service. Any help would be appreciated.Function Set-DependentService { #command retrieves the dependent services for a service and allows user to take start/stop action on them[CmdletBinding()]param([Parameter(Mandatory = $True)][String]$ServiceName,[Parameter(Mandatory = $True)][String]$Action,[String]$ErrorLog = ‘c:\error.txt’,[switch]$LogErrors)PROCESS{try{$dependentservices = Get-Service $servicename -DependentServices -ErrorAction stopForeach ($Service in $dependentservices){if ($Action -eq “Start”){start-service $service}else{stop-service $service}}$props = @{‘ServiceName’ = $service.name;‘Status’ = $service.Status;‘StartType’ = $service.StartType}$obj = New-Object -TypeName PSObject -Property $propsWrite-output $obj}catch{Write-Warning “Warning, an error has occured: Please enter a valid service name.”if($LogErrors){“Service Name: $servicename… Warning, an error has occured: Please enter a valid name.” | out-file $ErrorLog -Append}}}}
-
December 7, 2020 at 2:45 pm #277356
What exactly is the error\issue? First thing that jumps out is you are writing to the root of C:, which standard users don’t have permissions to do. A better default path would be something like this:
PowerShell1[environment]::GetFolderPath('Desktop') -
December 7, 2020 at 3:04 pm #277362
So if they put in a service that isn’t recognized it’ll warn them and log it into a file. I have everything work besides the log being sent to a file.
Thanks
-
December 7, 2020 at 3:10 pm #277365
There is code in the function to accomplish what you are asking. Are you getting an error? Are you adding the switch -LogErrors to the command?
-
December 7, 2020 at 3:17 pm #277368
I got it to work thanks!
-
-
AuthorPosts
Viewing 4 reply threads
- You must be logged in to reply to this topic.