Trying to use PowerShell to install Microsoft sql management studio (ssms) - amazon-web-services

I'm trying to install Microsoft sql server management studio on my AWS windows server and I keep getting this error on PowerShell
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$here = pwd
$software = "SQL Server Management Studio";
$installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where { $_.DisplayName -eq $software }) -ne $null
#If SQSS was not installed before, it will be download required files and install it.
If(-Not $installed)
{
Write-Host "'$software' is NOT installed.";
wget https://aka.ms/ssmsfullsetup -outfile "SSMS-Setup-ENU.exe"
.\SSMS-Setup-ENU.exe /install /quiet /norestart
}
#If SQSS was installed before, it will try to update it to the newer version, if available.
#If no updates available, it will do nothing.
else
{
Write-Host "'$software' is installed."
if ( Test-Path -Path $here\SSMS-Setup-ENU.exe )
{
.\SSMS-Setup-ENU.exe /update /quiet /norestart
}
else {
wget https://aka.ms/ssmsfullsetup -outfile "SSMS-Setup-ENU.exe"
.\SSMS-Setup-ENU.exe /update /quiet /norestart
}
}
Here is the error I keep getting
wget : The remote name could not be resolved: 'download.microsoft.com'
At C:\Temp\mqss-1.ps1:12 char:1
wget https://aka.ms/ssmsfullsetup -outfile "SSMS-Setup-ENU.exe"
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Continuing from my comment. The installer does not offer an /update switch, so you can just use install for both. I would use Start-Process to execute the command and let it provide the array of arguments to it.
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Push-Location $env:temp
$software = "SQL Server Management Studio"
$installed = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -eq $software )
If(-Not $installed){
Write-Verbose "'$software' is NOT installed, installing" -Verbose
}
else{
Write-Verbose "'$software' is installed, updating" -Verbose
}
Write-Verbose "Downloading SSMS-Setup-ENU.exe" -Verbose
try{
Invoke-WebRequest https://aka.ms/ssmsfullsetup -OutFile '.\SSMS-Setup-ENU.exe' -ErrorAction Stop
}
catch{
Write-Warning "Error downloading file: $($_.exception.message)"
break
}
$arguments = "/install","/quiet","/norestart"
Write-Verbose "Executing 'SSMS-Setup-ENU.exe $arguments'" -Verbose
try{
$result = Start-Process .\SSMS-Setup-ENU.exe -ArgumentList $arguments -PassThru -Wait
}
catch{
Write-Warning $_.exception.message
}
switch -Exact($result.ExitCode){
1603 {
Write-Verbose "Reboot is required" -Verbose
}
0 {
Write-Verbose "Installation successful" -Verbose
}
default{
Write-Verbose "Installation was not successful" -Verbose
}
}

Related

PowerShell does not recognize AWS CLI installed in the same script

I have installed aws cli using powershell script
$command = "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12"
Invoke-Expression $command
Invoke-WebRequest -Uri "https://awscli.amazonaws.com/AWSCLIV2.msi" -Outfile C:\AWSCLIV2.msi
$arguments = "/i `"C:\AWSCLIV2.msi`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait
aws --version
When I try to print the aws --version it gives the below error.
aws : The term 'aws' 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:1 char:1
+ aws
+ ~~~
I was able to fix this by adding the below line after installing aws cli:
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
complete code:
$command = "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12"
Invoke-Expression $command
Invoke-WebRequest -Uri "https://awscli.amazonaws.com/AWSCLIV2.msi" -Outfile C:\AWSCLIV2.msi
$arguments = "/i `"C:\AWSCLIV2.msi`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait
$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine")
aws --version
aws s3 ls

EC2 User data - Disable it after all conditions are met in user data

I'm trying to rename hostname and add to AD of a spot instance. It is a simple powershell script. I've read the docs that by default user data will be disable after it gets executed once and if <persist>true</persist> is used it will not be disabled.
I think I saw somewhere this(enabling to be run at each startup) is done via taskscheduler but can't find the link.
Can someone point me to the task scheduler job or the way to manually disable the userdata once my if conditions are met.
<powershell>
Set-ExecutionPolicy unrestricted -Force
$instanceName = "test-name5"
$username = "domain\username"
$password = "password" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential($username, $password)
Start-Sleep -s 5
$hostname = hostname
$domain = (Get-WmiObject win32_computersystem).Domain
if (!($hostname -eq $instanceName)){
Rename-Computer -NewName $instanceName -restart -force
}Elseif (!($domain -eq 'my.domain.local')){
Start-Sleep -s 5
Add-Computer -DomainName my.domain.local -OUPath "OU=Windows,OU=QAServers,OU=Servers,DC=my,DC=domain,DC=local" -Credential $cred -Force -Restart -erroraction 'stop'
}Else {
####code to disable the running of userdata once above conditions
are met####
}
</powershell>
<persist>true</persist>
It's worth reading the ec2config-service documentation, as the setting you want is referenced in there.
You want the Ec2HandleUserData setting, which is configured in the Config.xml.
Powershell can easily update this setting:
$path = 'C:\Program Files\Amazon\Ec2ConfigService\Settings\config.xml'
$xml = [xml](Get-Content $path)
$state = $xml.Ec2ConfigurationSettings.Plugins.Plugin | where {$_.Name -eq 'Ec2HandleUserData'}
$state.State = 'Disabled'
$xml.Save($path)
I use this code when creating custom AMI's to re-enable userdata handling ($state.State = 'Enabled').
EDIT: The above is for ec2config not ec2launch which is what the OP is using. I'd missed this originally.
I this case I think you need to change the way your script runs, rather than use <persist> and then try to disable its functionality, I would remove the persist tag and call InitializeInstance.ps1 –Schedule (documentation link) in your if for the conditions you want the userdata to re-run:
if ($hostname -ne $instanceName) {
& C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 -Schedule
Rename-Computer -NewName $instanceName -Restart -Force
}
elseif ($domain -ne 'my.domain.local') {
& C:\ProgramData\Amazon\EC2-Windows\Launch\Scripts\InitializeInstance.ps1 -Schedule
Add-Computer -DomainName aws.macmillan.local -OUPath "OU=Windows,OU=QAServers,OU=Servers,DC=my,DC=domain,DC=local" -Credential $cred -Force -Restart -ErrorAction 'stop'
}
As I said in the comments of the previous answer, I had 3 options and since I found the aws scheduled task I went with the last option. Answering my own question since it'll be easy to spot the code.
<powershell>
Set-ExecutionPolicy unrestricted -Force
#Enter instance hostname here
$instanceName = "test-name8"
$username = "domain\username"
#Using ssm parameter store to avoid having the password in plaintext
$password = (Get-SSMParameterValue -Name AD-Password -WithDecryption $True -Region us-east-1).Parameters[0].Value | ConvertTo-SecureString -asPlainText -Force
Start-Sleep -s 3
$cred = New-Object -typename System.Management.Automation.PSCredential($username, $password)
Start-Sleep -s 5
$hostname = hostname
$domain = (Get-WmiObject win32_computersystem).Domain
if ($hostname -ne $instanceName){
Rename-Computer -NewName $instanceName -restart -force
}Elseif ($domain -ne 'my.domain.local'){
Start-Sleep -s 5
Add-Computer -DomainName my.domain.local -OUPath "OU=Windows,OU=QAServers,OU=Servers,DC=my,DC=domain,DC=local" -Credential $cred -Force -Restart -erroraction 'stop'
}Else {
Disable-ScheduledTask -TaskName "Amazon Ec2 Launch - Userdata Execution"
Unregister-ScheduledTask -TaskName "Amazon Ec2 Launch - Userdata Execution"
}
</powershell>
<persist>true</persist>
note: a role that has ssm policies must be attached while launching the server for this ssm parameter command to work.
I was solving similar issue and I had to change Windows Server 2016 hostname and enroll it to Elastic Server Fleet. Also I could not allow instance to be rebooted. I used this code to solve this.
NB. I understand that it is not direct way of doing this and has numerous drawbacks, but in my circumstances goal was achieved without negative impact.
<powershell>
$ComputerName = "MyPCRandomName"
Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" -name "Hostname" -value $ComputerName
elastic-agent enroll --enrollment-token 123 --url=321
</powershell>

Azure ARM DSC - install VS2017 remote debugger

I'm creating a Service Fabric cluster for a dev environment which requires the Visual Studio 2017 Remote Debugger to be installed and running as a service on each node using Powershell DSC.
Our DSC script successfully copies the vs2017 remote tools installer and does the unattended install but we are struggling to get it running as a service and with the correct firewall settings.
Here is what we ended up going with:
# Download and configure Chocolaty
cChocoInstaller InstallChoco
{
InstallDir = "C:\choco"
}
# Download and install VS2017 Remote Debugger
cChocoPackageInstaller InstallRemoteDebugger
{
Name = "visualstudio2017-remotetools"
Version = "15.0.26430.2"
Source = “https://github.com/chocolatey/chocolatey-coreteampackages/tree/master/manual/visualstudio2017-remotetools”
DependsOn = "[cChocoInstaller]installChoco"
}
# Install the remote debugger and run as a service
Script ConfigureRemoteDebugger {
GetScript = { #{ Result = "" } }
TestScript = {
$msvsmonPathx64 = 'C:\Program Files\Microsoft Visual Studio 15.0\Common7\IDE\Remote Debugger\x64\msvsmon.exe'
$serviceName = "msvsmon150"
$result = $true
# Validate the VS2017 Remote Debugger is installed to the harddrive
$result = $result -and (Test-Path $msvsmonPathx64)
# Verify the service exists and is running
if ($service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
if ($service.Status -eq "Running") {
$result = $result -and $true
}
else {
$result = $result -and $false
}
}
else {
$result = $result -and $false
}
return $result
}
SetScript =
{
# Run as service
$startDebugger = $true
$remoteDebugExe = "`"C:\Program Files\Microsoft Visual Studio 15.0\Common7\IDE\Remote Debugger\x64\rdbgservice.exe`" msvsmon150"
$serviceName = "msvsmon150"
$serviceDisplayName = "Visual Studio 2017 Remote Debugger"
$serviceDescription = "Allows members of the Administrators group to remotely debug server applications using Visual Studio. Use the Visual Studio Remote Debugging Configuration Wizard to enable this service."
if (!(Get-Service -Name msvsmon150 -ErrorAction SilentlyContinue)) {
New-Service -Name $serviceName -BinaryPathName $remoteDebugExe -DisplayName $serviceDisplayName -Description $serviceDescription
}
if ($startDebugger -eq $false) {
Set-Service -Name $serviceName -StartupType Manual
}
else {
Set-Service -Name $serviceName -StartupType Automatic
Start-Service -Name $serviceName
}
}
Credential = $serviceAccountCredential
DependsOn = "[cChocoPackageInstaller]InstallRemoteDebugger"
}
Note: Your DSC will likely need to configure the firewall to allow the Remote Debugger otherwise you will not be able to connect.
Big shoutout to Chocolatey for making the download+install process so easy.

I need to create to Redundant VMs (both on 2 different datastores) via function

I have defined all the needed variables in a separate Variable_Defination.ps1 file and have called it up here.
Is there a better way to do this?
I just want a script to create 2 redundant VMs both running on separate datastores and having Affinity rule set up for disaster recovery cases
. ./Variable_Defination.ps1
function CreateRedundantVMs {
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$ClusterName,
[string]$ComputerName1,
[string]$ComputerName2,
[string]$sourcetemplate,
[string]$InfraResourcePoolName,
[string]$OSCustomizationspec,
[string]$description
)
$Viabledatastores = (Get-Cluster $ClusterName | Get-Datastore) |
Where {$_.Name -like '*vSSD*'} |
Sort-Object FreeSpaceGB -Descending |
Select -First 2 -ErrorAction 'Stop'
if ($Viabledatastores) {
$Viabledatastores
} else {
Write-Host "No Viable Datastores found"
break;
}
Write-Verbose "`n---------------------- Creating redundant VMs now ------------------------`n " -Verbose
New-VM -Name $ComputerName1 -ResourcePool $InfraResourcePoolName -Datastore $Viabledatastores[0] -Description $description -Template $sourcetemplate -OSCustomizationspec $OSCustomizationspec -DiskStorageFormat Thin
New-VM -Name $ComputerName2 -ResourcePool $InfraResourcePoolName -Datastore $Viabledatastores[1] -Description $description -Template $sourcetemplate -OSCustomizationspec $OSCustomizationspec -DiskStorageFormat Thin
Start-Sleep -s 3
Write-Host "`n -------------------------------------------------------------------------`n "
Write-Verbose -Message "Virtual Machine $ComputerName1 and $ComputerName2 Deployed. Powering On" -Verbose
Write-Host "`n -------------------------------------------------------------------------`n "
Start-VM -VM $ComputerName1
Start-VM -VM $ComputerName2
}
# calling function
CreateRedundantVMs $ClusterName $ComputerName1 $ComputerName2 $sourcetemplate $InfraResourcePoolName $OSCustomizationspec $description

powershell error wmi

Hi i am new to power shell and i cant seem to get this script to run it is to remote execute a command using the command prompt on a computer in a workgroup here is the error i get the script is below i am running the script on a win 7 machine the machine i want to remote execute on is windows xp sp3 the fire wall is off and the com settings are set for default for authentication settings and identify for impersonate and help would be great
here is the Error
Invoke-WmiMethod : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At C:\Users\Kevin\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:57 char:40
+ $newproc = Invoke-WmiMethod <<<< -class Win32_process -name Create `
+ CategoryInfo : NotSpecified: (:) [Invoke-WmiMethod], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.InvokeWmiMethod
$command = Read-Host " Enter command to run"
$user = "\Administrator"
$Domainname = $HostName +$user
$login = Get-Credential $domainname
[string]$cmd = "CMD.EXE /C " +$command
}
process {
$newproc = Invoke-WmiMethod -class Win32_process -name Create `
-ArgumentList ($cmd) -EnableAllPrivileges -ComputerName $HostName -authentication Packetprivacy -Impersonation 3 -Credential $login
if ($newproc.ReturnValue -eq 0 )
{ Write-host -foregroundcolor Green "Command $($command) Ran Sucessfully on $($HostName)"}
I think this is because Get-Credential won't pass the password to the -credential of Invoke-WmiMethod. I do this exact thing by creating the credential password using "convertto-securestring"
I know it's not as secure as you have to put the password in as plain text, but if you're the only one using the script to do maintenance or such..it's no biggie.
Try this:
$command = Read-Host " Enter command to run"
$pass = ConvertTo-SecureString "yourpassword" -Force -AsPlainText
$Domainname = 'Domain'
$user = '\administrator'
$login = $Domainname + $user
$cred = (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $login, $pass)
[string]$cmd = "CMD.EXE /C " +$command
}
process {
$newproc = Invoke-WmiMethod -class Win32_process -name Create `
-ArgumentList ($cmd) -EnableAllPrivileges -ComputerName $HostName -authentication Packetprivacy -Impersonation 3 -Credential $cred
if ($newproc.ReturnValue -eq 0 )
{ Write-host -foregroundcolor Green "Command $($command) Ran Sucessfully