Powershell RunAs Administrator in a SSIS Package - powershell

Am trying to remote connect to a server and run a powershell script to open ports in windows firewall in a SSIS Execute Process task
Here is the Powershell code:
$computername = hostname
$script = {
$FireWallRule_1 = Get-NetFirewallRule
$par1 = #{
DisplayName = "DAC"
LocalPort = 1434
Direction="Inbound"
Protocol ="TCP"
Action = "Allow"
}
$FireWallRule_2 = Get-NetFirewallRule
$par2 = #{
DisplayName = "MSSQLSERVER"
LocalPort = 1433
Direction="Inbound"
Protocol ="TCP"
Action = "Allow"
}
$par1.Localport = 1434
$par1.DisplayName = "DAC"
if (-not $FireWallRule_1.DisplayName.Contains($par1.DisplayName)) {New-NetFirewallRule #par1}
$par2.LocalPort = 1433
$par2.DisplayName = "MSSQLSERVER"
if (-not $FireWallRule_2.DisplayName.Contains($par2.DisplayName)) {New-NetFirewallRule #par2}
}
Invoke-Command -ScriptBlock $script -ComputerName $computername
Here is the error i got:
Connecting to remote server [SERVERNAME] failed with the following error message: Access is denied. For more information, see the
aboute_Remote_Troubleshooting Helptopic.
+ CategoryInfo : OpenError: (SERVERNAME:String) [], PSRemotingTransportException
+ FullyQualifiederrorId : AccessDenied, PSSessionStateBroken
I have tried to run the PS script locally and its working, the account that run ssis is local administrator on the target server. Is it possible to RunAs Administrator in a SSIS Package?
Thanks Håkan

Related

Configuring Remote Desktop Services remotely via powershell

Trying to manage our Remote Desktop Services installation using PowerShell and we're running into an issue where the commands in the RemoteDeskop module and the RemoteDesktopServices module do not appear to work when being run via Invoke-Command. Basically it appears that these functions do not work when run in a remote session.
The script below gets the following error:
The RD Connection Broker server is not available. Verify that you can
connect to the RD Connection Broker server.
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-RDServer
+ PSComputerName : AWSELABSDevX13.LABSDEV.com
$server = "OUR_SERVER"
$connection_broker = "OUR_SERVER"
$collectionName ="COLLECTION"
$admin_user = "FULLY_QUALIFIED_DOMAIN_USER"
$password = "PASSWORD"
$password_sec = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($admin_user, $password_sec)
$sb =
{
function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
if (Test-IsAdmin) {
""
"You are running with Administrator access."
""
} else {
""
"You do not have admin access."
""
}
whoami /priv
Import-Module RemoteDesktop
Import-Module RemoteDesktopServices
Get-RDServer
}
Invoke-Command -Credential $cred -ComputerName $connection_broker -ScriptBlock $sb

How to set up client in Powershell 5.0 DSC Pull Mode

I have 2 servers set up for DSC, Both running Powershell 5.0 and Server 12 R2, DSCPULL is configured as a DSC Pull Server over HTTP, DSCIIS is the client.
On DSCIIS i am trying to set it up so that it downloads the config from the Pull server via a configuration names, i have taken code from the MSDN website and altered slightly to my requirements but it still isn't working.
[DSCLocalConfigurationManager()]
configuration PullClientConfigID
{
Node localhost
{
Settings
{
RefreshMode = 'Pull'
RefreshFrequencyMins = 30
RebootNodeIfNeeded = $true
}
ConfigurationRepositoryWeb DSCPULL
{
ServerURL = 'http://DSCPULL:8080/PSDSCPullServer.svc'
RegistrationKey = 'test'
ConfigurationNames = #('WebServer')
AllowUnsecureConnection = $true
}
}
}
PullClientConfigID -OutputPath c:\Configs\TargetNodes
Start-DscConfiguration C:\Configs\TargetNodes -ComputerName localhost -wait -Verbose
The error i receive is
Start-DscConfiguration : The computer-specific MOF file for computer localhost does not exist in the current directory.
At line:1 char:1
+ Start-DscConfiguration C:\Configs\TargetNodes -ComputerName localhost ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-DscConfiguration], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.DesiredStateConfiguration.Commands.StartDscConfiguration
Command
I have tried changing "Node Localhost" to the server name and then run the last line with the correct "ComputerName" but i get the same error.
I should have been using Set-DSCLocalConfigurationManager not Start-DSCConfiguration
Set-DSCLocalConfigurationManager localhost –Path C:\Configs\TargetNodes –Verbose

Powershell - Change SQL Server Service Password and Start Service

The SQL Server service is currently not running.
I am trying to change the password for my local SQL instance then start the instance using PowerShell.
I've tried using a remote session as suggested from this site (http://www.databasejournal.com/features/mssql/managing-sql-server-services-with-powershell.html)
PS - When I run PowerShell ISE 5, I am running it as an admin.
#Create a new remote PowerShell session and pass in the scrip block to be executed
$session = New-PSSession -ComputerName Laptop123 -Credential Domain01\User01
$UserName = "Domain01\User01" # specify user Name here
$Password = "Password1" # specify Password here
Invoke-Command -Session $session -ArgumentList $UserName, $Password -Scriptblock {
param($UserName, $Password)
# Start SQL Server Database engine service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='MSSQL$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'MSSQL$SQL2008R2_32BIT' -Force
Start-Service 'MSSQL$SQL2008R2_32BIT'
# Start SQL Server SQL Server Agent service (default instance)
$Svc = Get-WmiObject win32_service -filter "name='SQLAgent$SQL2008R2_32BIT'"
$Svc.Change($Null, $Null, $Null, $Null, $Null, $Null, $UserName, $Password)
Stop-Service -Name 'SQLAgent$SQL2008R2_32BIT' -Force
Start-Service 'SQLAgent$SQL2008R2_32BIT'
}
However, I end up getting the following errors:
Method invocation failed because [System.ServiceProcess.ServiceController] does not contain a method named 'Change'.
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : Laptop123
Service 'SQL Server (SQL2008R2_32BIT) (MSSQL$SQL2008R2_32BIT)' cannot be started due to the following error: Cannot start service MSSQL$SQL2008R2_32BIT on computer '.'.
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
+ PSComputerName : Laptop123
Any suggestions on how to change the service password and then start it?
it looks like you are calling the wrong name of the service in your script try changing the name filter to 'SQL Server (SQL2008R2_32BIT)'
Let me know if that works, if not list any output you may receive from trying that.

Commands in Workflow not recognized in Remote Session

We have moved our system alerting over to SCOM 2012 and receive heartbeat alerts when servers go offline. Presently there are approximately 750 servers in the vDC that I am managing. The SCOM 2012 server is in a different untrusted domain.
I have one working script where it puts the servers in Maintenance mode, but its run serially and takes about 40 minutes to put nearly 400 servers in Maintenance Mode. This is a workable solution, but I would like to use the foreach -parallel command to speed it up.
I have my workflow (to use the foreach -parallel command) created and placed in one of the default PowerShell Module locations on the Source and Destination Machines. I've tested the set of commands outside of the workflow on the SCOM server and it runs successfully. When I try to run the command remotely via an Invoke-command, the SCOM commands come back as being unrecognized.
#Get Date for usage in Connection Name
$Date = Get-Date -Format HHmmsss
#combine Name with Date to uniquify
$name = "ScomMM" + $Date
#Collect Servers from WSUS Server
[reflection.assembly]::LoadWithPartialName("Microsoft.Updateservices.Administration") | out-null
$WSUS = [Microsoft.updateservices.administration.adminproxy]::Getupdateserver("ServerName",$false,8530);
$TS = $wsus.getcomputertargetgroups() | ? {($_.name -eq "Group1") -or ($_.Name -eq "Group2")}
$computers = $TS.getcomputertargets() | Select-Object FullDomainName
#Setup Trusted host
invoke-Command -ScriptBlock {(winrm.cmd s winrm/config/client '#{TrustedHosts="*PublicIPAddress*"}')}
Enable-PSRemoting -Force
#Credentials stored in a file
$username = "username"
$password = get-content 'Path' | convertto-securestring
$creds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,$password
$session = new-PSSession -ComputerName "IPAddress" -Credential $creds -Name $name
#SCOM Commands Module
Import-Module OperationsManager
#Workflow
Import-Module Set-MM
#Run the command remotely
Invoke-Command -Session $session -ScriptBlock {
Import-Module -Name Set-MM
Set-MM -computers $using:computers
}
#Workflow - Stored at C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Set-MM\Set-MM.psm1
Workflow Set-MM
{
Param($computers)
Foreach -Parallel($computer in $computers)
{
Get-SCOMClassInstance -Name $computers.FullDomainName | Start-SCOMMaintenanceMode -EndTime (Get-Date).AddMinutes(6) -Reason PlannedOperatingSystemReconfiguration
}
}
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Set-MM\Set-MM.psm1:6 char:3
+ Get-SCOMClassInstance -Name $computers.FullDomainName | Start ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot find the 'Get-SCOMClassInstance' command. If this command is defined as a workflow, ensure it is
defined before the workflow that calls it. If it is a command intended to run directly within Windows
PowerShell (or is not available on this system), place it in an InlineScript: 'InlineScript {
Get-SCOMClassInstance }'
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : CommandNotFound
+ PSComputerName : IPAddress
The term 'Set-MM' 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.
+ CategoryInfo : ObjectNotFound: (Set-MM:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : IPAddress
Get-PSSession | Remove-PSSession
If I use an Inlinescript on the script inside the foreach -Parallel
InlineScript{Get-SCOMClassInstance -Name $Using:computers.FullDomainName | Start-SCOMMaintenanceMode -EndTime (Get-Date).AddMinutes(6) -Reason PlannedOperatingSystemReconfiguration}
I get this for each computer that is attempting to get processed in the workflow:
The term 'Get-SCOMClassInstance' 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.
+ CategoryInfo : ObjectNotFound: (Get-SCOMClassInstance:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : ServerName

Why does setting the 'QueuingEnabled' of a COM+ app remotely by powershell cause the save to fail?

I have this powershell script which is creating COM+ applications on a remote machine:
$credentials = Get-Credential -Message "Test" -User "DOMAIN\User"
$roleRM = new-pssession -computername MACHINE -credential $credentials
Invoke-Command -Session $roleRM -scriptblock `
{
$comAdmin = New-Object -ComObject ("COMAdmin.COMAdminCatalog.1")
$comApplicationCollection = $comAdmin.GetCollection("Applications")
$comApplicationCollection.Populate()
$comApplication = $comApplicationCollection.Add()
$comApplication.Value("Name") = "Server"
$comApplication.Value("ApplicationAccessChecksEnabled") = 0
$comApplication.Value("AccessChecksLevel") = (0)
$comApplication.Value("Authentication") = (1)
$comApplication.Value("Identity") = "DOMAIN\User"
$comApplication.Value("Password") = "password"
$comApplication.Value("QueuingEnabled") = 1
$comApplication.Value("QueueListenerEnabled") = 1
$comApplicationCollection.SaveChanges()
}
but when I try and run it it fails with this error:
Exception calling "SaveChanges" with "0" argument(s): "An operations error occurred.
"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : MACHINE
If I exclude this line:
$comApplication.Value("QueuingEnabled") = 1
then it saves and creates the application correctly. If I run this script locally then it creates the application correctly on the local machine with QueuingEnabled=1, but always fails when running on a remote machine.
Why might this be?
Try setting "Authentication" to 4 or 6 and see if that changes anything. See this.