Powershell command invoke-sqlcmd in batch script
I have a powershell command that I want to be run in batch script. It works well in powershell window but I cannot call it properly in batch script. the powershell command goes like this:
invoke-sqlcmd -inputfile "D:\Reports\sql.sql" -ServerInstance Server1 | export-csv "D:\RawDataFiles\Raw\samp.csv" -Force -En UTF8
I hope somebody could help me out. Also, is it possible to include batch variable in replace of the file path for input and output file instead of putting the whole path in powershell command (stil run inside in batch script)?
Thanks.
I have found that works :) to run the invoke-sqlcmd within batch script:
I have use this line:
powershell -Command "& {Add-PSSnapin SqlServerCmdletSnapin100; Add-PSSnapin SqlServerProviderSnapin100; invoke-sqlcmd -inputfile '%sqlPath1%' -ServerInstance %Server% | export-csv '%out_path1%\%out1_fn%' -Force -En UTF8;}"
works like charm yay! ^_^
Similar Messages
-
How to execute SQL Script using windows powershell(using invoke-sqlcmd or any if)
OS : Windows server 2008
SQL Server : SQL Server 2012
Script: Test.sql (T-SQL) example : "select name from sys.databases"
Batch script: windows MyBatchscript.bat ( here connects to sql server using sqlcmd and output c:\Testput.txt)
(sqlcmd.exe -S DBserverName -U username -P p@ssword -i C:\test.sql -o "c:\Testoutput.txt) ---it working without any issues.....
This can execute if i double click MyBatchscript.bat file and can see the output in c:\testput.txt.
Powershell: Similarly, How can i do in powershell 2.0 or higher versions? can any one give full details with each step?
I found some of them online, but nowhere seen clear details or examples and it not executing through cmd line (or batch script).
example: invoke-sqlcmd -Servernameinstance Servername -inputfile "c:\test.sql" | out-File -filepath "c:\psOutput.txt" --(call this file name MyTest.ps1)
(The above script working if i run manually. I want to run automatic like double click (or schedule with 3rd party tool/scheduler ) in Batch file and see the output in C drive(c:\psOutput.txt))
Can anyone Powershell experts give/suggest full details/steps for this. How to proceed? Is there any configurations required to run automatic?
Thanks in advance.Testeted the following code and it's working.....thanks all.
Execute sql script using invoke-sqlcmd with batch script and without batch script.
Option1: using Import sqlps
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save Batch script as "C:\scripts\MyTest.bat" Script inside Batch script:
powershell.exe C:\scripts\mypowershell.ps1
3.Save powershell script as "C:\scripts\mypowershell.ps1"
import-module "sqlps" -DisableNameChecking
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
4.Run the Batch script commandline or double click then can able to see the output "C:\scripts\TestOutput.txt" file.
5.Connect to current scripts location cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\MyTest.bat (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".
Option2: Otherway, import sqlps and execution
1.Save sql script as "C:\scripts\Test.sql" script in side Test.sql: select name from sys.databases
2.Save powershell script as "C:\scripts\mypowershell.ps1"
# import-module "sqlps" -DisableNameChecking #...Here it not required.
invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
3.Connect to current scripts location
cd C:\scripts (enter)
C:\scripts\dir (enter )
C:\scripts\powershell.exe sqlps C:\scripts\mypowershell.ps1 (enter)
Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt". -
Hey guys. So I have this .bat file which automates the installation of SQL Server. Towards the end of the script, I'm trying to execute a powershell script which calls a SQL Scripts to install objects in our new instance(highlighted in bold below).
@echo off
pushd %0\..\
If NOT Exist C:\Temp\SQL2012 md C:\Temp\SQL2012
xcopy /E /I /H /R *.* C:\Temp\SQL2012
cd /d C:\Temp\SQL2012
If NOT Exist D: powershell -File C:\Temp\SQL2012\DiskPart.ps1
setup.exe /configurationfile=SQL2K12.ini /iacceptsqlserverlicenseterms
echo Return code: %ERRORLEVEL%
pause
powershell -File C:\Temp\SQL2012\Updates\standards.ps1
pause
popd
Problem is that when the powershell script tries to execute, it gives me an error saying that it doesn't recognize the invoke-sqlcmd. So I have another bat file which I run just to test out, and it simply calls the same powershell script, and it works.
@echo off
pushd %0\..\
powershell -File C:\Temp\SQL2012\Updates\standards.ps1
pause
popdit doesn't recognize the invoke-sqlcmd.
The command is only available when the SqlPs commandlet is loaded; see
sqlps Utility
Olaf Helper
[ Blog] [ Xing] [ MVP] -
Hi,
Im having some issue with a few powershell workflow scripts that will work in powershell ISE but they will appear to not run in a Admin powershell command prompt session.
The script is simple.
Workflow NewUser
Param (
[Parameter(Mandatory=$True)]
[string] $givenname,
[Parameter(Mandatory=$True)]
[string] $surname,
[Parameter(Mandatory=$True)]
[string] $template
"Param1 = $givenname"
"Param2 = $surname"
"Param3 = $template"
The saved file name is NewUser.ps1.
When I run .\NewUser.ps1 -givenname test -surname test -template test
Nothing happens. In Powershell ISE, it outputs
Param1 = test
Param2 = test
Template = test
I can run .\NewUser.ps1 skdjfsdkfjsdkfjsdkfj in powershell command
and nothing happens.
I notice this behavior with a number of scripts that I get working with ISE and they dont work in powershell command prompt.
We are using Powershell 4.0
Thanks LanceWhen I run
Set-psdebug -step
then newuser.ps1 -givename test -surname test -template test
it gets to the line workflow newuser and quits
am I missing some dependency?
Running [System.Threading.Thread]::GetDomain().GetAssemblies() in powershell commmand returns the following.
GAC Version Location
True v4.0.30319 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.ConsoleHost\v4.0_3.0.0.0__31bf...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.C...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Numerics\v4.0_4.0.0.0__b77a5c561934e089\Syst...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xm...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices\v4.0_4.0.0.0__b03f5f7f11d5...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management\v4.0_4.0.0.0__b03f5f7f11d50a3a\Sy...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Management.Infrastructure\v4.0_1.0.0.0__3...
False v4.0.30319
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration.Install\v4.0_4.0.0.0__b03f5f7f...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\Sy...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Security\v4.0_3.0.0.0__31bf385...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Activities\v4.0_3.0.0.0__31bf3...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\Sy...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Workflow.ServiceCore\v4.0_3.0....
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities.Presentation\v4.0_4.0.0.0__31bf38...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e3...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsB...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\PresentationCore\v4.0_4.0.0.0__31bf3856ad364e35\Prese...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml\v4.0_4.0.0.0__b77a5c561934e089\System.X...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Core.Activities\v4.0_3.0.0.0__...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Diagnostics.Activities\v4.0_3....
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Management.Activities\v4.0_3.0...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Security.Activities\v4.0_3.0.0...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Utility.Activities\v4.0_3.0.0....
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.WSMan.Management.Activities\v4.0_3.0.0.0_...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf385...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Dat...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Utility\v4.0_3.0.0.0_...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\Syst...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Mic...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Management\v4.0_3.0.0...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Dynamic\v4.0_4.0.0.0__b03f5f7f11d50a3a\Syste...
and for the ISE it returns this
GAC Version Location
True v4.0.30319 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll
False v4.0.30319 C:\Windows\System32\WindowsPowerShell\v1.0\powershell_ise.exe
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.ISECommon\v4.0_3.0.0.0__31bf3856ad364e35\Mic...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Window...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\Syste...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.GPowerShell\v4.0_3.0.0.0__31bf3856ad364e35\M...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ComponentModel.Composition\v4.0_4.0.0.0__b77a5c561934e089\...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Editor\v4.0_3.0.0.0__31bf3856ad364e35\Micros...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework\v4.0_4.0.0.0__31bf3856ad364e35\Presentation...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\PresentationCore\v4.0_4.0.0.0__31bf3856ad364e35\PresentationCore.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml\v4.0_4.0.0.0__b77a5c561934e089\System.Xaml.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Config...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\Syste...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\UIAutomationProvider\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationP...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll
False v4.0.30319
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.DirectoryServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Di...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Managemen...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.Management.Infrastructure\v4.0_1.0.0.0__31bf3856ad364e3...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Numerics\v4.0_4.0.0.0__b77a5c561934e089\System.Numerics.dll
False v4.0.30319
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework.AeroLite\v4.0_4.0.0.0__31bf3856ad364e35\Pre...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\UIAutomationTypes\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationType...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemXml\v4.0_4.0.0.0__b77a5c561934e089\Pr...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration.Install\v4.0_4.0.0.0__b03f5f7f11d50a3a\Syste...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transacti...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Security\v4.0_3.0.0.0__31bf3856ad364e35\Micr...
False v4.0.30319
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.GraphicalHost\v4.0_3.0.0.0__31bf3856ad364e35...
False v4.0.30319
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemCore\v4.0_4.0.0.0__b77a5c561934e089\P...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_64\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Utility\v4.0_3.0.0.0__31bf3856ad364...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemData\v4.0_4.0.0.0__b77a5c561934e089\P...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Management\v4.0_3.0.0.0__31bf3856ad...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceProcess\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Servi...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Activities\v4.0_3.0.0.0__31bf3856ad364e35\Mi...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.Activitie...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Workflow.ServiceCore\v4.0_3.0.0.0__31bf3856a...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Activities.Presentation\v4.0_4.0.0.0__31bf3856ad364e35\Sys...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Core.Activities\v4.0_3.0.0.0__31bf3856ad364e...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Diagnostics.Activities\v4.0_3.0.0.0__31bf385...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Management.Activities\v4.0_3.0.0.0__31bf3856...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Security.Activities\v4.0_3.0.0.0__31bf3856ad...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.PowerShell.Utility.Activities\v4.0_3.0.0.0__31bf3856ad3...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.WSMan.Management.Activities\v4.0_3.0.0.0__31bf3856ad364...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf3856ad364e35\S...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\Syst...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\PresentationFramework-SystemXmlLinq\v4.0_4.0.0.0__b77a5c561934e08...
True v4.0.30319 C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Dynamic\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Dynamic.dll
Thanks Lance -
OS Command batch script issue (FTP)
All,
I am running into a problem (i think it's simple) which I just can't seem to figure out. I have a FTP command which is in a batch script and I can run it manually (Its run in an old enviroment with Informatica) and the ftp script works just fine. When I use the OS Command to launch the bat file, it accesses the bat file but in the ftp log all I see it doing is copying the local directory into the first line of the log and then just copying the rest of the ftp script. It does nothing else!!
Does anyone have any ideas? I have copied the script and forced it into one bat file, tried running it from a local directory, running it from the server, combining everything into a single source for lcd and script, I am running out of ideas!!
- Another point is that I have to use this process as I am moving files from a server to a mainframe environment and need the ascii translate function in FTP.
Thanks,
AbhiUpdate:
After some searching (and soul searching;) ) I was able to find a way to call the FTP file through an shell batch. So for instance I have a shell script that calls the FTP script. This seems to work but now the log does not create correctly (the ftp script is creating the log) it seems to copy the script from the ftp file and paste it in the log file. -
How do I write a command in a .batch file written in NOTEPAD to run a powershell command?
Example:
powershell -Command "& {Update-Help;}"
would this be a correct command to put in a .batch file to update help information in powershell.
All I want to know is how to write a windows powershell command in a .batch file.
Multi-Commands
Single-Commands
Charles WrightHi,
You can separate multiple commands with a semicolon (;).
Don't retire TechNet! -
(Don't give up yet - 13,085+ strong and growing) -
Batch script to open multiple excel and doc files
Hi Everyone,
Could anybody please provide a batch script to open multiple excel and doc files at a time.
Appreciate ur quick response.
Regards,You have several scripting choices within Windows. At a basic level you've got "batch files" - which run a series of command interpreter commands, and have a file extension of .BAT or .CMD. If you just wanted to open a list of Word documents, then assuming that the path to Word is correct (something like this below) you could list these in a file with a .BAT extension and run this (e.g. double click on it):
"C:\Program Files\Microsoft Office\Office\Winword.exe" "C:\Documents and Settings\All Users\Desktop\File1.DOC"
"C:\Program Files\Microsoft Office\Office\Winword.exe" "C:\Documents and Settings\All Users\Desktop\File2.DOC"
"C:\Program Files\Microsoft Office\Office\Winword.exe" "C:\Documents and Settings\All Users\Desktop\File3.DOC"
"C:\Program Files\Microsoft Office\Office\Excel.exe" "C:\Documents and Settings\All Users\Desktop\File1.XLS"
"C:\Program Files\Microsoft Office\Office\Excel.exe" "C:\Documents and Settings\All Users\Desktop\File2.XLS"
Another script language is VBScript, which was the example I gave. VBScript is available on most Windows platforms and can be run from a command prompt or within Windows. If you save the text I gave you above to a file with a .VBS extension you can double-click to run it (Windows) or open a command prompt and type CSCRIPT MyVBScript.VBS (assuming that's the name of the your .VBS file).
Other script languages are available to achieve the same thing, including Powershell, however you'd need to have Powershell available on your PC. -
Batch Script using System Varriable for Hostname and FQDN results in large space between
I have a batch script running on Windows 7 that I've created to help a physical computer, connect to his virtual cousin. Problem is when I try to make
it use the FQDN (required by the View Client) it puts a large space between the hostname and the domain.
Result
ECHO Connecting View Client to PREFIX-SERIAL .domain.comOR"C:\Program Files\VmWare\View.exe" -Args -serverURL PREFIX-SERIAL .domain.com
Our computers are named a combination of a prefix and the serial number. Our virtual computer names are the same, but with a different prefix. So my attempt was to make a connection
script, using the computer serial number. My Process:
Setting %serial% variable.
for /F "skip=1 tokens=*" %%b in ('wmic bios get serialnumber') do if not defined serial set serial=%%b
Set %hostname% variable.
set hostname=PREFIX-%serial%
Installation command line
"C:\Program Files\VmWare\View.exe" -Args -serverURL %hostname%.domain.com
That results in the output at the beginning of my post.
I've also tried
%hostname%.%userdomain%.com
PREFIX-%serial%.%userdomain%.com
PREFIX-%serial%.domain.com
SET FQDN=.domain.com
PREFIX-%serial%%FQDN%
%hostname%%FQDN%
I also tried carets and quotes on set commands without any improvement.
I'm sure I'm missing something simple here. Any advise?
There's no place like 127.0.0.1Will something like this get you what you are looking for?
(gwmi win32_bios).SerialNumber+(gwmi WIN32_ComputerSystem).Domain
Or
$hostname=(gwmi win32_bios).SerialNumber+"."+(gwmi WIN32_ComputerSystem).Domain
Sorry just realized your looking to do this in a Batch file...so maybe something like this
@echo off
for /F "skip=1 delims=" %%j in ('powershell "[System.Net.Dns]::GetHostByName((hostname)).HostName"') do (
set Host=%%j
goto :DONE
:DONE
echo %HOST% -
Create SQL Job with Invoke-Sqlcmd
I'm trying to run a set of .sql files, i didn't know how to pass a common variable to all, so i've started running the statements directly in ps. One of these creates a job but i'm running into all of the errors due to the special characters and the
variables, can someone help?
$Client = "C0212"
$Instance = "SQL03\"+$Client
$sqlscript3 = "
--NEED TO CHANGE THE LOG LOCATION BELOW
USE [msdb]
GO
/****** Object: Job [DatabaseBackup - USER_DATABASES - FULL] Script Date: 11/15/2013 8:40:20 AM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object: JobCategory [Database Maintenance] Script Date: 11/15/2013 8:40:20 AM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N''Database Maintenance'' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N''JOB'', @type=N''LOCAL'', @name=N''Database Maintenance''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N''DatabaseBackup - USER_DATABASES - FULL'',
@enabled=1,
@notify_level_eventlog=2,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N''Source: http://ola.hallengren.com'',
@category_name=N''Database Maintenance'',
@owner_login_name=N''sa'', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object: Step [DatabaseBackup - USER_DATABASES - FULL] Script Date: 11/15/2013 8:40:20 AM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N''DatabaseBackup - USER_DATABASES - FULL'',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N''CmdExec'',
@command=N''sqlcmd -E -S `$(ESCAPE_SQUOTE(SRVR)) -d DBA -Q `"EXECUTE [dbo].[DatabaseBackup] @Databases = ''''USER_DATABASES'''', @Directory = N''''T:\SQLsafe Backups\SQL Native Backup'''', @BackupType = ''''FULL'''',
@Verify = ''''Y'''', @CleanupTime = 170, @CheckSum = ''''Y'''', @LogToTable = ''''Y''''`" -b'',
--NEED TO CHANGE THE LOG LOCATION BELOW
@output_file_name=N''C:\Program Files\Microsoft SQL Server\MSSQL11.$Client\MSSQL\LOG\DatabaseBackup_`$(ESCAPE_SQUOTE(JOBID))_`$(ESCAPE_SQUOTE(STEPID))_`$(ESCAPE_SQUOTE(STRTDT))_`$(ESCAPE_SQUOTE(STRTTM)).txt'',
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N''Saturday 4am'',
@enabled=1,
@freq_type=8,
@freq_interval=64,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20131109,
@active_end_date=99991231,
@active_start_time=40000,
@active_end_time=235959,
@schedule_uid=N''5b3c3fcf-28dc-4f4c-95ce-a624667ee378''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N''(local)''
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
GO"
Invoke-Sqlcmd –ServerInstance $Instance –Database msdb –Query $sqlscript3 -QueryTimeout 300So, if I try this:
$Client = "C0212"
Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable $Client
and in my .sql file that line that contains the variable looks like this:
@output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.`$(Client)\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
I get the error:
Invoke-Sqlcmd : The format used to define the new variable for Invoke-Sqlcmd cmdlet is invalid. Please use the 'var=value' format for defining a new variable.
If i try like this:
Set @Client = "C0212"
Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable @Client
Line in .sql file like this:
@output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.@Client\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
I get the error: Set-Variable : A positional parameter cannot be found that accepts argument '2'. -
PowerShell command returned an exception. Unexpected token 's' in expression or statement
Hi All,
I am trying to Creating a VM based on a Template in VMM through Orchestrator Runbook using below URL;
http://blogs.catapultsystems.com/lrayl/archive/2013/07/03/orchestrator-system-center-integrations-part-3-creating-a-vm-based-on-a-template-in-vmm.aspx
Runbook:
But at the Create VM from Template activity runbook will failed:
Throwing below error in while running runbook in Error Summary text:
PowerShell command returned an exception. Unexpected token 's' in expression or statement.
Exception: InvalidOperationException
Target site: PSRunspaceInvoker.HandleInvokeException
Stack trace:
at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSRunspaceInvoker.HandleInvokeException(Exception ex, ILogger logger)
at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSRunspaceInvoker.Invoke(RunspaceInvoke runspace, String script, ILogger logger)
at Microsoft.SystemCenter.Orchestrator.Integration.PowerShellConnector.PSScriptRunner.Execute(String script)
at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012Domain.VM.CloneFromTemplate(String vmmServer, ParameterList inputParameters)
at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012QIK.VM.CloneFromTemplate.DoExecute(IActivityRequest request, ILogger logger)
at Microsoft.SystemCenter.Orchestrator.Integration.VMM2012QIK.ActivityBase`2.Execute(IActivityRequest request, IActivityResponse response)
Both Orchestrator & SCVMM powershell are set on Unrestricted powershell.
Kindly suggest any solution or work around for resolution.
Thanks Rahul$This may be a bit late and perhaps not even relevant but I came across this post when trying to solve an issue I had with a powershell script in Orchestrator. Maybe it will help you, or maybe it will help someone else.
I was trying to create a connector between SCOM and our ticketing system. I wanted to export alert descriptions and in the process of testing I came across an alert description that had multiple lines and all kinds of crazy formatting. When I tried to assign
the Published Data to a varialbe in my powershell script i would get an error "Unexpected token [a partial alert description] in expression or statement.". After looking at the actual alert description data and seeing that i was only getting some of it
and not all of it it dawned on me that i somehow needed to escape out of all the crazy quoting, carriage returns, and special characters. to do that i assigned the Published Data to a variable in my powershell script as follows:
$Description = @"
{Description from "Get Alert"}
Apparently the @" "@ is called a here-string. Somewhat interesting. Hope it helps you or someone else! -
Invoke-sqlcmd with domain user name and password
I am trying to execute below small SQL script from powershell by passing my domain user name and password..but it is throwing an error login failed for the user.
Howerver I am able to execute the same query by passing normal user 'non domain' and password. The issue is only when i am trying to connect with domain username.
Can you please suggest if there is any way to execute below query with domain user..
Invoke-Sqlcmd
-query "select name from master.sys.databases"
-ServerInstance "CM-NCKM-DBTST04\SQL2012" -username "sos\9venk" -password "xxxx"
Thanks
Venkat
venkatHi Venkat,
Agree with Mike, to connect sql via powershell, you can refer to this article about authentications:
Connecting to SQL Server through Powershell
Please try to gather credentials using Get-Credential, and then use New-PSSession -Authentication CredSSP to open the pssession.
A similar discussion about this issue is for your reference:
Invoke-SQLCmd with Different Credential
If there is anything else regarding this issue, please feel free to post back.
Best Regards,
Anna Wang
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected] -
Output format depends on hower PowerShell is invoked?
Hi,
I am currently developing a script to collect information about the software installed on client computers which is based on Jaap Brasser's Get-RemoteProgram.ps1 (https://gallery.technet.microsoft.com/scriptcenter/Get-RemoteProgram-Get-list-de9fd2b4). Depending
on how I invoke the script, the format of the output is different...
When I start PowerShell (on Windows Server 2012 in case it matters) and issue the command
.\Get-RemoteProgram.ps1 | out-file result.txt -encoding Default
the column containing the program name is 100 characters wide. However, if I am running the command from the shell like
Powershell -command ".\Get-RemoteProgram.ps1 | Out-File result.txt -encoding Default; exit"
that column is just 66 characters wide so that several program names are truncated.
Why is that, and how can I avoid it? Excuse me if that is a trivial question but I am not an experienced PowerShell guy...
Thanks, Georg.Hi,
Take a look at this:
http://poshoholic.com/2010/11/11/powershell-quick-tip-creating-wide-tables-with-powershell/
Don't retire TechNet! -
(Don't give up yet - 13,225+ strong and growing) -
Remotely executing an invoke-sqlcmd fails
When remotely executing an invoke-sqlcmd fails. A simple query such as:
Invoke-Command -ComputerName ComputerName -ScriptBlock{
$qry = "SELECT SERVERPROPERTY('ServerName') AS ServerName,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('Edition') AS Edition,
SERVERPROPERTY('EngineEdition') AS EngineEdition;"
Invoke-Sqlcmd -Query $qry} -ConfigurationName SQLSession
I get the following error:
[ComputerName] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (http://sche
mas.microsoft.com/powershell/SQLSession) was not found in the WS-Management catalog. The catalog contains the metadata that describes resources, or logical endpoints. For
more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
I have run Enable-WSManCredSSP Server on the SQL server and tried to run Enable-WSManCredSSP -Role Client -DelegatedCredentials * on a Windows 7 x32 workstation but I get the following error:
Enable-WSManCredSSP : A parameter cannot be found that matches parameter name 'DelegatedCredentials'.
At line:1 char:55
+ Enable-WSManCredSSP -Role Client -DelegatedCredentials <<<< *
+ CategoryInfo : InvalidArgument: (:) [Enable-WSManCredSSP], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.WSMan.Management.EnableWSManCredSSPCommand
I have tried the Enable-WSManCredSSP with the actual server name instead of a wildcard and it still fails.Hi,
As cmille replied, for the command, there is no DeletegatedCredentials parameter, more details about the command:
Enable-WSManCredSSP
http://technet.microsoft.com/en-us/library/hh849872(v=wps.620).aspx
Did you use Server Core? Please below link to troubleshoot this issue:
the ws-management service cannot process the request
http://social.technet.microsoft.com/Forums/windowsserver/en-US/27020cf2-47fc-43e3-b135-e68b80a1bb4e/the-wsmanagement-service-cannot-process-the-request?forum=winservercore
Regards,
Yan Li
Regards, Yan Li -
Executing DPM Powershell Commands
Hi All,
I am trying to execute DPM 2012 Powershell commands from a console application in c#, but at the time of Invoke it is giving me the following error.
{"Could not load file or assembly 'ACM, Version=1.0.523.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.":"ACM, Version=1.0.523.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"}
Below is my code.
var runspace = PShell.GetRunSpace();
if (runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("$installPath = (Get-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Microsoft Data Protection Manager\\Setup\" \"UIInstallPath\").UIInstallPath");
pipeline.Commands.AddScript("$dpmModuleFullPath = $installPath + \"Modules\\DataProtectionManager\\DataProtectionManager.psd1\"");
pipeline.Commands.AddScript("Import-Module $dpmModuleFullPath");
pipeline.Commands.AddScript("$pg=get-protectiongroup -dpmserver dpm-2012-01");
pipeline.Commands.AddScript("$pg");
try
System.Collections.ObjectModel.Collection<PSObject> result = pipeline.Invoke();
foreach (PSObject obj in result)
var name = obj.Properties["FriendlyName"].Name;
catch (Exception e)
ilyasHi All,
I am trying to execute DPM 2012 Powershell commands from a console application in c#, but at the time of Invoke it is giving me the following error.
{"Could not load file or assembly 'ACM, Version=1.0.523.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.":"ACM, Version=1.0.523.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"}
Below is my code.
var runspace = PShell.GetRunSpace();
if (runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen)
runspace.Open();
var pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("$installPath = (Get-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Microsoft Data Protection Manager\\Setup\" \"UIInstallPath\").UIInstallPath");
pipeline.Commands.AddScript("$dpmModuleFullPath = $installPath + \"Modules\\DataProtectionManager\\DataProtectionManager.psd1\"");
pipeline.Commands.AddScript("Import-Module $dpmModuleFullPath");
pipeline.Commands.AddScript("$pg=get-protectiongroup -dpmserver dpm-2012-01");
pipeline.Commands.AddScript("$pg");
try
System.Collections.ObjectModel.Collection<PSObject> result = pipeline.Invoke();
foreach (PSObject obj in result)
var name = obj.Properties["FriendlyName"].Name;
catch (Exception e)
ilyas
I have the very same issue, only I am running the script from within PowerGui (www.powergui.org). Was a resolution ever found for this issue?
http://blog.aggregatedIntelligence.com/ -
Windows 8.1 Batch Scripts for devcon.exe
HiI'm using batch script with devcon.exe for cleaning usb ghost devices. On XP and Win 7 it works perfect but on windows 8.1 only if i manualy paste commands on "administrator command line" but it wont start from my batch script. Is there any solution for windows 8 to enable security rule for batch script? Win 8 is so annoying for any type of scripts even gpo. At the moment im trying to resolve this problem with PowerShell.This is how script looks like:
Text@echo offDEVCON Find * | FIND /I /V "matching device(s)" > "%Temp%\DevconFind.txt"FOR /F "tokens=1 delims=: " %%A IN ('DEVCON FindAll * ^| FIND /I /V "matching device(s)"') DO (TYPE "%Temp%\DevconFind.txt" | FIND "%%~A" >NULIF ERRORLEVEL 1 %Debug% DEVCON Remove "@%%~A")DEL "%Temp%\DevconFind.txt"
Regards
This topic first appeared in the Spiceworks CommunityUninstall it. Reboot. Then install. Reboot.
All of this should be done as Run as Administrator or it will fail.
16GIG or Larger usb flash drive is required. 8 gigs is too small.
http://www.dell.com/support/home/us/en/19/Drivers/DriversDetails?driverId=8HY96
Maybe you are looking for
-
Fluid grid for Wordpress: insert PHP code into DW or DW code into Wordpress?
This may be a stupid question but it's a dilemma for me. Here's the problem. I want to create a mobile first, fluid grid Wordpress website in Dreamweaver CS6 based on an existing Wordpress theme. I can see two ways of doing that: 1) Create a fluid gr
-
HT204053 how do I change my apple ID username in the app store?
On my iphone, how do I change the apple ID that naturally pops up when I try to update my apps?
-
After configuring SSL, cannot run Report Manager but ReportServer works fine
I'm using SSRS 2014 as part of SQL Server 2014 Express. I've configured both the Web Service URL and the Report Manager URL to use a Certificate and only allow port 443 traffic. I did this by removing the port 80 identity and adding an SSL Identity.
-
Hi, I have created the system Sap_webdynpro_Xss in the EP and but when i acced to EP ESS i get this error: While processing the current request, an exception occured which could not be handled by the application or the framework. If the information c
-
How can one develop on Windows?
Hi! Short and simple here: I'd like to be able to work on my laptop - which is not a mac. What are my options? Thanks, Alex