Powershell is failing with named instance in connection string - shell

function Get-Type {
param($type)
$types = #( 'System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal',
'System.Double', 'System.Guid', 'System.Int16', 'System.Int32',
'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32',
'System.UInt64')
if ( $types -contains $type )
{
Write-Output "$type"
}
else
{
Write-Output 'System.String'
}
}
function Out-DataTable {
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
if ($property.value)
{
if ($property.value -isnot [System.DBNull])
{
$Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)")
}
}
$DT.Columns.Add($Col)
}
if ($property.IsArray)
{
$DR.Item($property.Name) =$property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1
}
else
{
$DR.Item($property.Name) = $property.value
}
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output #(,($dt))
}
}
try
{
add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0,
Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch
{add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try
{add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0,
Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch
{add-type -AssemblyName "Microsoft.SqlServer.Smo"
}
function Get-SqlType
{
param([string]$TypeName)
switch ($TypeName)
{
'Boolean' {[Data.SqlDbType]::Bit}
'Byte[]' {[Data.SqlDbType]::VarBinary}
'Byte' {[Data.SQLDbType]::VarBinary}
'Datetime' {[Data.SQLDbType]::DateTime}
'Decimal' {[Data.SqlDbType]::Decimal}
'Double' {[Data.SqlDbType]::Float}
'Guid' {[Data.SqlDbType]::UniqueIdentifier}
'Int16' {[Data.SQLDbType]::SmallInt}
'Int32' {[Data.SQLDbType]::Int}
'Int64' {[Data.SqlDbType]::BigInt}
'UInt16' {[Data.SQLDbType]::SmallInt}
'UInt32' {[Data.SQLDbType]::Int}
'UInt64' {[Data.SqlDbType]::BigInt}
'Single' {[Data.SqlDbType]::Decimal}
default {[Data.SqlDbType]::VarChar}
}
}
function Add-SqlTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [String]$TableName,
[Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[ValidateRange(0,8000)]
[Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000,
[Parameter(Position=7, Mandatory=$false)] [switch]$AsScript
)
try
{
if($Username)
{
$con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password
}
else
{
$con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance
}
$con.Connect()
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
$db = $server.Databases[$Database]
$table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName
foreach ($column in $DataTable.Columns)
{
$sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)"
if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar')
{
if ($MaxLength -gt 0)
{
$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength
}
else
{
$sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max"
$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType
}
}
else
{
$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType
}
$col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType
$col.Nullable = $column.AllowDBNull
$table.Columns.Add($col)
}
if ($AsScript) {
$table.Script()
}
else
{
$table.Create()
}
}
catch
{
$message = $_.Exception.GetBaseException().Message
Write-Error $message
}
}
function Write-DataTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [string]$TableName,
[Parameter(Position=3, Mandatory=$true)] $Data,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000,
[Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0,
[Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15
)
$conn=new-object System.Data.SqlClient.SQLConnection($Username)
{
$ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout
}
else
{
$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout
}
$conn.ConnectionString=$ConnectionString
try
{
$conn.Open()
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = $tableName
$bulkCopy.BatchSize = $BatchSize
$bulkCopy.BulkCopyTimeout = $QueryTimeOut
$bulkCopy.WriteToServer($Data)
$conn.Close()
}
catch
{
$ex = $_.Exception
Write-Error "$ex.Message"
continue
}
}
$xmlfile = [xml](get-content "C:\SQLConfiguration.XML") set-location $xmlfile.configuration.folders.APP.Path
$servername=$xmlfile.configuration.server.servername
foreach ($svr in get-content C:\justservers.txt) {
$dt = new-object "System.Data.DataTable"
$cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
$cn.Open()
$sql = $cn.CreateCommand()
$sql.CommandText = "select * from blah"
The above code is working for default instance but not named instance.
Justserver.txt file has both default and named instances like below
xxxxx xxxx\ins01 xxx\ins02
I am hitting error for xxxx\ins01 as "Exception calling execute reader with 0 arguments" string or binary data would be truncated"
any help is appreciated
regards,

Is the backslash before the instance name being seen as an escape character? Try using a replace in your code to escape the escape, something like this:
$svr = $svr -replace '\\', '\\'
$cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
$cn.Open()

There is no problem with Powershell but I found one of coloumn length was not ok with the data populated. I have fixed it now and got result as expected. Thanks you all and have a great weekend

Related

How to get the 'status' column value in Windows explorer by PowerShell or java

when we open a windows explorer, we will see multi-column, like this:
now, I want to get the status column(Circled in red) value by PowerShell or java, Is there a way to do it?
You can include below function and modify as per your need in Powershell.
Below Powershell function can be used to get all details or properties of an item in file explorer.
function Get-FileMetaData {
<#
.SYNOPSIS
Small function that gets metadata information from file providing similar output to what Explorer shows when viewing file
.DESCRIPTION
Small function that gets metadata information from file providing similar output to what Explorer shows when viewing file
.PARAMETER File
FileName or FileObject
.EXAMPLE
Get-ChildItem -Path $Env:USERPROFILE\Desktop -Force | Get-FileMetaData | Out-HtmlView -ScrollX -Filtering -AllProperties
.EXAMPLE
Get-ChildItem -Path $Env:USERPROFILE\Desktop -Force | Where-Object { $_.Attributes -like '*Hidden*' } | Get-FileMetaData | Out-HtmlView -ScrollX -Filtering -AllProperties
.NOTES
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline)][Object] $File,
[switch] $Signature
)
Process {
foreach ($F in $File) {
$MetaDataObject = [ordered] #{}
if ($F -is [string]) {
$FileInformation = Get-ItemProperty -Path $F
} elseif ($F -is [System.IO.DirectoryInfo]) {
#Write-Warning "Get-FileMetaData - Directories are not supported. Skipping $F."
continue
} elseif ($F -is [System.IO.FileInfo]) {
$FileInformation = $F
} else {
Write-Warning "Get-FileMetaData - Only files are supported. Skipping $F."
continue
}
$ShellApplication = New-Object -ComObject Shell.Application
$ShellFolder = $ShellApplication.Namespace($FileInformation.Directory.FullName)
$ShellFile = $ShellFolder.ParseName($FileInformation.Name)
$MetaDataProperties = [ordered] #{}
0..400 | ForEach-Object -Process {
$DataValue = $ShellFolder.GetDetailsOf($null, $_)
$PropertyValue = (Get-Culture).TextInfo.ToTitleCase($DataValue.Trim()).Replace(' ', '')
if ($PropertyValue -ne '') {
$MetaDataProperties["$_"] = $PropertyValue
}
}
foreach ($Key in $MetaDataProperties.Keys) {
$Property = $MetaDataProperties[$Key]
$Value = $ShellFolder.GetDetailsOf($ShellFile, [int] $Key)
if ($Property -in 'Attributes', 'Folder', 'Type', 'SpaceFree', 'TotalSize', 'SpaceUsed') {
continue
}
If (($null -ne $Value) -and ($Value -ne '')) {
$MetaDataObject["$Property"] = $Value
}
}
if ($FileInformation.VersionInfo) {
$SplitInfo = ([string] $FileInformation.VersionInfo).Split([char]13)
foreach ($Item in $SplitInfo) {
$Property = $Item.Split(":").Trim()
if ($Property[0] -and $Property[1] -ne '') {
$MetaDataObject["$($Property[0])"] = $Property[1]
}
}
}
$MetaDataObject["Attributes"] = $FileInformation.Attributes
$MetaDataObject['IsReadOnly'] = $FileInformation.IsReadOnly
$MetaDataObject['IsHidden'] = $FileInformation.Attributes -like '*Hidden*'
$MetaDataObject['IsSystem'] = $FileInformation.Attributes -like '*System*'
if ($Signature) {
$DigitalSignature = Get-AuthenticodeSignature -FilePath $FileInformation.Fullname
$MetaDataObject['SignatureCertificateSubject'] = $DigitalSignature.SignerCertificate.Subject
$MetaDataObject['SignatureCertificateIssuer'] = $DigitalSignature.SignerCertificate.Issuer
$MetaDataObject['SignatureCertificateSerialNumber'] = $DigitalSignature.SignerCertificate.SerialNumber
$MetaDataObject['SignatureCertificateNotBefore'] = $DigitalSignature.SignerCertificate.NotBefore
$MetaDataObject['SignatureCertificateNotAfter'] = $DigitalSignature.SignerCertificate.NotAfter
$MetaDataObject['SignatureCertificateThumbprint'] = $DigitalSignature.SignerCertificate.Thumbprint
$MetaDataObject['SignatureStatus'] = $DigitalSignature.Status
$MetaDataObject['IsOSBinary'] = $DigitalSignature.IsOSBinary
}
[PSCustomObject] $MetaDataObject
}
}
}
Reference :
Follow Below Link for the complete tutorial.
https://evotec.xyz/getting-file-metadata-with-powershell-similar-to-what-windows-explorer-provides/

Why the argument is empty or null

everyone
I'm a novice at Powershell.
My script gather Windows Event Viewer logs and export data to csv files. If the input is empty then is used the default values.
But it crashes:
"Export-Csv: Unable to validate argument for "Path" parameter. The argument is empty or NULL. Specify a non-empty, non-null argument and then run the command again."
Could explain to me why??
function exportLogs
{
[CmdletBinding()]
param (
$exportFolder=(Read-Host -prompt "exportFolder"),
$applicatiomLogs=(Read-Host -prompt "applicationLogs"),
$systemLogs=(Read-Host -prompt "systemLogs"),
$fromDate=(Read-Host -prompt "fromDate"),
$eventTypes=(Read-Host -prompt "eventTypes")
)
$comp = $env:computername
$now=Get-Date
#check empty input and assign default values
if (!$exportFolder) { [String]$exportFolder="D:\temp\" }
if (!$applicationLogs) {
$applicationLogs="True"
[System.Convert]::ToBoolean($applicationLogs)
}
if (!$systemLogs) {
$systemLogs="True"
[System.Convert]::ToBoolean($systemLogs)
}
if (!$fromDate) { [DateTime]$fromDate=$now.AddDays(-30) }
if (!$eventtypes) { [String[]]$eventtypes=("Error", "Warning") }
if ($applicationLogs)
{
$exportFile = $exportFolder + "applicationLogs_" + $now.ToString("yyyyMMddHHmmss") + ".csv"
$exportedLog = get-eventlog -ComputerName $comp -log "Application" -After $fromDate -EntryType $eventTypes
exportCsv($exportedLog, $exportFile)
}
if ($systemLogs)
{
$exportFile = $exportFolder + "systemLogs_" + $now.ToString("yyyyMMddHHmmss") + ".csv"
$exportedLog = get-eventlog -ComputerName $comp -log "System" -After $fromDate -EntryType $eventTypes
exportCsv($exportedLog, $exportFile)
}
}
function exportCsv([String]$exportedLog, [String]$exportFile)
{
$el_sorted = $exportedLog | Sort-Object TimeGenerated
Write-Host Exporting to $exportFile
$el_sorted|Select MachineName, TimeGenerated, EntryType, Source, Message | Export-CSV $exportFile -NoTypeInfo
}
Try this refactor... (run on the default Windows Sandbox on Win10)
function New-LogExport
{
Param
(
[String]$exportedLog,
[String]$exportFile
)
$el_sorted = $exportedLog |
Sort-Object TimeGenerated
Write-Host "Exporting to $exportFile"
$el_sorted |
Select-Object MachineName,
TimeGenerated,
EntryType,
Source,
Message |
Export-Csv -Path $exportFile -NoTypeInfo
}
function Start-ExportLogs
{
[CmdletBinding()]
param
(
$exportFolder = (Read-Host -prompt 'exportFolder'),
$applicatiomLogs = (Read-Host -prompt 'applicationLogs'),
$systemLogs = (Read-Host -prompt 'systemLogs'),
$fromDate = (Read-Host -prompt 'fromDate'),
$eventTypes = (Read-Host -prompt 'eventTypes')
)
$comp = $env:computername
$now = Get-Date
if (!$exportFolder)
{[String]$exportFolder = 'C:\temp'}
if (!$applicationLogs)
{
$applicationLogs = 'True'
[System.Convert]::ToBoolean($applicationLogs)
}
if (!$systemLogs)
{
$systemLogs = 'True'
[System.Convert]::ToBoolean($systemLogs)
}
if (!$fromDate)
{[DateTime]$fromDate = $now.AddDays(-30)}
if (!$eventtypes)
{[String[]]$eventtypes = ('Error', 'Warning')}
if ($applicationLogs)
{
$exportFile = "$exportFolder\applicationLogs_$($now.ToString('yyyyMMddHHmmss')).csv"
$getEventLogSplat = #{
ComputerName = $comp
LogName = 'Application'
EntryType = $eventTypes
After = $fromDate
}
$exportedLog = Get-EventLog #getEventLogSplat
New-LogExport -exportedLog $exportedLog, -exportFile $exportFile
}
if ($systemLogs)
{
$exportFile = "$exportFolder\systemLogs_$($now.ToString('yyyyMMddHHmmss')).csv"
$getEventLogSplat = #{
ComputerName = $comp
LogName = 'System'
EntryType = $eventTypes
After = $fromDate
}
$exportedLog = Get-EventLog #getEventLogSplat
}
New-LogExport -exportedLog $exportedLog -exportFile $exportFile
}
# Results
<#
exportFolder:
applicationLogs:
systemLogs:
fromDate:
eventTypes:
True
True
Exporting to C:\temp\applicationLogs_20210120143659.csv
Exporting to C:\temp\systemLogs_20210120143659.csv
#>

Server Pending Reboot

I am trying to modify my PowerShell script to find the best possible ways to check for Pending Reboots on our servers. This script checks the registry entries. However, I am seeing inconsistencies from other PowerShell scripts and wanting guidance on the best approach.
function PendingReboot ($comp) {
process {
try {
$WMI_OS = ""
$RegCon = ""
$WMI_OS = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $comp -ErrorAction Stop
if ($?){
try{
$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine",$comp)
If ($WMI_OS.BuildNumber -ge 6001){
$RegValueSetupex = ""
$RegValuePFRO2k8 = ""
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValueSetupex = $RegSubKeySM.GetValue("SetupExecute",$null)
if ($RegValueSetupex){
$RegValueSetupex = $true
}
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValuePFRO2k8 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null)
if ($RegValuePFRO2k8 ){
$RegValuePFRO2k8 = $true
}
$RegCon.Close()
if ( $RegValueSetupex -eq $true -or $RegValuePFRO2k8 -eq $true){
return '<font color="#FF0000">'+$true
}
else {
return $false
}
}
else{
$RegValuePFRO2k3 = $false;
$RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]"LocalMachine","$comp")
$RegSubKeySM = $RegCon.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\")
$RegValuePFRO2k3 = $RegSubKeySM.GetValue("PendingFileRenameOperations",$null)
$RegCon.Close()
If ($RegValuePFRO2k3) {
return '<font color="#FF0000">'+$true;
}
else {
return $false;
}
}
}
catch {
return '<font color="#FFFF00">'+"Remote Registry Service KO"
}
}
else {
throw $error[0].Exception
}
}
catch {
return '<font color="#FF0000">'+"RPC Issue"
}
}
}
Try this.
function PendingBoot($comp) {
$pendingRebootTests = #(
#{
Name = 'RebootPending'
Test = { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing' Name 'RebootPending' -ErrorAction Ignore }
TestType = 'ValueExists'
}
#{
Name = 'RebootRequired'
Test = { Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update' Name 'RebootRequired' -ErrorAction Ignore }
TestType = 'ValueExists'
}
#{
Name = 'PendingFileRenameOperations'
Test = { Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name 'PendingFileRenameOperations' -ErrorAction Ignore }
TestType = 'NonNullValue'
}
)
$session = New-PSSession -Computer SRV1
foreach ($test in $pendingRebootTests) {
$result = Invoke-Command -Session $session -ScriptBlock $test.Test
if ($test.TestType -eq 'ValueExists' -and $result) {
$true
} elseif ($test.TestType -eq 'NonNullValue' -and $result -and $result.($test.Name)) {
$true
} else {
$false
}
}
$session | Remove-PSSession
}

Speed up PowerShell script for Windows Registry search (currently 30 minutes)

I'm working on a script for use in Windows 7 and Windows 10 for a Windows Registry search in HKLM:\Software\Classes. So far my code works, but it's extremely slow. It takes about 30 minutes to complete.
I need to use Set-Location also to avoid an error with Get-ItemProperty, which occurs because the $path is not a valid object.
How can I speed this code up? What's wrong?
File regsearch.ps1 (Mathias R. Jessen's answer applied)
Function Get-RegItems
{
Param(
[Parameter(Mandatory=$true)]
[string]$path,
[string]$match)
#Set Local Path and ignore wildcard (literalpath)
Set-Location -literalpath $path
$d = Get-Item -literalpath $path
# If more than one value -> process
If ($d.Valuecount -gt 0) {
$d |
# Get unkown property
Select-Object -ExpandProperty Property |
ForEach {
$val = (Get-ItemProperty -Path . -Name $_).$_
#if Filter $match found, generate ReturnObject
if (($_ -match $match) -or ($val -match $match ) -or ($path-match $match)) {
New-Object psobject -Property #{ “key”=$path; “property”=$_; “value” = $val ;}
}
}
}
} #end function Get-RegItems
Function RegSearch
{
Param(
[Parameter(Mandatory=$true)]
[string]$path,
[string]$match)
# Expand $path if necessary to get a valid object
if ($path.Indexof("HKEY") -ne "-1" -and $path.Indexof("Registry::") -eq "-1" ) {
$path = "Microsoft.PowerShell.Core\Registry::" +$path
}
# Retrieve items of the main key
Get-RegItems -path $path -match $match
# Retrieve items of all child keys
Get-ChildItem $path -Recurse -ErrorAction SilentlyContinue |
ForEach {
Get-RegItems -path $_.PsPath -match $match
}
} #end function RegSearch
#$search = "HKCU:\SOFTWARE\Microsoft\Office"
$searchkey = ‘HKLM:\SOFTWARE\Microsoft\Office\’
#$searchkey = "HKLM:\Software\Classes\"
$pattern = "EventSystem"
cls
$result = #()
Measure-Command {$result = Regsearch -path $searchkey -match $pattern }
# TESTING
#$t = #( "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Classes",
# "HKLM:\Software\Classes\Wow6432Node\CLSID\",
# "HKCU:\SOFTWARE\Microsoft\Office\",
# "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office")
#cls
#$t |ForEach { Get-RegItems -path $_ } | fl
if ($result.Count) {
$result
"Count: {0}" -f ($result.Count-1)
}
else {
"Path: {0} `nNo Items found" -f $searchkey
}
I accepted the challenge and made it "as fast as possible".
Now it is even faster than REGEDIT or any other tool.
The below sample lasts 11 seconds to parse the complete OFFICE-key and all subkeys.
In addition, it also searches for string-matches in REG-BINARY etc.
Enjoy!
# carsten.giese#googlemail.com
# reference: https://msdn.microsoft.com/de-de/vstudio/ms724875(v=vs.80)
cls
remove-variable * -ea 0
$ErrorActionPreference = "stop"
$signature = #'
[DllImport("advapi32.dll")]
public static extern Int32 RegOpenKeyEx(
UInt32 hkey,
StringBuilder lpSubKey,
int ulOptions,
int samDesired,
out IntPtr phkResult
);
[DllImport("advapi32.dll")]
public static extern Int32 RegQueryInfoKey(
IntPtr hKey,
StringBuilder lpClass, Int32 lpCls, Int32 spare,
out int subkeys, out int skLen, int mcLen, out int values,
out int vNLen, out int mvLen, int secDesc,
out System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime
);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 RegEnumValue(
IntPtr hKey,
int dwIndex,
IntPtr lpValueName,
ref IntPtr lpcchValueName,
IntPtr lpReserved,
out IntPtr lpType,
IntPtr lpData,
ref int lpcbData
);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
public static extern Int32 RegEnumKeyEx(
IntPtr hKey,
int dwIndex,
IntPtr lpName,
ref int lpcName,
IntPtr lpReserved,
IntPtr lpClass,
int lpcClass,
out System.Runtime.InteropServices.ComTypes.FILETIME lpftLastWriteTime
);
[DllImport("advapi32.dll")]
public static extern Int32 RegCloseKey(IntPtr hkey);
'#
$reg = add-type $signature -Name reg -Using System.Text -PassThru
$marshal = [System.Runtime.InteropServices.Marshal]
function search-RegistryTree($path) {
# open the key:
[IntPtr]$hkey = 0
$result = $reg::RegOpenKeyEx($global:hive, $path, 0, 25,[ref]$hkey)
if ($result -eq 0) {
# get details of the key:
$subKeyCount = 0
$maxSubKeyLen = 0
$valueCount = 0
$maxNameLen = 0
$maxValueLen = 0
$time = $global:time
$result = $reg::RegQueryInfoKey($hkey,$null,0,0,[ref]$subKeyCount,[ref]$maxSubKeyLen,0,[ref]$valueCount,[ref]$maxNameLen,[ref]$maxValueLen,0,[ref]$time)
if ($result -eq 0) {
$maxSubkeyLen += $maxSubkeyLen+1
$maxNameLen += $maxNameLen +1
$maxValueLen += $maxValueLen +1
}
# enumerate the values:
if ($valueCount -gt 0) {
$type = [IntPtr]0
$pName = $marshal::AllocHGlobal($maxNameLen)
$pValue = $marshal::AllocHGlobal($maxValueLen)
foreach ($index in 0..($valueCount-1)) {
$nameLen = $maxNameLen
$valueLen = $maxValueLen
$result = $reg::RegEnumValue($hkey, $index, $pName, [ref]$nameLen, 0, [ref]$type, $pValue, [ref]$valueLen)
if ($result -eq 0) {
$name = $marshal::PtrToStringUni($pName)
$value = switch ($type) {
1 {$marshal::PtrToStringUni($pValue)}
2 {$marshal::PtrToStringUni($pValue)}
3 {$b = [byte[]]::new($valueLen)
$marshal::Copy($pValue,$b,0,$valueLen)
if ($b[1] -eq 0 -and $b[-1] -eq 0 -and $b[0] -ne 0) {
[System.Text.Encoding]::Unicode.GetString($b)
} else {
[System.Text.Encoding]::UTF8.GetString($b)}
}
4 {$marshal::ReadInt32($pValue)}
7 {$b = [byte[]]::new($valueLen)
$marshal::Copy($pValue,$b,0,$valueLen)
$msz = [System.Text.Encoding]::Unicode.GetString($b)
$msz.TrimEnd(0).split(0)}
11 {$marshal::ReadInt64($pValue)}
}
if ($name -match $global:search) {
write-host "$path\$name : $value"
$global:hits++
} elseif ($value -match $global:search) {
write-host "$path\$name : $value"
$global:hits++
}
}
}
$marshal::FreeHGlobal($pName)
$marshal::FreeHGlobal($pValue)
}
# enumerate the subkeys:
if ($subkeyCount -gt 0) {
$subKeyList = #()
$pName = $marshal::AllocHGlobal($maxSubkeyLen)
$subkeyList = foreach ($index in 0..($subkeyCount-1)) {
$nameLen = $maxSubkeyLen
$result = $reg::RegEnumKeyEx($hkey, $index, $pName, [ref]$nameLen,0,0,0, [ref]$time)
if ($result -eq 0) {
$marshal::PtrToStringUni($pName)
}
}
$marshal::FreeHGlobal($pName)
}
# close:
$result = $reg::RegCloseKey($hkey)
# get Tree-Size from each subkey:
$subKeyValueCount = 0
if ($subkeyCount -gt 0) {
foreach ($subkey in $subkeyList) {
$subKeyValueCount += search-RegistryTree "$path\$subkey"
}
}
return ($valueCount+$subKeyValueCount)
}
}
$timer = [System.Diagnostics.Stopwatch]::new()
$timer.Start()
# setting global variables:
$search = "enterprise"
$hive = [uint32]"0x80000002" #HKLM
$subkey = "SOFTWARE\Microsoft\Office"
$time = New-Object System.Runtime.InteropServices.ComTypes.FILETIME
$hits = 0
write-host "We start searching for pattern '$search' in Registry-Path '$subkey' ...`n"
$count = search-RegistryTree $subkey
$timer.stop()
$sec = [int](100 * $timer.Elapsed.TotalSeconds)/100
write-host "`nWe checked $count reg-values in $sec seconds. Number of hits = $hits."
The single biggest improvement you can make here is changing:
Set-Location -literalpath $path
$d= Get-Item .
to
$d = Get-Item -LiteralPath $path
Manipulating the location stack for each key in the hierarchy introduces A LOT of unnecessary overhead
User function call overhead (scriptblocks included) is extremely big (e.g. 0.1-1ms). This becomes a very serious issue when the function is executed thousands/millions of times. Surprisingly, it's not mentioned in optimization-related articles (at least I've never seen it and I googled this topic a lot).
Unfortunately, the only only real solution to this particular issue is to inline the code at the cost of duplication and reduced readability.
Optimization should include code profiling.
PowerShell doesn't have a code profiler so you'll need to do it manually with Measure-Command.
Use System.Diagnostics.Stopwatch inside loops to display the accumulated time:
# global stopwatch
$sw1 = [Diagnostics.Stopwatch]::new()
$sw2 = [Diagnostics.Stopwatch]::new()
............
forEach(....) {
........
$sw1.start()
........
$sw1.stop()
........
$sw2.start()
........
$sw2.stop()
........
}
............
echo $sw1.ElapsedMilliseconds, $sw2.ElapsedMilliseconds
Here is a faster version of you sample-script.
Lasts ca. 1 minute on my machine.
If you need it faster, then you need to work with advapi32.dll-Pinvokes, but then
it will end quite complex.
Function Get-RegItems {
Param(
[Parameter(Mandatory=$true)]
[string]$path,
[string]$match
)
#write-host $path.Substring(30)
$key = Get-Item -literalpath $path
ForEach ($entry in $key.Property) {
$value = $key.GetValue($entry)
if (($entry -match $match) -or ($value -match $match ) -or ($path -match $match)) {
write-host "key=$path property=$entry value=$value"
}
}
}
Function RegSearch {
Param(
[Parameter(Mandatory=$true)]
[string]$path,
[string]$match
)
Get-RegItems -path $path -match $match
ForEach ($item in get-ChildItem -literalpath $path -ea 0) {
RegSearch -path $item.PsPath -match $match
}
}
cls
Remove-Variable * -ea 0
[System.GC]::Collect()
$searchkey =‘HKLM:\SOFTWARE\Microsoft\Office’
$pattern = "EventSystem"
measure-command {
$result = RegSearch -path $searchkey -match $pattern
}
Don't use the registry drive provider, if you want it faster.
I've also read classes with static methods are faster.

Oracle & Powershell different behaviour in batch file

I have built a script that connects to an Oracle database and proceed to some various export.
It works perfectly when I launch powershell.exe from Windows start menu and run the script as follows:
.\OracleConnect
But, when I try to automatize the exact same script by launching it from a batch, I'm getting an error message:
"The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception"
As I said the script is identical in both case.
My .bat file is as follows:
set path=%~dp0
set file=OracleConnect.ps1
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass %file%
I've also tried with the alternative powershell.exe path:
C:\Windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass %file%
Without any success.
Here is my full script:
$scriptpath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
Set-Location $scriptpath
[void][Reflection.Assembly]::LoadFile($scriptpath + "\Oracle.DataAccess.dll")
$logpath = $scriptpath + "\Export.txt"
$connectionpath = read-host 'connection file [optional]'
if($connectionpath)
{
$connectionstring = get-content $connectionpath
}
else
{
$server = read-host 'host name'
$user = read-host 'user name'
$pass = read-host 'password'
$database = read-host 'service'
$connectionstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=$server)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=$database)));User Id=$user;Password=$pass;"
}
$echoon = read-host 'echo on (y - n) [default off]'
function global:get-result($query)
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
$oracleconnection.connectionstring = $connectionstring
$oracleconnection.Open()
$oraclecommand = $oracleconnection.CreateCommand()
$oraclecommand.CommandText = $query
$reader = $oraclecommand.ExecuteReader()
$writer = new-object System.IO.StreamWriter($logpath)
$counter = 0
write-output ""
while ($reader.Read())
{
$columns = ""
$columnslog = ""
$tab = ""
$tablog = ""
if($counter -eq 0)
{
for ($i= 0; $i -lt $reader.FieldCount; $i++)
{
$columns = $columns + " | " + $reader.GetName($i)
$columnslog = $columnslog + "`t" + $reader.GetName($i).ToUpper()
}
$writer.WriteLine($columnslog)
if($echoon -eq "y")
{
write-output $columns
write-output ""
}
}
for ($i= 0; $i -lt $reader.FieldCount; $i++)
{
$tab = $tab + " | " + $reader.GetValue($i).ToString()
$tablog = $tablog + "`t" + $reader.GetValue($i).ToString()
}
$writer.WriteLine($tablog)
if($echoon -eq "y")
{
write-output $tab
write-output ""
}
$counter = $counter + 1
}
$oracleconnection.Close()
$writer.Close()
}
function global:update-query($query)
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
$oracleconnection.connectionstring = $connectionstring
$oracleconnection.Open()
$oraclecommand = $oracleconnection.CreateCommand()
$oraclecommand.CommandText = $query
$reader = $oraclecommand.ExecuteNonQuery()
}
function global:readscript($path)
{
$inenc = [System.Text.Encoding]::UTF7
$reader = new-object System.IO.StreamReader($path, $inenc)
$finalquery = ""
while ($line = $reader.ReadLine())
{
$finalquery += $line
}
$reader.close()
return $finalquery
}
write-output "Enter query or type 'exit' to quit..."
while($true)
{
$value = read-host " "
if($value -eq "exit")
{
$save = read-host "Save connection ? [Y:yes N:no]"
if($save.ToLower() -eq "y")
{
$path = read-host "Connection path"
if(test-path $path)
{
rm $path
}
new-item -type file -force $path
$writer = New-Object System.IO.StreamWriter $path
$writer.WriteLine($connectionstring)
$writer.Close()
}
else
{
}
return
}
else
{
if($value.Tolower().EndsWith(".sql") -eq $false)
{
if ($value.ToLower().StartsWith("select") -or $value.ToLower().StartsWith("show"))
{
get-result($value)
}
else
{
update-query($value)
}
}
else
{
$scriptquery = readscript $value
if ($scriptquery.ToLower().StartsWith("select") -or $scriptquery.ToLower().StartsWith("show"))
{
get-result($scriptquery)
}
else
{
update-query($scriptquery)
}
}
}
}
Edit:
I've now tried to catch the exception adding a try catch instruction here:
try
{
$oracleconnection = new-object Oracle.DataAccess.Client.OracleConnection
}
catch
{
write-host $_.Exception.ToString()
}
And I'm getting this message:
Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client
I still don't understand how this can be an issue with the version of Oracle since it works fine when I run it from a powershell window.

Resources