Writing tabs to a file using PowerShell - syntax

I need to echo a series of elements of an array in PowerShell, but provide various delimiters between the elements, so I'm using;
Add-Content -Path $tempInputDir\testoutput.log -value ($($fields[0]) + " "+
$($fields[1]) + " " + $($fields[2]) + " " + $($fields[3]) + " "+
$($fields[15]) + " " + $($fields[17]))
}
I need to be able to add tabs and space characters, as you can see from the code above I've just done this by physically adding tabs and spaces in between double quotes, but I'm sure this will cause problems down the line.
What's the correct way to echo these characters to a file? I read somewhere that "'t" could be used, but that doesn't seem to work?

You can use `t for a tab character in a double quoted string. You can also simplify the above to:
"$($fields[0]) $($fields[1]) $($fields[2]) $($fields[3]) $($fields[15]) $($fields[17])" | Add-Content $tempInputDir\testoutput.log

To join the nominated fields together with tabs:
[string]::join("`t", (0..3,15,17 | % {$fields[$_]}))

Related

How can i use system() with rxrepl in WinCC OA?

I try to use:
string result;
string path = "C:/winccoa.projects/filters/bin/tools/rxrepl.exe";
string cmd = "'opcki' | " + path + " -s 'op' -r 'tata'";
system(cmd, result);
DebugN(result);
But in LogViewer i see nothing, instead ["tatacki"]
Why? What i doing wrong?
In PowerShell that works fine:
PS C:\> 'opcki' | C:/winccoa.projects/filters/bin/tools/rxrepl.exe -s "op" -r "tata"
tatacki
I'm assuming that WinCC's system() function targets cmd.exe, not powershell.exe (which is typical, because historically cmd.exe has been the default shell, and APIs are unlikely to change, so as to maintain backward compatibility).
Therefore, formulate your command for cmd.exe:
string cmd = "echo opcki | " + path + " -s op -r tata";
Not the use of echo to produce output and the omission of single-quoting ('...'), which cmd.exe doesn't recognize.
If embedded quoting were needed, you'd have to use `" inside "..." PowerShell strings (or use '...' PowerShell strings (whose content is taken literally) and embed " chars. as-is).

Prevent shell from escaping single quotes

Script:
#!/bin/sh -x
ARGS=""
CMD="./run_this_prog"
. . .
ARGS="-first_args '-A select[val]' "
. . .
$CMD $ARGS
I want the commandline to be expanded like this when I run this shell script:
./run_this_prog -first_args '-A select[val]'
Instead what shell does (note the added '\' before each single quote):
+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args '\''-A select[val]'\'' '
and what it ran on commandline (escaped every special char - Not what I want):
./run_this_prog -first_args \'\-A select\[val\]\'
I tried escaping single quotes like :
ARGS="-first_args \'-A select[val]\' "
But that resulted in (added '\' after each backslash):
+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args \'\''-A select[val]\'\'' '
I did my googling but couldn't find anything relevant. What am I missing here?
I am using sh-3.2 on rel6 centOS.
Once a quote is inside a string, it will not work the way you want: Inside a string quotes are not syntactic elements, they are just literal characters. This is one reason why bash offers arrays.
Replace:
#!/bin/sh -x
...
ARGS="-first_args '-A select[val]' "
$CMD $ARGS
With:
#!/bin/bash -x
...
ARGS=(-first_args '-A select[val]')
"$CMD" "${ARGS[#]}"
For a much more detailed discussion of this issue, see: "I'm trying to put a command in a variable, but the complex cases always fail!"

How can I force PostgreSQL to put my output in quotation marks?

I have the following code:
$sql = "copy(" . $sql . ") TO STDOUT CSV HEADER" ;
$cmd = "psql -h " . DATABASE_HOST . " -d " . DATABASE_NAME . " -U " . DATABASE_USER . " -c '" . $sql . ";' > " . WEBUSER_DOWNLOAD_PATH . $archivo_csv ;
I want the output to contain values inside quotes, for example "name", "age", ...,"any".
How can I do this?
Oof. Okay, first thing: this is probably a bad pattern. Consider, for example, what happens when $sql is "DELETE FROM users) TO STDOUT; COPY (SELECT * FROM profiles". Or, since you're issuing a bash command, something like "SELECT 1) TO STDOUT;" rm -rf /". Basically, this code pattern is vulnerable to SQL Injection and Shell Injection problems.
That said, the COPY command has a bunch of options nowadays. You could use something like:
COPY (query) TO STDOUT WITH (FORMAT CSV, HEADER, FORCE_QUOTE *);
I'm assuming you're using a relatively current version (9.0 or later) of postgres. If you're using an older version, you might still be okay. Starting with 8.0, there was a FORCE QUOTE option on the older syntax.

how to escape space and ampersand in same time in powershell script that execute CMD

In my Powershell script, I use "rmtshare.exe" to get information about share level permission. The "rmtshare.exe" can run perfectly under CMD environment with following command:
rmtshare.exe \\fs-sw-206\"C&C FQT"
However, when I bring it to powershell environment. I can't figure out how to escape the space and the ampersand. Here is what I have tried so far which it is not working:
$rmtShare = "C:\rmtshare.exe"
$ServerName = "fs-sw-206"
$ShareName = "C&C FQT"
Invoke-Expression ($rmtShare + " " + "\\" + $ServerName + "\" + $ShareName)
The script above will give error message from the CMD, it said "if a sharename or path contains spaces, it should be enclosed in quotes".
If I changed the last line to this:
Invoke-Expression ($rmtShare + " " + "\\" + $ServerName + "\" + "'"+'"'+"'" + $ShareName +"'"+'"'+"'")
The error message was from Powershell itself, it said "The ampersand (&) character is not allowed". NOTE: if there is no ampersand, it works. So, now I am stuck because I need to escape both characters at the same time.
Please offer your solution.
You may need to download the rmtshare.exe to test out yourself. Download site: (https://www.symantec.com/connect/downloads/remove-folder-share-remote-computer)
so, here is the code in Powershell that overcame the problem - escape space and ampersand in same time in powershell script that execute CMD
$s = " "
$q = '"'
$Verbatim = '--%'
$rmtShare = "C:\rmtshare.exe"
$ServerName = "fs-sw-206"
$ShareName = "C&C FQT"
Invoke-Expression ($rmtShare +$s+$Verbatim+$s+"\\"+$ServerName+"\"+$q+$ShareName+$q)
There should be other solutions as well. Please post if you know it.

Can't rename item in powershell because it's null

qqq.exe exists.
$DB is correct, I use it other times just fine.
$DB = Get-Content C:\Users\asd\Desktop\Farm\AccountList.txt
foreach ($x in $DB){
Rename-Item C:\Users\asd\Desktop\Farm\$x\qqq.exe $x.exe
}
Rename-Item : Cannot bind argument to parameter 'NewName' because it is null.
At C:\Users\asd\Desktop\Farm\test2.ps1:3 char:57
+ Rename-Item C:\Users\asd\Desktop\Farm\$x\qqq.exe $x.exe
+ ~~~~~~
+ CategoryInfo : InvalidData: (:) [Rename-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RenameItemCommand
When the powershell parser sees an argument starting with a $, it treats it as an expression, meaning that it will try to evaluate it as code.
Since the string $x doesn't have a property named exe, the expression results in $null and Rename-Item throws the error you see.
If you use a double-quoted string instead, the parser will stop evaluating $x after the dot:
Rename-Item C:\Users\asd\Desktop\Farm\$x\qqq.exe "$x.exe"
From Get-Help about_Parsing:
When processing a command, the Windows PowerShell parser operates
in expression mode or in argument mode:
- In expression mode, character string values must be contained in
quotation marks. Numbers not enclosed in quotation marks are treated
as numerical values (rather than as a series of characters).
- In argument mode, each value is treated as an expandable string
unless it begins with one of the following special characters: dollar
sign ($), at sign (#), single quotation mark ('), double quotation
mark ("), or an opening parenthesis (().

Resources