Powershell in VB.NET with Admin rights - vb.net

I'm writing a webservice with PowerShell commands where I want to start and stop services on the local computer and also on remote computer.
It's not a problem to start and stop the services on remote computers. I do this with an WmiObject as you can see below.
If I want to start a local service it says that I don't have the permissions.
I can't use an WmiObject with Credentials if I want to start an local service.
What can I do to start the service with admin rights?
My Script (strScriptText):
$username = "domain\administrator"
$pw = convertto-securestring "password" -asplaintext -force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $pw
$computername = "serverAB"
if ( $computername.Contains("serverAB")){(Get-WmiObject -class Win32_Service -filter "name='AppIDSvc'").startservice().returnvalue}
else {(Get-WmiObject -class Win32_Service -ComputerName $computername -Credential $cred -filter "name='AppIDSvc'").startservice().returnvalue}
vb:
runspace = RunspaceFactory.CreateRunspace()
runspace.Open()
pipeline = runspace.CreatePipeline()
pipeline.Commands.AddScript(strScriptText)
pipeline.Commands.Add("Out-String")

Can't you try to use the old .NET method through PowerShell.
# Create an authentication object
$ConOptions = New-Object System.Management.ConnectionOptions
$ConOptions.Username = "dom\jpb"
$ConOptions.Password = "pwd"
$ConOptions.EnablePrivileges = $true
$ConOptions.Impersonation = "Impersonate"
$ConOptions.Authentication = "Default"
# Creation of a rmote or local process
$scope = New-Object System.Management.ManagementScope("\\dom.fr\root\cimV2", $ConOptions)
$ObjectGetOptions = New-Object System.Management.ObjectGetOptions($null,
[System.TimeSpan]::MaxValue, $true)
$proc = New-Object System.Management.ManagementClass($scope,
"\\dom.fr\ROOT\CIMV2:Win32_Process", $ObjectGetOptions)
# Equivalent to :
# $proc = [wmiclass]"\\.\ROOT\CIMV2:Win32_Process"
# $res = $proc.Create("cmd.exe")

Related

How to use App Pool Identity to connect using SqlClient in Powershell?

We have many servers with a ASP.Net application installed. I'm trying to figure out a automatic way to connect to the sql server using Powershell.
They use a domain account to run the app pool. I have the code below to get the connection string from the app and the app pool identity to try to open a connection to sql.
However, when I run it in powershell, the sql login fails for, Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'. I don't understand why. I confirmed the ASP.Net Application is using the App Pool Identity in SQL via sp_who2.
Output confirms that the invoke-command is using the App Pool Identity. I can't change the connectionstring per business policies. I want to only use .Net to connect to SQL because I know .Net framework 4.8 will be on all machines I use to run it.
I removed the code for getting the connection string and app pool identity from the sample below in hopes to allow more people to troubleshoot.
Just update the username, password, and server name below and try it out
$username = 'MyUsername'
$password = 'MyPassword'
$ConnStr = 'Data Source=MyServer;Trusted_Connection=yes;'
$query = 'Select system_user, ##servername DBHostName,(SELECT login_time FROM sys.sysprocesses where spid=1)SQLUptime, ##version SQLVersion;'
$SQLPoshCmds = {
$env:USERNAME
$args[0]
try{
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $args[0]
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $args[1]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlConnection.open()
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables|fl
}
Catch{
$_
# write "`r`n$($_.Exception)"
# write $_.ScriptStackTrace
# write $_.ErrorDetails
}
Finally{
$SqlConnection.Close()
$SqlConnection.Dispose()
}
}
if($ConnStr.Contains('Trusted_Connection=yes;')){
invoke-command -ArgumentList $ConnStr,$query -ComputerName '.' -ScriptBlock $SQLPoshCmds -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,(ConvertTo-SecureString -AsPlainText $password -Force))
}else{
invoke-command -NoNewScope -ScriptBlock $SQLPoshCmds
}

trying to connect to SQL using Get-Credential in Winpe

Does anyone know how to pass Get-Credentials to a SQL login using powershell?
I have tried many different ways but no success.
This needs to run in winpe - i can get the credentials using Get-Credential but i need to use those to connect to SQL DB - i keep getting.
Login failed for 'NT AUTHORITY\ANONYMOUS LOGIN' The below code works fine in Windows - I am logged on as the user though so it must not be passing the credentials. if i remove the trusted_connection=true; i get the failed login and this is the best test for WINPE as no one is logged on. Is there a way to pass those Get-Credentials to SQL?
Either that or the same code does not work in WINPE - not sure why though?
$Cred = Get-Credential
Function SQL_CONNECT ($Query){
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Cred.Username;password=$Cred.Password;trusted_connection=true;"
$SqlConnection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = $Query
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$a = $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
}
$Owners = SQL_CONNECT "Select Task_Name, Task_owner, first_action_query_date from PROV_HISTORY_TASK" | Select-Object Task_Owner, first_action_query_date
$Owners
SQL connections use either:
Windows Authentication ("Trusted_Connection=True")
or
SQL Authentication ("User Id=myUsername;Password=myPassword;")
You cannot have both "Trusted_Connection" and "User ID/Password", you have to pick one.
In order to use Windows Authentication, the PowerShell process must be running as the user that has access to the database. i.e. you have to launch the PowerShell process as impersonating that user, and run your code.
Rough example will look something like this:
# Get the other user's credentials
$credential = Get-Credential
# Execute a scriptblock as another user
$commands = #'
#....code....
$ConnectionString = "server=VM855;database=LDMS2016;trusted_connection=true;"
#.....etc....
'#
Start-Process -FilePath Powershell.exe -LoadUserProfile -Credential $credential -ArgumentList '-Command', $commands
Or, the easier method is to just use SQL authentication, and hard code the username/password.
$ConnectionString = "server=VM855;database=LDMS2016;user id=Username;password=Password;"
Or at the very least you will have to use Read-Host to read in the username and password because $Cred.Password returns System.Security.SecureString and not the password in plain text.
For ex.
$Username = Read-Host "User:"
$Password = Read-Host "Password:"
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Username;password=$Password;"

Authentication error with webclient in powershell

I'm relatively new to Powershell so really not sure where to go with this issue now. I am trying to download a file from a subversion repository and am getting the (401) Unauthorized" error. I am able to log into the site and download the file using IE using the exact Same credentials on the same machine.
$source = "http://repository/folder/File.exe"
$destination = "E:\Temp\File.exe"
$wc = New-Object System.Net.WebClient
$user="user"
$pwd=convertto-securestring -string "password" -AsPlainText -force
$creds=New-Object System.Management.Automation.PSCredential -ArgumentList $user, $pwd
$wc.Credentials = New-Object System.Net.NetworkCredential ($user, $Creds.GetNetworkCredential().Password,"DOMAIN")
$download=$wc.DownloadFile($source, "$destination")
Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (401) Unauthorized."
Any ideas if this is cross platform issue? And how to get around this?
Thanks
Are you using basic auth on your iis/apache? If so try this:
$source = "http://repository/folder/File.exe"
$destination = "E:\Temp\File.exe"
$wc = new-object System.Net.WebClient
$credCache = new-object System.Net.CredentialCache
$creds = new-object System.Net.NetworkCredential($user,$pwd)
$credCache.Add($source, "Basic", $creds)
$wc.Credentials = $credCache
$wc.DownloadFile($source, $destination)

Create a SQL Server User using Powershell

I've written a powershell script that creates a new sql server database and login, and then sets the database owner to the newly created user. This is successful. However, I get a login failed exception when attempting to login within the same script. If I use SQL Server Management Studio the login works.
Here's the script:
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($server, 'TestDB')
$db.Create()
$login = new-object Microsoft.SqlServer.Management.Smo.Login("(local)", 'TestUser')
$login.LoginType = 'SqlLogin'
$login.PasswordPolicyEnforced = $false
$login.PasswordExpirationEnabled = $false
$login.Create('Password1')
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $server.Databases.Item('TestDB')
$db.SetOwner('TestUser', $TRUE)
$db.Alter()
Invoke-Sqlcmd -ServerInstance localhost -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
I've tried adding a Start-Sleep (up to 5mins) to no avail, and I've tried Restart-Service mssqlserver -Force, also to no avail.
Any ideas?
This isn't an answer to the problem I was encountering, just a work around. The script is being run as part of an automated deployment, the overall scripts are run under the "NT AUTHORITY\SYSTEM" username, so to get around my logging in issue I'm simply using Integrated Security=true.
I think your final line should read:
Invoke-Sqlcmd -ServerInstance '(local)' -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
Notice the use of '(local)' rather than 'localhost'.
follow the codes below
$SqlServer = "servar.site.com Or server ip with port"
$SqlDBName = "dbName"
$sqlConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$sqlConnection.ServerInstance=$SqlServer
$sqlConnection.LoginSecure = $false
$sqlConnection.Login = "userid if you have"
$sqlConnection.Password = "password if is needed to connect to sql server"
Add-Type -Path "C:\Program Files\Microsoft SQL
Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlConnection)
# get all of the current logins and their types
$server.Logins |
Select-Object Name, LoginType, Parent
# create a new login by prompting for new credentials
$NewLoginCredentials = Get-Credential -Message "Enter credentials for the new login"
$NewLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($server,
$NewLoginCredentials.UserName)
$NewLogin.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$NewLogin.Create($NewLoginCredentials.Password)
# create a new database user for the newly created login
$NewUser = New-Object
Microsoft.SqlServer.Management.Smo.User($server.Databases[$SqlDBName],
$NewLoginCredentials.UserName)
$NewUser.Login = $NewLoginCredentials.UserName
$NewUser.Create()
$NewUser.AddToRole("db_datareader")

Azure database backup to blob using Powershell

We need to backup the azure database and store it on blob so that it can be restored. I've seen this blog but it uses the third party cmdlets.
http://weblogs.thinktecture.com/cweyer/2011/01/automating-backup-of-a-sql-azure-database-to-azure-blob-storage-with-the-help-of-powershell-and-task-scheduler.html
Could someone please guide/help how above can be achieved using powershell.
Backing up to WA Blob Store is not supported from Azure DB, rather the service does automatic backups for you with PITR capability. You'll find the following documentation useful:
http://msdn.microsoft.com/en-us/library/azure/hh852669.aspx
http://msdn.microsoft.com/en-us/library/azure/jj650016.aspx
Hope this helps.
Here is my powershell script
https://gist.github.com/voxon2/be29a3fd6dabbb9155ca
Here is an article describing many different approaches other than powershell
http://blogs.msdn.com/b/mast/archive/2013/03/04/different-ways-to-backup-your-windows-azure-sql-database.aspx
First get your Azure Automation Settings done (see here).
Edit the blow script and save it as .ps1 file. When you run it for
the first time, it will ask you both your azure automation account and
your database credentials. During this process, it will save your
credentials in a local file securely (see here how it is done). After this time on wards, it uses the saved credentials.
The .psl file and the encrypted credential files should be stored in one
directory
Once you are happy you can schedule it to run in task scheduler.
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = #"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"#
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
#Create a directory with you azure server name to isolate configurations
$FileRootPath = "C:\PowerShellScripts\AzureServerName"
Write-Host "Getting Azure credentials"
$AzureCred = Get-MyCredential ($FileRootPath + "AzureSyncred.txt")
#Use Azure Automation Account
#(If You do not have it will not work with other accounts)
Add-AzureAccount -Credential $AzureCred
Select-AzureSubscription -SubscriptionId "myAzureSubscriptionId"
#DO NOT use tcp:myServerName.database.windows.net,1433 but only myServerName
$ServerName = "myServerName"
$Date = Get-Date -format "yyyy-MM-dd-HH-mm"
$DatabaseName = "myTargetDatabaseName"
$BlobName = $Date + "-" + $DatabaseName.bacpac"
$StorageName = "myStorageAccountName"
$ContainerName = "myContainerNameToStoreBacpacFiles"
$StorageKey = "myStorageAccountKey"
Write-Host "Getting database user credential"
#DO NOT use myDatabaseUsername#myServerName but only myDatabaseUsername
$credential = Get-MyCredential ($FileRootPath + "DbSyncred.xml")
Write-Host "Connecting to Azure database"
$SqlCtx = New-AzureSqlDatabaseServerContext -ServerName $ServerName -Credential $credential
Write-Host "Connecting to Blob storage"
$StorageCtx = New-AzureStorageContext -StorageAccountName $StorageName -StorageAccountKey $StorageKey
$Container = Get-AzureStorageContainer -Name $ContainerName -Context $StorageCtx
Write-Host "Exporting data to blob"
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlCtx -StorageContainer $Container -DatabaseName $DatabaseName -BlobName $BlobName
Get-AzureSqlDatabaseImportExportStatus -Request $exportRequest
# use the below script in powershell to execute the script
# powershell -ExecutionPolicy ByPass –File C:\PowerShellScripts\AzureServerName\mySavedScript.ps1 –noexit