Reputation: 35
I saved this function into StartWindowsService.ps1 file. I made sure that the executionpolicy is 'Unrestricted'. I ran this file the following way:
Before I ran the next line, I stopped the 'FAService' from services. so that my function will start the service.
I ran the following line at Powershell command prompt. It doesn't write to host anything and doesn't start FASservice. I am really dumb founded.
C:\LocationofthisFile\ .\StartWindowsService.ps1 StartWindowsService FAService
I also tried
function StartWindowsService{
Param([string] $ServiceName)
$aService = Get-Service -Name $ServiceName
if ($aService.Status -ne "Running"){
Start-Service $ServiceName
Write-Host "Starting " $ServiceName " service"
" ---------------------- "
" Service is now started"
}
if ($aService.Status -eq "running"){
Write-Host "$ServiceName service is already started"
}
}
Thank you
Upvotes: 1
Views: 884
Reputation: 28993
If you have just a function in a script as you have, when you run the script it will start a new PowerShell scope, define the function because that's all the script does, then quit and clear it up. None of the other things you passed as parameters (function name, service name) go anywhere because the script doesn't look for them. Only the function does, and you're not calling the function.
One way forward is to dot source
the script which is . .\thing.ps1
with a dot and a space at the start. Or maybe Import-Module .\thing.ps1
. These will define the function and keep it in your current scope, so you can call it in the shell:
c:\path\ > . .\StartWindowsService.ps1
c:\path\ > StartWindowsService FAService
Another way forward is to make the script be the function by removing the definition:
Param([string] $ServiceName)
$aService = Get-Service -Name $ServiceName
and then you can use it directly from the file
c:\path\ > .\StartWindowsService.ps1 FAService
and the parameter goes to the Param()
part of the script and it works as if it was a function.
Upvotes: 2