Read var directly from csv - variables

Is it possible to read a variable directly by loading a csv?
My csv looks like this:
Var,Path
$SrcHost,\\computer
Is there a possibility to import-csv and put the path into the var?

import-csv test3.csv | foreach-object {
iex "$($_.var) = ""$($_.path)"""
}

You can also use new-variable (nv):
import-csv csvfile.csv | % { nv -name ($_.var) -value ($_.path) }
However to make this work you have to:
remove the $ from the source csv
or, trim $ as described by the comments below
or, select your variable as ${$srchost}

How bout this:
Get-Content -Path test.csv | Select-Object -Skip 1 | ForEach-Object { $_.Replace(",", "=`"") +
"`"" } | Invoke-Expression

Related

Script to replace string of text at a end of a line

I would like to modify this script if possible:
((Get-Content -path "C:\Users\User1\OUT\Summary.txt" -Raw) -replace '</ab></cb>','</x>') | Set-Content -Path "C:\Users\User1\OUT\Summary.txt"
I would like a script that will run with Windows OS to search through one file it finds at this path:
C:\Users\User1\File\Summary.txt
And within that file, when it finds data starting with: <a><b>Data
And at the same time ending with: </ab></cb>
It would need to change the ending to: </x>
And it would need to save the file without changing the name of the file.
For instance a line showing this data:
<a><b>Data:</y> 12345678</ab></cb>
Would be changed to:
<a><b>Data:</y> 12345678</x>
The PowerShell script above will find all instances of </ab></cb> and replace it with </x>, which is not what I am hoping to accomplish.
You can use Get-Content to process the file line be line and only do the Replace when you have a Match on <a><b>. Something like this:
$InFile = ".\TestIn.txt"
$OutFile = ".\TestOut.txt"
If (Test-Path -Path $OutFile) {Remove-Item $OutFile}
Get-Content $InFile | ForEach-Object -Process {
$NewLine = $_
If ($_ -Match '<a><b>') {
$NewLine = ($_ -Replace '</ab></cb>','</x>')
}
Add-Content $OutFile $NewLine
}

Import CSV using PowerShell: date conversion

I'm importing CSV files to the MS SQL, and in different CSV files I have different date types. My code:
## Input Variables
$csvPath = "F:\Test\table.csv"
$csvDelimiter = ";"
$serverName = "name"
$databaseName = "dbname"
$tableSchema = "dbo"
$tableName = "dates"
$encoding = "windows-1251"
Import-Csv -Path $csvPath -encoding $encoding -Delimiter $csvDelimiter | Write-SqlTableData -ServerInstance $serverName -DatabaseName $databaseName -SchemaName $tableSchema -TableName $tableName -Force
And, for example, dates in my CSVs are like:
12JAN2021:18:03:41.000000
The problem here is that month written by the letters
or
17.04.2021
The problem here is that SQL read this like "mm.dd.yyyy" but it's "dd.mm.yyyy"
How can I improve my code so it can automatically read date correctly and write it to my date or datetime field in the destination table?
Thanks so much!
update CSV example:
product;product_id;product_nm;dttm
220;text;some text;12JAN2021:18:03:41.000000
220;text;some text;1JAN2021:18:03:41.000000
564;text;some text;16JAN2021:18:03:41.000000
I don't believe there is an "automated way" of parsing your CSVs if they all have a different DateTime format. I believe you would need to inspect each file to see if the format is valid (cast [datetime] directly to the string) or if they have a format that needs to be parsed.
In example, both provided dates on your question, need to be parsed and can be parsed with [datetime]::ParseExact(..):
[datetime]::ParseExact(
'12JAN2021:18:03:41.000000',
'ddMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
[datetime]::ParseExact(
'17.04.2021',
'dd.MM.yyyy',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
If you need help "updating" the DateTime column from your CSV you would need to provide more details on that.
In example, the CSV provided in the question can be updated as follows:
# Here you would use this instead:
# $csv = Import-Csv path/to/csv.csv -Delimiter ';'
$csv = #'
product;product_id;product_nm;dttm
220;text;some text;12JAN2021:18:03:41.000000
220;text;some text;1JAN2021:18:03:41.000000
564;text;some text;16JAN2021:18:03:41.000000
'# | ConvertFrom-Csv -Delimiter ';'
foreach($line in $csv)
{
$line.dttm = [datetime]::ParseExact(
$line.dttm,
'dMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
}
Now if we inspect the CSV it would look like this:
PS /> $csv | Format-Table
product product_id product_nm dttm
------- ---------- ---------- ----
220 text some text 01.12.2021
220 text some text 01.01.2021
564 text some text 01.16.2021
And all the process in pipeline would look as follows:
Import-Csv -Path $csvPath -Encoding $encoding -Delimiter $csvDelimiter |
ForEach-Object {
$_.dttm = [datetime]::ParseExact(
$_.dttm,
'dMMMyyyy:HH:mm:ss.ffffff',
[cultureinfo]::InvariantCulture
).ToString('MM.dd.yyyy')
$_
} | Write-SqlTableData.....

Extract values into variables from filename in Powershell

I have a Powershell script to read .sql files from a specific folder and run them against a database depending on the name of the filename.
The filenames are always the same: myDatabase.script.SomeRandomCharacters.csv
There can be many files which is why the script has a foreach loop.
[CmdletBinding()]
param (
[parameter(Mandatory = $true)][ValidateSet('dev')][String]$serverName,
[parameter(Mandatory = $true)][String]$databaseName,
)
$dir = Split-Path $MyInvocation.MyCommand.Path
$scripts = Get-ChildItem $dir | Where-Object { $_.Extension -eq ".sql" } | Where-Object { $_.Name -like "$databaseName*" }
foreach ($s in $scripts) {
$script = $s.FullName
Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -InputFile $script
}
The issue here is that if I would have 2 databases "myDatabase" and "myDatabase2", running the script with the former input would run the latter as well since the Where-Object filtering uses an asterisk.
I can't figure out how to modify the script so that I get the absolute value of whatever is before the first fullstop in the filename. What I would also what to do is to validate the value between the first and second fullstops, in the example filename it is script.
Any help is appreciated!
Use the database names to construct a regex pattern that will match either:
param(
[Parameter(Mandatory = $true)][ValidateSet('dev')][String]$ServerName,
[Parameter(Mandatory = $true)][String[]]$DatabaseNames,
)
# Construct alternation pattern like `db1|db2|db3`
$dbNamesEscaped = #($DatabaseNames |ForEach-Object {
[regex]::Escape($_)
}) -join '|'
# Construct pattern with `^` (start-of-string anchor)
$dbNamePattern = '^{0}' -f $dbNamesEscaped
# Fetch scripts associated with either of the database names
$scripts = Get-ChildItem $dir | Where-Object { $_.Extension -eq ".sql" -and $_.Name -match $dbNamePattern }
# ...
You can use the StartsWith function to fix your filter:
$scripts = Get-ChildItem $dir | Where-Object { $_.Extension -eq ".sql" } | Where-Object { $_.Name.StartsWith("$($databaseName).") }

Get variable from tenant in Octopus

Is there any way to get a variable from tenant in Octopus server?
I already extracting variable from projects, using code below, but this method is not working for tenants:
Import-Module "C:\Program Files\WindowsPowerShell\Modules\Octopus-Cmdlets\0.4.4\Octopus-Cmdlets.psd1"
connect-octoserver http://octohost.cloudapp.azure.com:8082 API-12345678901234567890
$raw = (Get-OctoVariable someproject somevariable | Where-Object { $_.Environment -eq "DEV" } )
$jsonfile = "c:\dataapi.json"
$raw.Value | ConvertFrom-Json | ConvertTo-Json | Out-File $jsonfile -Encoding UTF8
$data = Get-Content $jsonfile -Encoding UTF8 | ConvertFrom-Json
$data | ConvertTo-Json | Set-Content $jsonfile -Encoding UTF8
There is at least the following way to get a variable from a tenant in Octopus Deploy. I got this working with making OctopusClient.dll calls.
Add-Type -Path $OctopusClientDll #this should point to the dll
$Endpoint = New-Object Octopus.Client.OctopusServerEndpoint $octopusURI, $apiKey
$Repository = New-Object Octopus.Client.OctopusRepository $Endpoint
$TenantEditor = $Repository.Tenants.CreateOrModify($TenantName)
$Vars = $TenantEditor.Variables.Instance.LibraryVariables
$VarSet = $Vars[$COMMON_TENANT_VARSET_ID] # you need to know this
$VarTemplate = $VarSet.Templates | Where-Object -Property Name -eq "Tenant.VariableName"
$VariableValue = $VarSet.Variables[$varTemplate.Id].Value

How do I concatenate strings with variables in PowerShell?

I'm trying to build a file path in PowerShell and the string concatenation seems to be a little funky.
I have a list of folders:
c:\code\MyProj1
c:\code\MyProj2
I want to get the path to a DLL file here:
c:\code\MyProj1\bin\debug\MyProj1.dll
c:\code\MyProj2\bin\debug\MyProj2.dll
Here's what I'm trying to do:
$buildconfig = "Debug"
Get-ChildItem c:\code | % {
Write-Host $_.FullName + "\" + $buildconfig + "\" + $_ + ".dll"
}
This doesn't work. How can I fix it?
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config is not a valid variable name.
$.FullName should be $_.FullName
$ should be $_.Name
You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.
Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}
(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)
Try the Join-Path cmdlet:
Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
Join-Path -Path $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)"
}
This will get all dll files and filter ones that match a regex of your directory structure.
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'}
If you just want the path, not the object you can add | select fullname to the end like this:
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'} | select fullname