PowerShell v5 UTF8 format lost after conversion CR LF to LF - vba

I'm using a vba macro to write a PS1 script in order to :
first convert my txt file to UTF8 format
Second, convert CR LF to LF.
But when I do so, i'm loosing the UTF8 format.
Here is my code :
$file = 'C:\Users\c92434\Downloads\run_param_21_04_21\dg_poc_parameter.txt'
(Get-Content $file) | Out-File -Encoding UTF8 $file
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
Best regards,
Jouvzer

You can do this in one go:
$file = 'C:\Users\c92434\Downloads\run_param_21_04_21\dg_poc_parameter.txt'
(Get-Content -Path $file -Raw) -replace '\r?\n', "`n" | Set-Content -Path $file -NoNewline -Encoding UTF8
The -Raw switch on Get-Content reads the file as one single, multilined string.
The -replace '\r?\n', "`n" replaces all CRLF into LF

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
}

powershell not exporting

hi i am running the following query in powershell:
Import-Module Hall.psm1
$Database = 'Report'
$Server = '192.168.1.2'
$Query = 'SELECT all * FROM [Report].[dbo].[TestView]'
$LogLocation = "\\Report\LogFile.csv"
$DynamicYear = (Get-Date).Year
$DynamicMonth = (Get-Culture).DateTimeFormat.GetMonthName((Get-Date).Month)
$FileDestination = "\\Report\MONTHLY REPORTS\"+$DynamicYear+"\"+$DynamicMonth+"\"
$Outputfilename='TestView-'+(Get-Date).ToString('MM-dd-yyyy')+'.csv'
$LocalCreate = 'C:\Scripts\LocalCreate\'
$FolderPathExtension = "Microsoft.PowerShell.Core\FileSystem::"
$CodeDestination = $FolderPathExtension+$FileDestination
$filedest=$LocalCreate+$outputfilename
$Logfile = $FolderPathExtension+$LogLocation
Invoke-sqlcmd -querytimeout 120 -query "
$Query
" -database $database -serverinstance $server |
ConvertTo-Csv -NoTypeInformation | # Convert to CSV string data without the type metadata
Select-Object -Skip 0 | # Trim header row, leaving only data columns
% {$_ -replace '"',''} | # Remove all quote marks
Set-Content -Path $filedest
(gc $filedest) | ? {$_.trim() -ne "" } | set-content $filedest
if(Test-Path ($filedest)) {
Move-Item -Path $filedest -Destination $CodeDestination -Force
$LogType = 'INFO'
$LogEntry = "$filedest MovedTo $To"
Write-Log -Message $LogEntry -Level $LogType -Logfile $Logfile
}
which works fine without any issue if the query has data.
however, if the query does not have any data it does not create a .csv. how can i get it to create a blank .csv? or .csv with headers only?
Use New-Item -ItemType File -Path $filedest before your Invoke-SqlCmd Or ConvertTo-Csv

Import-Csv Offset rows

I'm Importing multiple CSV files into a SQL database.
What switches or additional functions can I use to skip the first 5 rows on the import?
Ive tried using Get-Content file.csv | Select -skip 5 | ConvertFrom-Csv -Header Name
but not sure how to add it to my code
$srcDir = "C:\PowerShell\Files"
Write-Output $srcDir
$files = Get-ChildItem $srcDir -Name -Attributes !Directory
foreach ($file in $files) {
echo $file
$filePath = $srcDir + '\' + $file
$delimiter = ','
$addTableName = $file -replace ".csv",""
$writeTableName = '"' + $addTableName + '"'
$dt = Import-Csv $filePath -Delimiter $delimiter | Out-DataTable
Write-Output $writeTableName
## Write-Output $dt.Columns
## Write-Output $dt.Columns
Add-SqlTable -ServerInstance "11.22.33.444\MSSQL" -Database "STAGE" -TableName $addTableName -DataTable $dt
Write-DataTable -ServerInstance "11.22.33.444\MSSQL" -Database "STAGE" -TableName $writeTableName -Data $dt
}

[ character in powershell

I'm using Powershell for replace a string in a text file.
For replace String 1 to String 2 in file.txt I use
(Get-Content file.ps1) | Foreach-Object { $_ -replace 'String 1', 'String 2'} | Set-Content file.txt
It works pretty well even with for replace characters like - and #
It need to replace a string with the [ character but it doesn't work. I need to replace -state [VMstate]::stopped with -state stopped but it doesn't work with
(Get-Content TEMP_config.ps1) | Foreach-Object { $_ -replace '-state [VMstate]::stopped', '-state stopped'} | Set-Content TEMP_config.ps1
How can i find the [ char?
The replace operator uses regular expressions to match text. One way to search for literal text is to escape the search text:
$search = [regex]::escape('[MyText]')
(Get-Content file.ps1) | Foreach-Object { $_ -replace $search , 'String 2'} | Set-Content file.txt
You just have to escape the [:
$_ -replace '-state \[VMstate]::stopped', '-state stopped'
Or use [Regex]::escape if you are not sure what to escape
You can use "\[" instead of "[" (prefixed with a backslash) to escape the [ character

Read var directly from csv

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