Montag, 19. Februar 2018

PowerShell script cannot be loaded due to policy settings

Problem

You have a PowerShell script that does not run and trying to do so calling it from command line or bat script it gives you something like below meaning what is described in the title.
Die Datei "C:\Users\kellnert\Documents\bin\svn_updates.ps1" kann nicht geladen werden, da die Ausführung von Skripts
auf diesem System deaktiviert ist. Weitere Informationen finden Sie unter "about_Execution_Policies" unter
"http://go.microsoft.com/fwlink/?LinkID=135170".
    + CategoryInfo          : Sicherheitsfehler: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess

Solution

Call PowerShell with following option.
-ExecutionPolicy RemoteSigned
It makes Windows require only remote PowerShell scripts being signed. What a nonsense invention of M$ if it so easily wrapped away. The total call could look like below.
powershell -ExecutionPolicy RemoteSigned -File "%~dp0%~n0.ps1"

Montag, 12. Dezember 2016

Determine the current text encoding of your Windows

$Enc = [System.Text.Encoding]::Default
Write-Host "Encoding name: " $Enc.EncodingName
Write-Host "=================================================="
Write-Host "Code page:     " $Enc.CodePage
Write-Host "Web name:      " $Enc.WebName
Write-Host "Header name:   " $Enc.HeaderName " (destined for e-mail applications)"
Write-Host "Body name:     " $Enc.BodyName " (destined for e-mail applications)"
Write-Host

Batch equivalent to: $(dirname ${0})/$(basename ${0} .<old_suffix>)<new_suffix>

Actually it is not PowerShell but useful in bat scripts starting PowerShell scripts.
%~dp0%~n0.ps1
If you want to use it in the previous post, you cannot put it in a variable first if the result contains space characters. For some obscure reason. Not connected with this fomula.

Dienstag, 18. Oktober 2016

P:\My : The term 'P:\My' is not recognized as the name of a cmdlet,...

Error

Calling following gives the below error message.
powershell P:\My Roaming Documents\create_db_patch_deployment_package.ps1
P:\My : The term 'P:\My' is not recognized as the name of a cmdlet,...

Solution

Use call
powershell -File "P:\My Roaming Documents\create_db_patch_deployment_package.ps1"

module '%~dp0' could not be loaded

Error

Calling following gives the below error message. %~dp0 on the Windows command prompt is the equivalent of the bash dirname $0
powershell %~dp0\create_db_patch_deployment_package.ps1
%~dp0\create_db_patch_deployment_package.ps1 : The module '%~dp0' could not be loaded. For more information, run 'Import-Module %~dp0'.

Solution

Use call
powershell -File "%~dp0\create_db_patch_deployment_package.ps1"

Montag, 17. Oktober 2016

Write files without byte order mark (BOM)

If you use Out-File with -Encoding utf8 you invariably get a file where the first three bytes mark the byte order. This can break the further processing of the file, e. g. SQL+ is incapable to cope with it... why does Oracle support UTF-8 anyway ;-).
To get arround this, you can use [System.IO.File]::WriteAllLines with the proper encoding, e.g.
$UTF8NoBomEncoding = New-Object System.Text.UTF8Encoding(
      $False,
      $True)
[System.IO.File]::WriteAllLines(
      $outputFilePath,
      $array,
      $UTF8NoBomEncoding)

Montag, 26. September 2016

Equivalent to grep being used in a pipe

Select-String (official documentation)

To search files recursively: Get-ChildItem -Path "path" | Select-String -Pattern "to look for" -CaseSensitive (official documentation of Get-ChildItem)

@ => Unrecognized token in source text.

Error

At P:\My Roaming Documents\west-3325\west_3325.ps1:12 char:48
+ $Result=sqlplus SDM_DATA/SDM_DATA_DEV@D52PMDWH @ west_3325.sql
+                                                ~
Unrecognized token in source text.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnrecognizedToken

Problem

@ is a special character in PowerShell:
 @(...)                 Force an expression to be evaluated as an array

Solution

Use a tic to escape it:
$Result=sqlplus SDM_DATA/SDM_DATA_DEV@D52PMDWH `@ west_3325.sql

Donnerstag, 19. Mai 2016

Create user interface dynamically, where users can select from a choice

$patchNames = ("P1", "P2", "P3")  # You probably want to create that dynamically. This seems to be the whole point.
$patchIndex = -1
$patchOptions = @()
foreach ($patchName in $patchNames) {
      $patchIndex++
      $patchOptions += New-Object `
         System.Management.Automation.Host.ChoiceDescription `
         "${patchName}"
}
$options = [System.Management.Automation.Host.ChoiceDescription[]]$patchOptions
$patchIndex = $host.ui.PromptForChoice(
   "Patch-Auswahl",
   "Bitte den Patch anhand des Namens auswählen (z. B. Copy-Paste). " + `
   "Vorausgewählt ist der jüngste, der mit einfachem Enter-Drücken " + `
   "ausgewählt wird",
   $options,
   0
)
$patchName = $patchNames[${patchIndex}]

Zip files and directories

Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$zipFilePath = `
   $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
         "${scriptDirPath}\..\software-lieferung\${patchName}.zip"
   )
if (Test-Path -path "${zipFilePath}") {
      Write-Debug("Removing ${zipFilePath}")
      Remove-Item -path "${zipFilePath}" -force
}
[System.IO.Compression.ZipFile]::CreateFromDirectory(
      "${tmpPatchDirPath}",
      "${zipFilePath}",
      $compressionLevel,
      $False
)

Donnerstag, 28. Januar 2016

Command output is an array of lines

If you need to have it as a single string, -join "`n" the output or pipe the output through Out-String.

Mittwoch, 27. Januar 2016

Problem

You need to replace a string containing double $$ using regular expression by a string containing a double $, e. g. original string $$Reusable_only_switch= replacement string $$Reusable_only_switch=true.

Solution

Put the $$ in a group and make the group part of the replacement string, e. g. regular expression ^(\$\$Reusable_only_switch=)\s*$ replacement expression $1true.

Shortcoming

If the double $ needs to end up at a different position, for the time being I do not see other solution but to take several steps.

Mittwoch, 20. Januar 2016

Create empty zip file

if (
       -not (
            Test-Path `
                -Path $pathAbsoluteArchiveFile `
                -PathType Leaf
       )
 ) {
       Set-Content -Path $pathAbsoluteArchiveFile (
             "PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
 }