Executing sql file with sqlplus in windows 10 powershell - powershell

I have created a .bat file to export csv file regulary through windows task scheduling which works fine.
But not working when I switch to Powershell. It returns (both in ISE and right click .ps1 "Run with Powershell") with:
SQL*Plus: Release 19.0.0.0.0 - Production on Sun May 2 14:05:52 2021
Version 19.10.0.0.0
Copyright (c) 1982, 2020, Oracle. All rights reserved.
ERROR: ORA-12154: TNS:could not resolve the connect identifier specified
So.I'm not sure what I'm doing wrong. The variable input are dummies.
In my .bat contains:
SET NLS_LANG=.AL32UTF8
SET hostIp="123.123.1.12"
SET username="user1"
SET password="pass1"
SET port="1521"
SET service="myDBname"
SET sqlPath="C:\My script\TEST_EXPORT.sql"
sqlplus %username%/%password%#%hostIp%:%port%/%service% #"%sqlPath%"
In my .ps1 contains:
cls
$hostIp="123.123.1.12"
$username="user1"
$password="pass1"
$port="1521"
$service="myDBname"
$sqlPath="C:\My script\TEST_EXPORT.sql"
echo "$username/$password#$hostIp`:$port/$service #$sqlPath"
sqlplus "$username/$password#$hostIp`:$port/$service #$sqlPath"

Try using composite formatting to build the parameter string. The upside is that one can build the string and not to worry about quotation issues. Note that there is no need to escape the colon `: in the string, as it is not interpreted as scope operator.
# A variable that contains double quote
$quote = '"'
$("{0}/{1}#{2}:{3}/{4} #{5}{6}{5}" -f $username, $password, $hostIp, $port, $service, $quote, $sqlPath,$quote)
user1/pass1#123.123.1.12:1521/myDBname #"C:\My script\TEST_EXPORT.sql"
Another an alternative for building complex strings is string interpolation. Here are three versions that contain different techniques to include double-quotes. The same works in composite fomatting too.
# Double-doublequote version. I'd avoid this, as multiple double quotes are hard to read
"${username}/${password}#{$hostIp}:${port}/${service} #""${sqlPath}"""
user1/pass1#{123.123.1.12}:1521/myDBname #"C:\My script\TEST_EXPORT.sql"
# Backtick-escape version
"${username}/${password}#{$hostIp}:${port}/${service} #`"${sqlPath}`""
user1/pass1#{123.123.1.12}:1521/myDBname #"C:\My script\TEST_EXPORT.sql"
# Quote in a variable version
"${username}/${password}#{$hostIp}:${port}/${service} #${quote}${sqlPath}${quote}"
user1/pass1#{123.123.1.12}:1521/myDBname #"C:\My script\TEST_EXPORT.sql"

Related

How to pass multiple arguments to dotCover merge

I am writing powershell command to merge two snapshots as following -
&$coveragTool merge /Source= $TestResult1;$TestResult2 /Output= TestMergeOutput.dcvr
it is giving error as -
Parameter 'Source' has invalid value.
Invalid volume separator char ':' (0x3A) in path at index 67.
where as the document says two files should be separated by a semicolon(;)
like this -
merge: Merge several coverage snapshots
usage: dotCover merge|m <parameters>
Valid parameters:
--Source=ARG : (Required) List of snapshots separated with semicolon (;)
--Output=ARG : (Required) File name for the merged snapshot
--TempDir=ARG : (Optional) Directory for the auxiliary files. Set to system temp by default
Global parameters:
--LogFile=ARG : (Optional) Enables logging and allows specifying a log file name
--UseEnvVarsInPaths=ARG : (Optional) [True|False] Allows using environment variables (for example, %TEMP%) in paths. True
by default
how do i make it correct?
You cannot pass an unquoted ; as part of an argument, because PowerShell interprets it as a statement separator.
Either enclose the argument in "...", or `-escape the ; character selectively; also, the space after = may or may not be a problem.
To make the call (at least syntactically) succeed, use the following:
& $coveragTool merge /Source="$TestResult1;$TestResult2" /Output=TestMergeOutput.dcvr
Alternatively (note the `, ignore the broken syntax highlighting):
& $coveragTool merge /Source=$TestResult1`;$TestResult2 /Output=TestMergeOutput.dcvr
PowerShell has more so-called metacharacters than cmd.exe, for instance, notably ( ) , { } ; # $ # in addition to & | < > - see this answer for additional information.

Use special character in custom VSTS PowerShell script task

I am currently facing the problem that I would like to set the Copyright of my AssemblyInfo dynamically during the VSTS build to something like this:
© 2012-2018 Company Name
but the 2018 should be set dynamically representing the current year.
Therefor I tried to set a global build variable to something like this:
© 2012-$(Date:yyyy) Company Name
Here the copyright special character works fine but the date does not work at this place so the next thing I tried was to make a custom PowerShell script build task with an inline script.
I set again my global variable ("Copyright") this time to
-set during build-
and in the inline script I tried to replace the value like this:
$date=$(Get-Date -Format yyyy);
$_Copyright = "© 2012-$date Company Name";
Write-Host "##vso[task.setvariable variable=Copyright]$_Copyright";
Now I got my dynamic date working but on my shipped dlls I get
"c 2012-2018 Company Name"
with a 'c' instead of the '©'.
So I replaced it with [char]0x00A9:
$date=$(Get-Date -Format yyyy);
$_Copyright = [char]0x00A9 + " 2012-$date Company Name";
Write-Host "##vso[task.setvariable variable=Copyright]$_Copyright";
But nothing changes in the result:
"c 2012-2018 Company Name"
Although on my local machine my PowerShell gives me for [char]0x00A9 the '©' sign.
Any suggestions?
I can reproduce this issue.
Seems the logging command cannot recognize the symbol ©. So we cannot set the variable which including the © as the value by below command:
Write-Host "##vso[task.setvariable variable=Copyright]$_Copyright"
In your scenario you can try below workarounds:
1, Using Copyright (c) instead of Copyright ©, the logging command can recognize the string (c):
$date=$(Get-Date -Format yyyy);
$_Copyright = "(c) 2012-$date Company Name";
Write-Host "##vso[task.setvariable variable=Copyright]$_Copyright";
2, Combine variables:
1) Set a global build variable e.g.: $(Symbol) and set © as the value
2) Set a date variable using logging command :
$date=$(Get-Date -Format yyyy);
$Company= "2012-$date Company Name";
Write-Host "##vso[task.setvariable variable=Company]$Company";
3) Use the variable $(Symbol)$(Company) together to get the entire Copyright string.
Alternately you can directly use ©$(Company) to check if that works.

Detecting error after a powershell statement is executed

I am using powershell to run sqlplus and I would like PowerShell to detect if there are error after the script was run and to perform some action instead of me looking at the result file.
& 'sqlplus' 'system/myOraclePassword' '#Test' | out-file 'result.txt';
Normally in DOS, there is %errorlevel% when the command encounters error and I wonder if there is similar stuff in PowerShell?
Of course, I can read the log file myself but sometimes, thing got too routine and I may forget.
My Test.sql:
select level from dual
connect by level<5;
select 10/0 from dual;
quit;
There is clearly a division by zero error. The result.txt captures it but I would like powershell to detect it as well
SQL*Plus: Release 12.1.0.2.0 Production on Thu Apr 27 16:24:30 2017
Copyright (c) 1982, 2014, Oracle. All rights reserved.
Last Successful login time: Thu Apr 27 2017 16:17:34 -04:00
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
LEVEL
----------
1
2
3
4
select 10/0 from dual
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
Does the powershell statement return an errorlevel after the statement is executed like DOS?
I have tried:
& 'sqlplus' 'system/myOraclePassword' '#Test' | out-file 'result.txt';
if (errorlevel 1)
{ write-host error;
}
else
{ write-host ok;
}
But that has caused syntax error?
errorlevel : The term 'errorlevel' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and
try again.
What is a proper way to check error in powershell?
UPDATE
I used this:
if ($LASTEXITCODE -ne 0 )
{
write-host error;
}
else
{
write-host ok;
}
Since you are invoking an executable, you probably want to check for the $LASTEXITCODE variable or the return value of sqlplus. In PowerShell each variable has a $ prefix.

Install4j varfile doesnt' read few variables

Installer is installed typically using GUI or console, we need unattended installation capability as well. Running the installer like this (in Linux):
myapp -q -c -varfile myfile.var
Installer installs the software successfully. Problem is it ignores some variables (not all variables). It doesn't read values for zServerPort$Long and zShutdownPort$Long variables and instead applies the default values configured in application.
Varfile is provided below
#install4j response file for Sw 4.6
#Mon Aug 11 19:55:46 PDT 2014
sys.adminRights$Boolean=true
choiceIsLicenseSelected=true
zDBUserName=user
zLaunchDesktopPostInstall$Boolean=false
zDBPassWord=password
sys.languageId=en
sys.installationDir=/opt/mydir
zServerPort$Long=85
zLicenseFilePath=/home/mydir/Desktop/license.lic
zMysqlPath=/usr/bin/mysql
zMysqlCnf=/etc/mysql/my.cnf
zDbPort$Long=3306
choiceInstallDir=/opt/mydir
zShutdownPort$Long=8015
zServerPort, zShutdownPort, choiceInstallDir, zMysqlPath are all installer variables. Reordering the variables didn't work either. Is the problem due to data type being Long ?
Is there a way to pass the values of these two variables zServerPort, zShutdownPort in some other way ?
Other idea am thinking is whether if the installer can know that it is being run in unattended mode and read these variables from command line ?
Most likely, the defaults are applied with a code snippet and not through the initial values of form components.
In those code snippets (i.e. in a "Run script" action"), you have to check whether the value is already defined or not. For example:
if (context.getVariable("variableName") != null) {
context.setVariable("variableName"), 100L);
}

Use AppCmd to LIST CONFIG in APPHOST only

I have a requirement to use powershell to configure IIS7.5 on WebApplications that have not yet had code deployed (possibly at all, possibly old/broken web.configs exist) to the file system. I would like to be able to do this all at the APPHOST level. (Note at the bottom about use of Powershell > AppCmd).
I can SET all the values properly, however, being somewhat diligent, I like to also validate the values were set properly by retrieving them after setting.
Here's the scenario:
I can set this value using AppCmd so the setting is applied at the APPHOST level using the /Commit:APPHOST flag. However, I havent found a way to READ the values exclusively at the APPHOST level.
Setting the Code is successful:
C:\Windows\System32\inetsrv\appcmd.exe set config "webSiteName/webAppName" -section:system.webServer/security/authentication/anonymousAuthentication /enabled:"True" /commit:apphost
However, I cant find a way to read the values using AppCmd (or Powershell):
Running the following AppCmd returns an error due to the broken pre-existing web.config in the folder (the specific error is unimportant, as it is reading the WebApp's web.config instead of the ApplicationHost.config/APPHOST):
C:\Windows\System32\inetsrv\appcmd.exe list config "MACHINE/WEBROOT/APPHOST/webSiteName/webAppName" -section:system.webServer/security/authentication/anonymousAuthentication
ERROR ( message:Configuration error
Filename: \\?\c:\inetpub\wwwroot\webSiteName\webAppName\web.config
Line Number: 254
Description: The configuration section 'system.runtime.caching' cannot be read because it is missing a section declaration
. )
Note: I would prefer to do this all in Powershell instead of using AppCmd, so if anyone has the syntax for modifying the APPHOST settings for anonymousAuthentication section of a WebApplication, that lives under a Website, from inside Powershell (Get-WebConfiguration seems to only use the WebApp web.config), that would be totally awesome and much appreciated!
Here's how to do this in PowerShell:
[Reflection.Assembly]::Load(
"Microsoft.Web.Administration, Version=7.0.0.0,
Culture=Neutral, PublicKeyToken=31bf3856ad364e35") > $null
$serverManager = New-Object Microsoft.Web.Administration.ServerManager
$config = $serverManager.GetApplicationHostConfiguration()
$anonymousAuthenticationSection = $config.GetSection("system.webServer/security/authentication/anonymousAuthentication", "simpleasp.net")
Write-Host "Current value: " $anonymousAuthenticationSection["enabled"]
# Now set new value
$anonymousAuthenticationSection["enabled"] = $true
$serverManager.CommitChanges()