powershell command invoke-sqlcmd in batch script - windows

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:\Rpt\historical\sample1.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! ^_^

Related

Executing an EXE file using a PowerShell script with arguments for GCDS

I am new to windows and PowerShell on the admin level. I have experience in Linux and prefer using Python but I have a difficult time understanding windows environments. In bash and Linux I am used to running shell scripting with cronjobs but in Windows, I'm having an issue running this command in the Task Scheduler. I need to be able to run Google Cloud Directory Sync so that our AD is in sync with Gsuite. I wrote a batch file that works but I feel its a bit dated to use a bat file
cd C:\Program Files\Google Apps Directory Sync\
sync-cmd.exe -a -o -c config.xml
my best guess is this needs to run as a PowerShell script through task scheduler, but I don't know where to start. I found this so far but I get an error that I don't know how to interpret.
Start-Process sync-cmd.exe -ArguementList "-a -o -c C:\Somepath\config.xml"
sorry for being a noob thanks in advance!
Also for an additional resource here's the GCDS command page.
https://support.google.com/a/answer/6152425?hl=en
Your error indicates that Start-Process does not have a parameter called ArguementList. You can use Get-Help to get a list of available parameters.
Get-Help Start-Process -Parameter * | Select-Object Name
Indeed ArguementList is not available, but ArgumentList is available. There simply is a typo in your command.
The following should work just fine:
Start-Process sync-cmd.exe -ArgumentList "-a -o -c C:\Somepath\config.xml"
Option 1 - Schedule your EXE directly through Task Scheduler
No need for powershell. You can just provide the full path to the EXE and the arguments using the Windows Task Scheduler User Interface. You can specify a working folder using the Start in option.
Option 2 - Schedule a PowerShell script using Task Scheduler
I find using the -File option of PowerShell.exe very useful when scheduling a PowerShell script using Task Scheduler. In this case, I would use the cmdlet Start-Process and I would encapsulate the arguments inside the PowerShell script.
Example
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -File "c:\MyScript.ps1"
MSDN
https://learn.microsoft.com/en-us/powershell/scripting/components/console/powershell.exe-command-line-help?view=powershell-6
Syntax
PowerShell[.exe]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
[-EncodedCommand <Base64EncodedCommand>]
[-ExecutionPolicy <ExecutionPolicy>]
[-File <FilePath> [<Args>]]
[-InputFormat {Text | XML}]
[-Mta]
[-NoExit]
[-NoLogo]
[-NonInteractive]
[-NoProfile]
[-OutputFormat {Text | XML}]
[-PSConsoleFile <FilePath> | -Version <PowerShell version>]
[-Sta]
[-WindowStyle <style>]
PowerShell[.exe] -Help | -? | /?
Example from my laptop
Passing arguments through Start-Process
If you are using Start-Process then you can pass an array of arguments through a comma delimited string.
PS C:\> Start-Process -FilePath "$env:comspec" -ArgumentList "/c dir `"%systemdrive%\program files`""
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6
I discovered that PowerShell is pretty similar to python and bash with variables. This runs as a script that I then attach to Task Scheduler.
$msbuild = "C:\Program Files\Google Apps Directory Sync\sync-cmd.exe"
$arguments = "-a -o -c config.xml"
start-Process -FilePath $msbuild $arguments

How to execute Windows command (Get-Content) from PowerShell in Windows Server

My server is Windows Server. I would like to replicate the Unix tail command in Windows Server.
Unix Server: tail -f test.txt
PowerShell: Get-Content test.txt
How to execute in Windows Server?
Below command is not working:
powershell -File "Get-Content test.txt"
Error message:
Unable to execute program 'powershell -File "\"Get-Content...
Any idea?
Get-Content is not a file; it is a cmdlet. The -file parameter to Powershell.exe instructs Powershell to read the file supplied and execute the commands in it, as a script.
You can pass commands directly to Powershell by using the -command parameter; the parameter can be a quoted string, which is interpreted as a Powershell command. You would therefore want to use
powershell -command "Get-Content test.txt"
in the simplest case.
Note that Powershell.exe must be in your system path; if it is not, you would need to supply the full path to powershell, e.g.,
C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -command "Get-Content text.txt"
This question is very similar - perhaps essentially identical - to Unix tail equivalent command in Windows Powershell; I would recommend reading that question and its answers as well.
Additionally, exploring the help for Get-Content will provide useful information.
Working fine after setting full path of powershell.exe and without any quotes
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command Get-Content test.txt
Within a powershell window :
Get-Content test.txt
command returns :
hello world.
i'm inside test.txt.
bye.

How to debug hidden powershell scripts?

I'm writing a script that normally will get called by another application (VMware vCenter Server). From that application I trigger a batch file (redirect.bat) and pass a variable which is the powershell script name (TestMe.ps1).
The script is placed on a Windows Server and when I go into the command prompt of the Windows Server and call the redirect script, I see that my PowerShell script runs as expected. However when I trigger it from the app the Powershell script is not run or doesn't produce output. I have confirmation that the redirect.bat is run, because the redirect.bat writes a line in a log file.
The vCenter Server app is running under Local System account. Could it be a permissions error? Is LocalSystem allowed to run Powershell scripts?
I now have no clue if the Powershell script even starts, because it (of course) is not visible in my console when running. The batch file always returns errorlevel = 0.
Any tips on how to insert debugging info in the script that should always give output? Tips on how to troubleshoot this?
redirect.bat:
set POWERSHELL=C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -nologo -noprofile -noninteractive
SET ERRORLEVEL =
echo %1 > G:\DataStoreAlarms\Log\Redirect-batch.txt
start %POWERSHELL% -command "&"%1""
echo Error level: %ERRORLEVEL% >> G:\DataStoreAlarms\Log\Redirect-batch.txt
I call redirect.bat from the command line and from the app like this:
redirect.bat G:\DataStoreAlarms\Scripts\TestGabrie.ps1
TestGabrie.ps1:
$String = "This is a test"
$String | Out-File -FilePath "G:\DataStoreAlarms\Log\Powershell.txt" -Append
Regards
Gabrie
Problem seemed to be the START command:
start %POWERSHELL% -command "&"%1""
After changing it to this, it worked:
%POWERSHELL% -command "&"%1""
Thanks for all your help.

Powershell Write Bitlocker status to text file

I am trying to write the bitlocker status to a text file via powershell by invoking a cmd shell but it doesn't seem to work. Any ideas?
Here is what i have tried so far
#doesn't work
cmd /c manage-bde.txt>c:\bitlockerstatus.txt
# makes an empty file
$oProcess = Start-Process cmd.exe -ArgumentList "manage-bde>c:\bitlockerstatus.txt" -wait -NoNewWindow -PassThru
$oProcess.HasExited
$oProcess.ExitCode
#doesn't work
[Diagnostics.Process]::Start("cmd.exe","/c manage-bde>c:\bitlockerstatus.txt")
why don't you call the exe directly from powershell using the & operator ?
& manage-bde.exe -status > c:\temp\bl.txt

How to condense PowerShell script to fit on a single line

Quick question. I am trying to write the following PowerShell script, but I would like it to fit on a single line:
$app = New-Object -comobject Excel.Application
$wb1 = $app.Workbooks.Open("C:\xampp\upload_files\Launchpad.xlsm")
$app.Run("Refresh")
$wb1.Close($false)
$app.Quit()
The pseudo-code would look something like this:
$app = New-Object -comobject Excel.Application AND $wb1 = $app.Workbooks.Open AND "C:\xampp\upload_files\Launchpad.xlsm") AND $app.Run("Refresh") AND $wb1.Close($false) AND $app.Quit()
The reason I want to fit on a line is because I would like to insert the arguments directly in the 'arguments' box of Windows Task Scheduler. The reason for this is that for some reason scripts have been disabled (e.g. I cannot call a .ps1 file...)
I know this will still work, as I already have a "one liner" PS script running. What would the syntax look like??
Kind regards,
G.
Powershell statements can be separated with semicolons:
$app = New-Object -COM 'Excel.Application'; $wb1 = $app.Workbooks.Open("..."); ...
The PowerShell executable takes a -Command parameter that allows you to specify a command string for execution in PowerShell:
powershell.exe -Command "stmnt1; stmnt2; ..."
To run this via Task Scheduler you'd put powershell.exe into the "program" field and -Command "stmnt1; stmnt2; ..." into the "arguments" field of the task.
However, as #alroc said: you should verify why script execution has been restricted. If it's just the default setting you can simply change it by running Set-ExecutionPolicy RemoteSigned or override it by adding -ExecutionPolicy ByPass to a PowerShell command line. However, if the setting is enforced by policy changing/bypassing the setting will fail, and you could get into quite some trouble for violating company policies.
Here is a solution that you might use if the script is not that easy to convert, but you are on Windows running at least PowerShell V5.
It converts the code into Base64 and uses PowerShell.exe with the parameter -encodedCommand to pass the encodedCommand as string.
$command = Get-Content .\YourPowerShellFileContainingTheCode.ps1 -raw
# Get-Content may require "-encoding utf8" or other encodings depending on your file
$encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
Write-Output "Text for application:"
Write-Output "PowerShell.exe" ""
Write-Output "Text for argurments:"
Write-Output "-encodedCommand $encodedCommand"
It would look like this, but with a much larger command:
Text for application:
PowerShell.exe
Text for argurments:
-encodedCommand SABvACAASABvACAASABvACwAIABzAHQAYQBjAGsAbwB2AGUAcgBmAGwAbwB3AA==

Resources