I have a string in powershell, which contains a native sqlcmd command. The command itself can be executed successfully in cmd.exe. I have difficulty in executing them in powershell. Anyone can help? Thanks.
This is sql.sql
select ##servername
go
select ##servicename
This is the result when I execute the sqlcmd command from cmd.exe
C:\Users\test>sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
--------------------------------------------------
thesimpsons\INSTANCE1
(1 rows affected)
--------------------------------------------------
INSTANCE1
(1 rows affected)
C:\Users\test>
This is the powershell script to call the sqlcmd command.
$sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command $sql
When I execute this powershell script, I got the following error.
PS C:\TEMP> $sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command $sql
Invoke-Command : Parameter set cannot be resolved using the specified named parame
ters.
At line:5 char:15
+ Invoke-Command <<<< $sql
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBin
dingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands
.InvokeCommandCommand
To call a Win32 executable you want to use the call operator & like this:
& sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
You could also stop using the external 'SQLCMD.EXE' and use the Invoke-Sqlcmd cmdlet instead:
Invoke-Sqlcmd is a SQL Server cmdlet that runs scripts that contain statements from the languages (Transact-SQL and XQuery) and commands that are supported by the sqlcmd utility
Just open the 'sqlps' utility and run
Invoke-Sqlcmd -InputFile "C:\temp\sql.sql"
Please see Running SQL Server PowerShell
You can also load the SQL Server snap-ins manually in PowerShell before using 'Invoke-Sqlcmd';
for MS SQL Server 2012 you can do that by running
Import-Module SqlPs
This is how I build some externals command in my scripts
$scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
-U a `
-P a `
-i `"c:\temp\sql.sql`" }
Invoke-Command -ScriptBlock $scriptBlock
You can then use $args variable inside it and even start it remotly.
$scriptblock = {fullpath\sqlcmd -S `"(local)\instance1`" <# comment option -S #>`
-U a `
-P a `
-i `"$($args[0])`" }
Invoke-Command -ScriptBlock $scriptBlock -argumentList "c:\temp\sql.sql" -computer "remote1"
Remark :
This allow to comment each param.
Be careful not to forget a "`" and no space after them where they are at the end of the line.
Use Invoke-Expression rather than Invoke-Command
The first positional parameter of invoke-command is -scriptblock, and it expects a script block argument. To take advantage of a here-string to build the command and then run it with invoke-command, you need to convert the here-string to a script block:
$sql = #"
sqlcmd -S "(local)\instance1" -U a -P a -i "c:\temp\sql.sql"
"#
Invoke-Command ([scriptblock]::create($sql))
Both instance name and username should be fully qualified
<domain_name>\Instanc_name and <domai_name>\Username. Only your instance name is correctly scripted.
This is what worked for me for using sqlcmd from within the powershell script using the & operator, see sample to generate a csv file:
& cmd /c "sqlcmd -S $sv -i $PROCFILE -s, -v varDB = $dbclean -o $filename"
$sv has server name like SERVERNAME\INSTANCE
$PROCFILE is like d:\TSTSQL\Sqlquery.SQL
$filename is d:\TSTSQL\Desiredoutfilename.CSV
$dbclean is a parameter passed to the sql file
Related
I am trying to use PSExec:
.\PsExec.exe \\servername -u $user -p $password /accepteula cmd.exe /c "C:\Program Files\VMware\vCenter Server\bin\service-control.bat --stop --all"
But I receive the following error:
.\PsExec.exe : 'C:\Program' is not recognized as an internal or external command,
At line:1 char:1
+ .\PsExec.exe \\$vCenter -u $user -p $password /accepteula cmd.exe /c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: ('C:\Program' is...ternal command,:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
operable program or batch file.
cmd.exe exited on <Server FQDN> with error code 1.
Issue is with the String formation. You need to wrap that in the single quotes to take the effect , like:
.\PsExec.exe \\servername -u $user -p $password /accepteula cmd.exe /c '"C:\Program Files\VMware\vCenter Server\bin\service-control.bat --stop --all"'
try with
.\PsExec.exe \\servername -u $user -p $password /accepteula cmd.exe /c '"C:\Program Files\VMware\vCenter Server\bin\service-control.bat --stop --all"'
the single quotes around the cmd command should tell the powershell to take the command as a string.
I have this code:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }"
it's for download file.
When I execute it in cmd on remote server - everything is ok.
But when I want to execute this code from my computer on remote server using paexec, I have some troubles with escape characters.
Command in my CMD:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
I try to use ^ symbol, but the same error;
Code using ^ symbol for double-quotes:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command ^"& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }^""
Also, I tried to use \ (like in PHP) for escape, but have the same result.
Help with this or give advice how I can remotely download a file using the command line.
Unfortunately CMD uses different escape characters depending on what is escaped and where. There is no single one escape character that would be used everywhere.
In most cases the next character is escaped by prepending it with a caret (^), e.g. in for /f loops:
for /f "tokens=1" %%a in ('type file.txt ^| find "something"') do ...
But sometimes characters are escaped by doubling them, e.g. percent characters (%) in batch scripts:
#echo off
echo %%DATE%%=%DATE%
Sometimes you may even need need to put in other escape characters (like backslashes) because you need to escape something not for CMD, but for the command the string is being passed to:
mountvol | findstr /r \\\\
Your particular scenario shouldn't require additional quotes or escaping, though. Just run the PowerShell commandline directly, without cmd /c:
paexec.exe \\remoteServer.0.1 -u username -p password powershell -command "&{...}"
Is it possible to use powershell the complete way? If so, you could try the following:
New-PsDrive -Name X -Root \\127.0.0.1\c$ -PsProvider FileSystem -Credential (Get-Credential)
Copy-Item -Path X:\RequestedFile.txt -Destination C:\Temp
Remove-PsDrive -Name X
If your destination is a http address you could perform following actions:
Invoke-WebRequest -Uri http://some.uri -Method Get -OutFile C:\temp\myfile -Credential (Get-Credential)
Hope that helps
Instead Of this:
psexec.exe \\remoteServer.0.1 -u username -p password -dbg -lo D:\PsExec.log cmd /c "powershell -command "& { (New-Object Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file') }""
DO this:
psexec.exe \\remoteServer.0.1 -u 'username' -p 'password' powershell.exe -Command "& {(New-Object System.Net.WebClient).DownloadFile('linkToMyFile.file', 'C:\my.file')}"
This should do your work.
Hope it helps.
I am experimenting with the following script in Powershell ISE, but this returns an error when executed.
$computerName = Read-Host "Enter name of remote computer"
psexec \\"$computerName" cmd
The Read-Host part works fine, but when it moves to the psexec line it returns
Enter name of remote computer: Computer
psexec :
At line:2 char:1
+ psexec \\"$computerName" cmd
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
So it seems that the script is not passing the value of $computer. I have tried various " ' combinations to no avail.
Any help would be much appreciated, I'm rather novice at powershell scripting.
To expand on some of the other answers, a method a coworker showed me for more complex psexec strings is as follows:
#Use Psexec to Allow all remote connections and Enable PSRemoting
$psexec = "psexec -accepteula \\"+$targetIP+" -u "+$localadmin+" -p "+'"'+$str+'"'+' -h powershell.exe "&{"Set-Item wsman:localhost\client\trustedhosts -Value * -Force" ; "Enable-PSRemoting -SkipNetworkProfileCheck -Force"}"'
invoke-command -ScriptBlock {cmd /c $args[0]} -Argumentlist $psexec
While the above code actually calls psexec on the remote machine then delivers two powershell commands, the problem of authentication causes all sorts of crazy errors in PS.
Hope this helps someone or the OP.
updated:
right, I tried this, seems to work:
$computerName = Read-Host "Enter Name of computer"
$cred = Get-Credential
psexec \\$computerName -u $cred.UserName -p $cred.GetNetworkCredential().Password ipconfig 2> $null #hide errors
You don't need to quote anything. PowerShell will quote automatically if needed.
psexec \\$computerName cmd
I am using psexec to execute a .bat on a system. This will fingerprint the system and return the info back to me. The command I use is:
psexec \\server -u username -p password -s -i -c .\fingerprint.bat
This works with most of the servers, but some of them won't work with the -i switch. Is there a way to say, if this fails, try to do it again without the -i? I am using powershell to execute the script.
$servers = get-content .\input.txt
foreach($server in $servers) {
psexec \\$server -u username -p password -s -i -c .\fingerprint.bat
}
Check the $LastExitCode automatic variable. This gets set when PowerShell invokes an EXE. Whatever exit code the EXE returns gets put in $LastExitCode. I'm pretty sure psexec returns 0 for success and anything else means failure e.g.:
foreach($server in $servers) {
psexec \\$server -u username -p password -s -i -c .\fingerprint.bat
if ($LastExitCode) {
psexec \\$server -u username -p password -s -c .\fingerprint.bat
}
}
This is using a PowerShell trick where if ($LastExitCode) will if evaluate to true if $LastExitCode is anything but 0.
I try remote execute powershell script like this:
psexec -i \\host -u user -p pass PowerShell C:\tst\tst.ps1
Source code for tst.ps1:
$TempLogFilePath = "$(Get-Date -u "%Y-%m-%d")-LogFileEventLog.log"
Start-Transcript -Path "$TempLogFilePath" -Append
echo (Get-Date –f o)
Stop-Transcript
Exit 0
When a run command to remote execute this script, script locate on remote machine, in local machine in output nothing. Command running in cmd.exe. How i can get output to local console?
PsExec.exe \\host -u domain\user -p pass cmd /c "echo . | %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe C:\WINDOWS\system32\Hello.ps1"
This construction help you to run remote powershell script, but script should be locate on remote computer.
and second construction
Param(
[alias("sp")]
[string]$script_path,
[alias("u")]
[string]$user_name,
[alias("p")]
[string]$password,
[alias("h")]
[string]$host_name
)
$pass = convertto-securestring $password -asplaintext -force
$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user_name,$pass
invoke-command -credential $mycred -computername $host_name -filepath $script_path
but i don't know how i can pass args string for execute remote script with param