I have asp.net mvc application, for which database connection string is placed in Environment variable DbConn as
Min Pool Size=20;Application Name=***;**initial catalog=*****;server=***;Integrated Security=True;
Now my question is how to read this connection string using Powershell script. I know how to read the entire connection string Get-ChildItem Env:DBConn,but I need a portion of it like the initial catalog,server etc.
Please guide me in resolving this.
You could parse and tokenize the connection string with -split, Trim() and a hashtable:
$DBConnValues = #{}
$env:DBConn.Trim(";") -split ";" |ForEach-Object {
$key,$value = $_ -split "="
$DBConnValues[$key] = $value
}
Now you can access each property by name:
PS C:\> $DBConnValues["Server"]
ServerName
This would be a perfect case for ConvertFrom-StringData so that you can make it into a custom object.
$props = $env:DBConn -replace ";","`r`n" | ConvertFrom-StringData
$dbConn = New-Object -TypeName psobject -Property $props
ConvertFrom-StringData wants a string where each line is a key value pair. We get just that by replacing the semicolons with newlines. It returns a hashtable which we feed to New-object to get a custom PowerShell object. Then you can use the new object like you would any in PowerShell.
$dbConn."Min Pool Size"
Related
I am trying to save the value fetched from a properties file in my jenkins pipeline but it is not working
script {
String content = readFile("gradle.properties")
Properties properties = new Properties()
properties.load(new StringReader(content))
backupVersion = ${properties.backupUrl} // this is not working
echo backupVersion
echo "property 'version' has value '${properties.backupUrl}'"// this is working
}
I have defined backupVersion globally
You don't use dollar syntax if you directly refer to variables. Dollar syntax is only for string interpolation.
Simply write:
backupVersion = properties.backupUrl
def a = "a string"
def b = 'another'
Is there any difference? Or just like javascript to let's input ' and " easier in strings?
Single quotes are a standard java String
Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String. For example:
println 'hi'.class.name // prints java.lang.String
println "hi".class.name // prints java.lang.String
def a = 'Freewind'
println "hi $a" // prints "hi Freewind"
println "hi $a".class.name // prints org.codehaus.groovy.runtime.GStringImpl
If you try templating with single quoted strings, it doesn't do anything, so:
println 'hi $a' // prints "hi $a"
Also, the link given by julx in their answer is worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.
My understanding is that double-quoted string may contain embedded references to variables and other expressions. For example: "Hello $name", "Hello ${some-expression-here}". In this case a GString will be instantiated instead of a regular String. On the other hand single-quoted strings do not support this syntax and always result in a plain String. More on the topic here:
http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings
I know this is a very old question, but I wanted to add a caveat.
While it is correct that single (or triple single) quotes prevent interpolation in groovy, if you pass a shell command a single quoted string, the shell will perform parameter substitution, if the variable is an environment variable. Local variables or params will yield a bad substitution.
I'd like to configure a choice parameter in Jenkins.
The parameter I'd like to configure is called CIDR.
I tried using "Extended choice parameter" plugin but to no avail.
What I'm trying to do, is to let the user manually insert the chosen CIDR, considering the CIDRs which are already in use -> I want to run a groovy script to populate the string description with CIDRs which are already in use.
In order to list the already in use CIDRs, I wrote the following Groovy code:
#!/usr/local/bin/groovy
def p = ['/usr/local/bin/aws', 'ec2', 'describe-vpcs'].execute() | 'grep CidrBlock'.execute() | ['awk', '{print $2}'].execute() | ['tr', '-d', '"\\"\\|,"'].execute()
p.waitFor()
println p.text
The script runs properly in terminal:
itai#Itais-MacBook-Pro ~ - $ groovy cidrs.groovy
172.31.0.0/16
172.51.0.0/16
172.51.0.0/16
I even accepted a suspicious signature in Jenkins in-script approvals to allow the script to run.
But when I insert it to the Groovy script section of the string description and run the "build the job with parameters", the string dropdown stays empty.
What am I doing wrong?
Looks trivial issue. Try below.
Change From :
println p.text
To:
return p.text
The reason why the parameter kept being empty is that as it seems, the "Extended Choice Parameter" plugin expects the output to be an array.
Changing the script to the following code solved the issue:
#!/opt/groovy-2.4.12/bin/groovy
def p = ['/usr/bin/aws', 'ec2', 'describe-vpcs'].execute() | 'grep CidrBlock'.execute() | ['awk', '{print $2}'].execute() | ['tr', '-d', '"\\"\\|,"'].execute()
p.waitFor()
def output = []
p.text.eachLine { line ->
output << line
}
output.each {
println it
}
Now the parameter is populated with the available CIDRs.
I use powershell to invoke a sql stored procedure, now I want to redirect the complete set of the output into a .ps1 file, because the the output line is executable in powershell.
I'm trying to use >output.ps1, it works, but I'm checking the output file, it contains a lot of '...' to replace real output.
How to export the complete output? also stripe the header off?
Thanks.
It depends how you invoke the stored procedure. If you're invoking it within PowerShell, you should be able to collect the output, so I assume you're starting it as a separate task its own window. Without your actual example, here's a way to collect the output from the tasklist.exe command. You may find it applicable.
cls
$exe = 'c:\Windows\System32\tasklist.exe'
$processArgs = '/NH'
try {
Write-Host ("Launching '$exe $processArgs'")
$info = New-Object System.Diagnostics.ProcessStartInfo
$info.UseShellExecute = $false
$info.RedirectStandardError = $true
$info.RedirectStandardOutput = $true
$info.RedirectStandardInput = $true
$info.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$info.CreateNoWindow = $true
$info.ErrorDialog = $false
$info.WorkingDirectory = $workingDir
$info.Filename = $exe
$info.Arguments = $processArgs
$process = [System.Diagnostics.Process]::Start($info)
Write-Host ("Launched $($process.Id) at $(Get-Date)")
<#
$process.StandardOutput.ReadToEnd() is a synchronous read. You cannot sync read both output and error streams.
$process.BeginOutputReadLine() is an async read. You can do as many of these as you'd like.
Either way, you must finish reading before calling $process.WaitForExit()
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
#>
$output = $process.StandardOutput.ReadToEnd()
$process.WaitForExit() | Out-Null
Write-Host ("Exited at $(Get-Date)`n$output")
} catch {
Write-Host ("Failed to launch '$exe $processArgs'")
Write-Host ("Failure due to $_")
}
$output
When Using SharpSSh and the SshExec class, I can't get the RunCommand to work, it always returns an empty string. When I debug the SharpSsh library it returns -1 when it tries to read the command from a stream. It works when I use the sftp class in the same library, but that class doesn't support all the ftp commands I need.
Here is a standard example, I can't get this to produce a correct result either
SshConnectionInfo input = Util.GetInput();
SshExec exec = new SshExec(input.Host, input.User);
if(input.Pass != null) exec.Password = input.Pass;
if(input.IdentityFile != null) exec.AddIdentityFile( input.IdentityFile );
Console.Write("Connecting...");
exec.Connect();
Console.WriteLine("OK");
while(true)
{
Console.Write("Enter a command to execute ['Enter' to cancel]: ");
string command = Console.ReadLine();
if(command=="")break;
string output = exec.RunCommand(command);
Console.WriteLine(output);
}
Console.Write("Disconnecting...");
exec.Close();
Console.WriteLine("OK");
Any ideas on how I can get the RunCommand function to run some commands?
Thanks for any help :)
To get the standard output and error streams from .RunCommand,
I'll repeat the answer I posted to: SharpSSH - SSHExec, run command, and wait 5 seconds for data!
You may want to try the following overload:
SshExec exec = new SshExec("192.168.0.1", "admin", "haha");
exec.Connect();
string stdOut = null;
string stdError = null;
exec.RunCommand("interface wireless scan wlan1 duration=5", ref stdOut, ref stdError);
Console.WriteLine(stdOut);
exec.Close();
If their API does what the name implies, it should put the standard output of your command in stdOut and the standard error in stdError.
For more information about standard streams, check this out: http://en.wikipedia.org/wiki/Standard_streams