Powershell -Command InvokeSqlcmd + Incorrect Synatx error - powershell

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

Related

Method invocation error when using PSCredential in Powershell

I will start by saying that I have successfully tested this script when running locally on my laptop against a remote dev server.
However, when I have migrated the script to our TFS server, I am now encountering the below (sanitized) error message.
2019-06-10T18:46:05.8256626Z Generating script.
2019-06-10T18:46:05.8257313Z Formatted command: . 'E:\***.ps1' -username "***" -password "***" -servername "***" -ScriptPath "***" -SourcePath "***" -DestinationPath "***" -CleanupFlag "***"
2019-06-10T18:46:06.0290179Z ##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'E:\***.ps1'"
2019-06-10T18:46:06.7520864Z Method invocation failed because [System.Management.Automation.PSCredential] does not contain a method named 'new'.
2019-06-10T18:46:06.7521292Z At E:\***.ps1:5 char:1
2019-06-10T18:46:06.7521480Z + $CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
2019-06-10T18:46:06.7523016Z + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2019-06-10T18:46:06.7523588Z + CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
2019-06-10T18:46:06.7524614Z + FullyQualifiedErrorId : MethodNotFound
2019-06-10T18:46:06.7525361Z
2019-06-10T18:46:06.8602349Z ##[error]PowerShell exited with code '1'.
The script is attempting to Invoke-Command (to run a different script) on a remote system. It appears to be messing up at the section where it creates a credential from the username and encrypted password.
This is the code that I'm attempting to execute:
param($username, $password, $servername, $ScriptPath, $SourcePath, $DestinationPath, $CleanupFlag)
$PWsec = ConvertTo-SecureString -String $password -AsPlainText -Force
$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
Invoke-Command -ComputerName $servername -Credential $CredentialSec -FilePath $ScriptPath -ArgumentList $SourcePath, $DestinationPath, $CleanupFlag
Per mcclayton's suggestion in the comments... because the new server is running an older version of Powershell, it worked when I changed from this format:
$CredentialSec = [System.Management.Automation.PSCredential]::new($username,$PWsec)
To this format:
$CredentialSec = New-Object System.Management.Automation.PSCredential($username,$PWsec)

Credential Parameter not working for Invoke-sqlcmd

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.

Executing PsExec64.exe from Poweshell throwing "Cannot process the XML from the 'Error' stream"

From my PowerShell script I am executing PSExec64.exe with below parameters.
$CommandToExecute = "& >\PsExec64.exe -accepteula -nobanner -s powershell -Command {Another_Power_Shell_Script Arguments_To_Script}"
Invoke-Expression -Command:$CommandToExecute
After this I am getting below error in log file:
PsExec64.exe : Cannot process the XML from the 'Error' stream of
'<<Script_Path>>\PsExec64.exe': Data at the root level is invalid.
Line 1, position 830. At line:1 char:1
+ & <<Script_Path>>\PsExec64.exe -accepteula -nobanner -s powershell -Command { ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SyntaxError: (<<Script_Path>>\PsExec64.exe:String) [], XmlException
+ FullyQualifiedErrorId : ProcessStreamReader_CliXmlError
Any inputs?

Escape space and resolve variable in Jenkins powershell script not working

I tried different ways to escape the space in "Program Files" but this is not working. I receive the following error in Jenkins after this part is executed:
powershell.exe : FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call At
C:\web\JenkinsMaster\workspace\XXX#tmp\durable-d3011838\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (FileStream was ... 'lpt1:', call :String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.
CategoryInfo : OpenError: (:) [Out-File], NotSupportedException
FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
PSComputerName : XXXXX
powershell script: '''
$pass = ConvertTo-SecureString -AsPlainText "XXXX" -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "XXXX",$pass
$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ComputerName XXXXXXXX -UseSSL -Credential $cred -SessionOption $sessionOption
Copy-Item $env:WORKSPACE\\* -Destination "C:\\data\\install\\" -Filter *TEST* -Recurse -Force -Verbose -ToSession $session
$filename = $env:JOB_NAME + "_" + $env:BUILD_DISPLAY_NAME + "_wwwroot.7z"
Invoke-Command -Session $session -ScriptBlock {cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL}
Remove-PSSession $session
Exit-PSSession
'''
If I change the Invoke-Command to the following, the Program Files directory seems to be resolved correctly, but then the variable $filename is not resolved anymore.
Invoke-Command -Session $session -ScriptBlock {cmd /c \'"C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$filename -oC:\\data\\install\\test -aoa >NUL'}
powershell.exe : NotSpecified: (:String) [], RemoteException At
C:\web\Jenkins\workspace\XXX#tmp\durable-53dbead2\powershellWrapper.ps1:5
char:3
+ & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (NotSpecified: (...RemoteException:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
CategoryInfo : NotSpecified: (:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
PSComputerName : XXXXX
ERROR: The system cannot find the file specified.
C:\Data\Install\$filename
System ERROR:
The system cannot find the file specified.
Hopefully you can assist me in this case! The rest of the commands is working fine.
Thanks!
The 7z.exe path in your first command has an extraneous trailing \, which causes problems:
cmd /c "C:\\Program Files\\7-Zip\\7z.exe\\" # <- trailing \\ shouldn't be there
In your 2nd command, you're using single quotes around the command passed to cmd /c ('...'), but the contents of '...' strings in PowerShell are treated as literals, which explains why $fileName was not expanded (interpolated);
only double-quoted ("...") strings and, within limits, unquoted command arguments are expanded in PowerShell; e.g., compare the output from Write-Output '$HOME' to the output from Write-Output "$HOME" / Write-Output $HOME.
As iRon mentions, there's no need to involve cmd at all - PowerShell is perfectly capable of executing command-line programs directly, so this should work:
Invoke-Command -Session $session -ScriptBlock { & "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\$using:filename -oC:\\data\\install\\test -aoa >$null }
Due to invoking 7z.exe directly, now there's no outer quoting needed anymore, and $fileName should be expanded.
Note, however, that $fileName was replaced with $using:fileName, which is necessary in order for the target session to know about the local $fileName variable - see Get-Help about_Remote_Variables.
Since the 7z.exe file path is quoted (of necessity, due to containing spaces), you must use &, the call operator, to invoke it.
Since the > redirection is now performed by PowerShell itself, the cmd-style >NUL output suppression was replaced with its PowerShell analog, >$null.
I wonder if it necessarily at all to invoke a CMD shell for this.
I guess it would be simpler to directly invoke the 7z.exe with its parameters.
Nevertheless, you can build you own script block like this:
[ScriptBlock]::Create('cmd /c "C:\\Program Files\\7-Zip\\7z.exe" x C:\\Data\\Install\\' + $filename + ' -oC:\\data\\install\\test -aoa >NUL')

Why is psexec getting stuck after showing the eula?

I am trying to run the following command on one of my servers.
$dotnetFrameworkInstalled = psexec -accepteula \\server1 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' 'Import-Module ServerManager;
$feature = Get-WindowsFeature -ErrorAction Stop | Where-Object { $_.Name -eq ''NET-Framework'' };
Write-Output $feature.Installed'
It looks like this is getting stuck after showing the following in the output window.
psexec :
At C:\temp\Untitled1.ps1:2 char:30
+ $dotnetFrameworkInstalled = psexec -accepteula \\server1 'C:\Windows\Syst ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PsExec v1.98 - Execute processes remotely
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com
But the same command is working with another server (server2).
what is psexec ?
I think just some argument parse issue. please turn to use Start-Process
Start-Process -FilePath "psexec" -ArgumentList "-accepteula ...."