开发者

Windows Batch File - Need to remove line breaks from parameter

开发者 https://www.devze.com 2023-02-22 02:40 出处:网络
I have a powershell script that will run a query and export the results to Excel.I want to hook this into SQL Studio Management Studio (2008)\'s external tools.SSMS will not allow powershell scripts s

I have a powershell script that will run a query and export the results to Excel. I want to hook this into SQL Studio Management Studio (2008)'s external tools. SSMS will not allow powershell scripts so I am using a batch file to get it started.

In the external tools section you can specify some predefined arguments. The argument that I want is called "current text". This argument passes whatever is highlighted to the tool (batch file). My batch file then passes that argumen开发者_开发技巧t on to a powershell script.

The problem is that if the user has a query that spans multiple lines highlighted then the powershell script fails because of the linebreaks. It seems it would be relatively easy to strip them out, or better yet, replace them with a space?

Here is my batch file:

echo %~1
call powershell ^& 'c:\temp\ExportSQL.ps1' -query "%~1"

My question is how can I replace newlines and carriage returns from %1 with a space before passing it to the powershell script? TIA.


First, I can't believe that you have really linefeeds in your parameter %1, as it is possible, but a bit complex to achieve this.
To control this you could use

echo on
rem # %1 #

To handle CR and linefeed characters you have to use the delayed expansion, as percent expansion of such a content is not possible.
With percent expansion CR's are always removed, linefeeds removes the rest of the line or in a block context they append a new command line.

So it's not possible to handle content with linefeeds in a parameter like %1 ..%9.
You need it stored in a variable.

Assuming you have content with newlines in a variable, you could replace it with spaces.
The empty lines in this example are important for the result.

@echo off
set text=This contains a ^

newline
setlocal EnableDelayedExpansion
set ^"result=!text:^

= !"
echo Content of text is   "!text!"
echo ----
echo Content of result is "!result!"

--- Output ---

Content of text is   "This contains a
newline"
----
Content of result is "This contains a  newline"
0

精彩评论

暂无评论...
验证码 换一张
取 消