Powershell Force windows service that has dependency service to stop - powershell

I'm currently working on a powershell script to stop certain windows services and set its startup type to disabled.
My script works fine for services with status stopped however for services that has dependency service running cannot be stopped. I get bunch of errors. I tried to append -Force switch,it aint working too. What could be wrong.
Below is my script.
# Function defintion
function Shut_Services_Down {
# Services array
$services_to_shut_down = #("spooler", "XblGameSave", "Fax")
# Loop each service in the array
foreach ( $node in $services_to_shut_down ){
Set-Service -Name $node -Status stopped -StartupType Disabled -Force
}
}
# Call the function
Shut_Services_Down
error 1
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
Set-Service : A parameter cannot be found that matches parameter name 'Force'.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:71
+ ... Set-Service -Name $node -Status stopped -StartupType Disabled -Force
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
error 2, after removing -Force switch
PS C:\users\admin\desktop\psscripts> .\services.ps1
Set-Service : Cannot stop service 'Print Spooler (spooler)' because it has dependent services.
At C:\users\admin\desktop\psscripts\services.ps1:9 char:9
+ Set-Service -Name $node -Status stopped -StartupType Disabled
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
+ FullyQualifiedErrorId : ServiceHasDependentServicesNoForce,Microsoft.PowerShell.Commands.SetServiceCommand
Solution
# Function defintion
function Shut_Services_Down {
# Services array
$services_to_shut_down = #("spooler", "XblGameSave", "Fax")
# Loop each service in the array
foreach ( $node in $services_to_shut_down )
{
Stop-Service -Name $node -Force -Confirm:$false
Set-Service -Name $node -Status stopped -StartupType Disabled
}
}
# Get-Service -Name "spooler" | Format-List -Property Name,DependentServices
# Call the function
Shut_Services_Down

Related

Create folder on remote computer using PowerShell

The intention is to create a folder on a remote computer C drive.
I'm trying to run this:
$stageSvrs | %{
Invoke-Command -ComputerName $_ -ScriptBlock {
$setupFolder = "c:\Support\test1"
Write-Host "Creating Support Folder"
New-Item -Path $setupFolder -type directory -Force
Write-Host "Folder creation complete"
}
}
but I get the following error:
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At \\company.local\share\share\userdata\username\Documents\WindowsPowerShell\CreateFolder.ps1:2 char:39
+ Invoke-Command -ComputerName $_ -ScriptBlock {
+ ~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Powershell scripting1

I am running this Script to get the directory listing
It was working few days ago but I keep having this error
New-PSSession : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:11 char:38
+ $session=New-PSSession -ComputerName $servers
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewPSSessionCommand
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:31 char:25
+ Invoke-Command -Session $session -ScriptBlock $scb
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
$servers=get-content C:\temp\servers.txt
$session=New-PSSession -ComputerName $servers
$scb = {
Write-host "working on $env:COMPUTERNAME" -ForegroundColor Red
$volumes=Get-WmiObject win32_volume -Filter "drivetype=3"
foreach($volume in $volumes) {
$driveletter=$volume.driveletter
if($driveLetter -ne $null) {
$drivename=$volume.name
(Get-ChildItem -path $drivename -Directory) |Select-Object Name,FullName
}
}
}
Invoke-Command -Session $session -ScriptBlock $scb

Erroraaction in uploading file by FTP

I have a file with IP address of servers. And script reads adress ($line) by adress, but sometimes can occur address of server that will be down. It is necessary to script steel run till end of IP address. So I used -Erroraction Continue to Set_FTPConnection But script break anyway. How to solve this problem?
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
}
Errors:
From my code
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.173
Set-FTPConnection : Exception calling "GetResponse" with "0" argument(s): "Unable to connect to the remote server"
At F:\DPI FTP\FTPUpload_v2.ps1:25 char:13
+ Set-FTPConnection -Credentials $FTPCredential -Server $li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Set-FTPConnection
With Test-NetConnection
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:21 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
ftp url: 10.80.59.173
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.170
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
With If:
WARNING: Could not connect to 10.80.59.173
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:20 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing.
At F:\DPI FTP\FTPUpload_v2.ps1:47 char:9
+ Stop-Transcript
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand
Continue is actually the default setting. It means that if a non-terminating error occurs, it will show the error and then should be continuing with the command and rest of the script. You could try SilentlyContinue to see if that helps.
Alternatively you could test if the IP Address is connectable first. If you're using Windows 8/Server 2012 or newer and PowerShell v4+ you could use Test-NetConnection -Port 21 to do this specifically for the FTP port, if not you could use Test-Connection instead (which is a PS equivalent of Ping):
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
If (Test-Connection $line) {
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
} Else {
Write-Warning "Could not connect to $line"
}
}

Azure runbook GetMember Error

I have the following runbook script which is supposed to copy application settings from one web app to another but when I run it I get an error.
# Get the credential to use for Authentication to Azure and Azure Subscription Name
$cred = Get-AutomationPSCredential -Name 'Credintial'
Login-AzureRmAccount -Credential $cred
$fromResourceGroup = 'parkprod'
$fromSite = 'parkprod'
$toResourceGroup = 'cmsfarhad'
$toSite = 'farhadparkingapi'
$props = (Invoke-AzureRmResourceAction -ResourceGroupName $fromResourceGroup -ResourceType Microsoft.Web/sites/Config -Name $fromSite/appsettings -Action list -ApiVersion 2015-08-01 -Force).Properties
$hash = #{}
$props | Get-Member -MemberType NoteProperty | % { $hash[$_.Name] = $props.($_.Name) }
Set-AzureRMWebApp -ResourceGroupName $toResourceGroup -Name $toSite -AppSettings $hash
Error:
Environments Context
------------ -------
{[AzureCloud, AzureCloud], [AzureChinaCloud, AzureChinaCloud], [AzureUSGovernment, AzureUSGovernment]} Microsoft.Azur...
Invoke-AzureRmResourceAction : Object reference not set to an instance of an object.
At line:10 char:11
+ $props = (Invoke-AzureRmResourceAction -ResourceGroupName $fromResour ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException
Get-Member : The input object cannot be bound to any parameters for the command either because the command does not
take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:13 char:10
+ $props | Get-Member -InputObject $f -MemberType NoteProperty | % { $h ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Member], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.GetMemberCommand
Get-Member : You must specify an object for the Get-Member cmdlet.
At line:13 char:10
+ $props | Get-Member -InputObject $f -MemberType NoteProperty | % { $h ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-Member], InvalidOperationException
+ FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
Set-AzureRMWebApp : The term 'Set-AzureRMWebApp' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:15 char:1
+ Set-AzureRMWebApp -ResourceGroupName $toResourceGroup -Name $toSite - ...
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Set-AzureRMWebApp:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
You have to install AzureRm.Websites. A cmdlet from that module is missing. Check if you have installed it on your system, and if not install it.
As Peter says, the AzureRM.Websites PowerShell module does not currently ship in the Automation service and so you need to import this module yourself. Please see https://azure.microsoft.com/en-us/blog/announcing-azure-resource-manager-support-azure-automation-runbooks/ for more details on that.
But it looks like you also have an issue with your use of the Invoke-AzureRmResourceAction cmdlet. The error being returned isn't very useful, and I'm not very familiar with that cmdlet, so hard for me to say what you're doing wrong. One thing to test would be to check if the same cmdlet call works from local PowerShell. If it does not work in local PowerShell, the issue is with your code and not any quirk in Azure Automation.

powershell get-content path null error

$commonElementsLocation = ((Get-Location).Path + "\FolderMatchingCommonWords.txt")
if ($commonElementsLocation) {
$result += Start-Job -InitializationScript {
$commonElements = Get-Content -Path $commonElementsLocation
} -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job
}
Not sure what I am doing wrong here - probably a stupid mistake, but I put a condition around the Start-Job statement, and powershell still gives the following error:
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:39
+ $commonElements = (Get-Content -Path $commonElementsLocation)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentC
ommand
Running startup script threw an error: Cannot bind argument to parameter 'Path' because it is null..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
In v3 add $using:
....(Get-Content -Path $using:commonElementsLocation...
You have already used a variable for a script block once with $testScriptBlock. You could just do that again for -InitializationScript?
$anotherSB = [scriptblock]::create("$commonElements = (Get-Content -Path $commonElementsLocation)")
$result += Start-Job -InitializationScript $anotherSB -ScriptBlock $testScriptBlock -ArgumentList "testing" | Wait-Job | Receive-Job