I am using the Invoke-sqlcmd cmdlet in Powershell to run an SQL query saved in a string against a remote server.
I have included the credential parameter to ask for domain credentials to connect to the SQL instance.
I've tested this without the credential parameter; instead running the Powershell window as the user, this works fine, so I am confident that permissions for the user are set correctly.
However, I cannot get it to work with the credential parameter.
Import-Module -Name SqlServer -force
function Correct-Servername {
param(
[string] $dataSource = ".\SQL",
[string] $database = "MASTER",
[string] $sqlCommand = "sp_dropserver ##servername DECLARE #ServerName SQL_VARIANT = (SELECT serverproperty('Servername')), #SQLQuery NVARCHAR(4000); SET #SQLQuery = 'sp_addserver ''' + CONVERT(NVARCHAR(100), #SERVERNAME) + ''', ''LOCAL''' PRINT #SQLQuery EXECUTE sp_executesql #SQLQuery"
)
$cred = Get-Credential
Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Database $database -Credential $cred
}
Correct-Servername | out-file -FilePath C:\Temp\correct_servername.log
This is the error i receive:
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
Invoke-Sqlcmd : Login failed for user 'domain\user'.
At C:\Temp\Rename-Create-Replication-2.ps1:20 char:2
+ Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At C:\Temp\Rename-Create-Replication-2.ps1:20 char:2
+ Invoke-Sqlcmd -Query $sqlCommand -ServerInstance $dataSource -Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Any assistance is appreciated.
Related
I'm trying to restore RDS DB using the InvokeSQL command and there is a use case to explicitly call pwsh!
The below works a gem
Invoke-Sqlcmd -Query 'exec msdb.dbo.rds_restore_database #s3_arn_to_restore_from="arn:aws:s3:::XXX/XX/XXX.bak",#restore_db_name=mydatabase' -ServerInstance XXXXX.eu-west-1.rds.amazonaws.com -Database master -Username XXX -Password XXX
But I have a problem while executing it as pwsh -command
pwsh -Command "& {Invoke-Sqlcmd -Query 'exec msdb.dbo.rds_restore_database #s3_arn_to_restore_from="arn:aws:s3:::XXX/XX/XXX.bak",#restore_db_name=mydatabase' -ServerInstance XXXXX.eu-west-1.rds.amazonaws.com -Database master -Username XXX -Password XXX}"
The error I get is a syntax issue-
pwsh : [91mInvoke-Sqlcmd: [91mIncorrect syntax near 'arn:'.
At line:1 char:1
pwsh -Command "& {Invoke-Sqlcmd -Query 'exec msdb.dbo.rds_restore_dat ...
+ CategoryInfo : NotSpecified: ([91mInvoke-Sql...x near 'arn:'. :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
I'm trying to write a powershell script to publish a theme in my on-premise installation of Dynamics CRM.
According to this page it should be really straight forward, I create an object of type PublishThemeRequest which derives from OrganizationRequest and call the method ExecuteCrmOrganizationRequest.
This is the code I'm running:
Import-Module Microsoft.Xrm.Data.Powershell
Add-PSSnapin Microsoft.Xrm.Tooling.Connector
$orgName = "<my organization name>";
$serverUrl = "http://server_url";
$Cred = Get-Credential -UserName "<my username>" -Message "Please Enter admin credentials for CRM"
$conn = Get-CrmConnection -Credential $Cred -OrganizationName $orgName -ServerUrl $serverUrl
$req = New-Object Microsoft.Crm.Sdk.Messages.PublishThemeRequest
$req.Target = New-CrmEntityReference -EntityLogicalName "theme" -Id "DB80D57A-6410-4D11-B784-0093122802AC"
$result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.ExecuteCrmOrganizationRequest($req, $null)
This is what I get when I execute the code above:
Cannot convert argument "req", with value: "Microsoft.Crm.Sdk.Messages.PublishThemeRequest", for "ExecuteCrmOrganizationRequest" to type
"Microsoft.Xrm.Sdk.OrganizationRequest": "Cannot convert the "Microsoft.Crm.Sdk.Messages.PublishThemeRequest" value of type
"Microsoft.Crm.Sdk.Messages.PublishThemeRequest" to type "Microsoft.Xrm.Sdk.OrganizationRequest"."
At C:\Users\xxxxxxxxxx\Desktop\PublishTheme.ps1:21 char:1
+ $result = [Microsoft.Crm.Sdk.Messages.PublishThemeResponse]$conn.Exec ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
I have been reading the documentation and other websites for a couple of hours now but seem to have hit a wall.
Any ideas of what my problem might be?
I'm trying to activate Windows 10 with PowerShell.
I got the following script:
$computerName = $env:COMPUTERNAME
$key = "[Windows 10 product key is in here]"
$activationService = Get-WmiObject -Query "select * from SoftwareLicensingService" -ComputerName $computerName
$activationService.InstallProductKey($key)
$activationService.RefreshLicenseStatus()
But I keep getting the following exception:
Exception calling "InstallProductKey" : ""
At F:test.ps1:4:1
+ $activationService.InstallProductKey($key)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
I just can't seem to get this right.
The syntax is correct!
I used the following to activate my notebook
$computer = gc env:computername
$key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
$service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()
Launch cmd as Administrator and run:
slmgr.vbs /ipk xxxxx-xxxxx-xxxxx-xxxxx-xxxxx
I have been able to connect to the PostgreSQL Server with OdbcConnection.
$DBConnectionString = "Driver={PostgreSQL ANSI(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
However I wish to connect to the PostgreSQL with command Invoke-Sqkcmd. I was told to always try to use the cmdlets and their commands. I tried it with:
$MyPort = '5432'
$MyUid = 'postgres'
$MyPass = 'pass'
$DBSvr = 'server'
$DBase = 'database'
$sqlcmd = 'SELECT email_addr FROM member_subscribers LIMIT 20'
$data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance $DBSvr$MyPort -Username $MyUid -Password $MyPass
Write-Output $data
However, I get the error.
Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and
that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 -
Could not open a connection to SQL Server)
At line:13 char:9
+ $data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
+ FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
Invoke-Sqlcmd :
At line:13 char:9
+ $data = Invoke-Sqlcmd -query $sqlcmd -Database $DBase -ServerInstance ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
+ FullyQualifiedErrorId : ExecutionFailureException,Microsoft.SqlServer.Management.PowerShell.GetScri
ptCommand
I know the credentials should be correct. So maybe the formatting is just wrong? I am not sure....
Invoke-SQLCmd is a SQL Server cmdlet. You can't connect to postgres using it.
I'm trying to run the code below via a script in a SQL agent job on a drive which is failing. When I logon as the service account user and run it in an ISE shell it works fine which leads me to believe it's not access related.
I tried running it as a PowerShell job step but it wouldn't work so decided to run it as a cmdexec job type and call it like this:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1"
Script
$ComputerName = "servername"
$KeyFolder = "\\servername\sharename\SSRSKEYS\"
$KeyPassword = "Password1"
$TimeStamp = Get-Date -Format "-yyyyMMdd-HHmmss"
Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer" -Class "__Namespace" -ComputerName $ComputerName |
Select-Object -ExpandProperty Name |
% {
$NameSpaceRS = $_
$InstanceName = $NameSpaceRS.SubString(3)
$KeyFileName = Join-Path -Path $KeyFolder -ChildPath ($InstanceName + $Timestamp + ".snk")
$SQLVersion = (Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)" -Class "__Namespace" - ComputerName $ComputerName).Name
$SSRSClass = Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)\$($SQLVersion)\Admin" - Query "SELECT * FROM MSReportServer_ConfigurationSetting WHERE InstanceName='$($InstanceName)'" -ComputerName $ComputerName
$Key = $SSRSClass.BackupEncryptionKey($KeyPassword)
If ($Key.HRESULT -ne 0) {
$Key.ExtendedErrors -join "`r`n" | Write-Error
} Else {
$Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length)
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length)
$Stream.Close()
}
}
Error
Executed as user: domain\svc_account. Exception calling "Create" with "2"
argument(s): "Access to the path '\\servername\sharename\SSRSKEYS\MSSQLSERVER-20150824-125254.snk' is denied." At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:24 char:13 + $Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : NotSpecified: (:) [], MethodInvocationException +
FullyQualifiedErrorId : UnauthorizedAccessException You cannot call a
method on a null-valued expression. At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:25 char:13 +
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length) +
Try passing the script path to the PowerShell.exe as a parameter using the & operator, e.g.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "& 'F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1'"
The call operator (&) allows you to execute a command, script or function.
Syntax
& "[path] command" [arguments]