How to check if custom culture exists - powershell

I have created one custom culture as 'gh-es'. I am trying to check if its already registered.its working fine if culture is registered but if not it throw an error in start only.
I am unable to find how to check if a culture is present or to check if its exists
$CustomCulture= [cultureinfo]::GetCultureInfo('gh-es')
If($CustomCulture -ne null)
{
Write-output "culture already registered"
}
Else
{
$CultureName = 'gh-es'
$BaseCulture=[cultureinfo]::GetCultureInfo('es-US')
$BaseRegion = New-Object System.Globalization.RegionInfo 'es-US'
try {
# Set up CultureAndRegionInfoBuilder
Add-Type -AssemblyName sysglobl
$CultureBuilder = New-Object System.Globalization.CultureAndRegionInfoBuilder
#($CultureName,[System.Globalization.CultureAndRegionModifiers]::None) $CultureBuilder.LoadDataFromCultureInfo($BaseCulture)
$CultureBuilder.LoadDataFromRegionInfo($BaseRegion)
$CultureBuilder.Register()
}
catch
{
throw
}
}

this is what i mean by using try/catch to handle an error when checking for a culture ...
try {
[cultureinfo]::GetCultureInfo('666-santa')
}
catch
{
'something glitched'
}
the output = something glitched
without the try/catch, the output is an error msg ...
Exception calling "GetCultureInfo" with "1" argument(s): "Culture is not supported.
Parameter name: name
666-santa is an invalid culture identifier."
At line:1 char:1
+ [cultureinfo]::GetCultureInfo('666-santa')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CultureNotFoundException

Related

PowerShell Unable to find type

I'm having trouble with an error when I try to run my PowerShell script from the command line:
Unable to find type [System.Windows.Forms.ListViewItem]
I have tried different ways to import the required classes:
using assembly System.Windows.Forms
using namespace System.Windows.Forms
using namespace System.Drawing
Add-Type System.Windows.Forms
In PowerShell ISE, I can run my script without any errors. But when I try to execute my script from CMD it doesn't work. It's exactly the same code and the same script files. This is the command I use to execute the script in CMD followed by the error messages:
C:\Users\Admin>powershell -File "C:\Folder\Main.ps1"
At C:\Folder\Main.ps1:35 char:30
+ ... return (([int](([System.Windows.Forms.ListViewItem]$a).Sub ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.ListViewItem].
At C:\Folder\Main.ps1:35 char:114
+ ... umnIndex].Text)) - ([int](([System.Windows.Forms.ListViewItem]$b).Sub ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.ListViewItem].
At C:\Folder\Main.ps1:37 char:41
+ ... return ([String]::Compare(([System.Windows.Forms.ListViewItem]$a).Sub ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.ListViewItem].
At C:\Folder\Main.ps1:37 char:115
+ ... [$this.columnIndex].Text, ([System.Windows.Forms.ListViewItem]$b).Sub ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.ListViewItem].
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound
The error messages refer to the code below. This is my only class in that script:
class ListViewItemComparer : System.Collections.IComparer {
[int]$sortOrder
[String]$columnType
[int]$columnIndex
ListViewItemComparer() {
$this.sortOrder = 1
$this.columnType = "String"
$this.columnIndex = 0
}
ListViewItemComparer([int]$sortOrder, [String]$columnType, [int]$columnIndex) {
$this.sortOrder = $sortOrder
$this.columnType = $columnType
$this.columnIndex = $columnIndex
}
[void] ChangeSorting([int]$columnIndex, [String]$columnType) {
if($this.columnIndex -eq $columnIndex) {
$this.sortOrder *= -1
} else {
$this.columnIndex = $columnIndex
$this.sortOrder = 1
}
$this.columnType = $columnType
}
[int] Compare([Object]$a, [Object]$b) {
if($this.columnType -eq "Number") {
return (([int](([System.Windows.Forms.ListViewItem]$a).SubItems[$this.columnIndex].Text)) - ([int](([System.Windows.Forms.ListViewItem]$b).SubItems[$this.columnIndex].Text))) * $this.sortOrder
} else {
return ([String]::Compare(([System.Windows.Forms.ListViewItem]$a).SubItems[$this.columnIndex].Text, ([System.Windows.Forms.ListViewItem]$b).SubItems[$this.columnIndex].Text)) * $this.sortOrder
}
}
}
I'm using the type System.Windows.Forms.ListViewItem at other places too in my code, but there is no problem outside of a class. I don't even have to write the whole class path, just ``ListViewItem` works as well.
Can somebody tell me why the type System.Windows.Forms.ListViewItem is not recognized?
Why is it recognized outside the ListViewItemComparer class in the same script file?
Why does this error occur when I run the script from CMD and not in PowerShell ISE?

Override Creation for Monitors and Rules

I want to create PowerShell scripts to override some parameter of my monitor and rule. I used the below code, but I have some errors. I want override my overidable parameter not enabled or something else. How can I doe this?
$mps = Get-SCOMManagementPack | ? {$_.Name -like "test"}
$overrideMp = Get-SCOMManagementPack -DisplayName "Overrides"
$overridename = "testmonitor.Overrides"
$monitor = 'testmonitor'
$override = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorPropertyOverride($overrideMp,$overridename)
$override.Monitor = $monitor
$override.Property = 'WarningThreshold'
$override.Value = 80
$override.DisplayName = "Overrides"
$overrideMp.Verify()
$overrideMp.AcceptChanges()
Errors:
error1: Exception setting "Property": "Cannot convert value "WarningThreshold" to
type "Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorProperty".
Error: "Unable to match the identifier name WarningThreshold to a valid enumerator
name. Specify one of the following enumerator names and try again: Enabled,
TraceEnabled, Algorithm, AlgorithmPercentage, DefaultState, GenerateAlert,
AutoResolve, AlertPriority, AlertOnState, AlertSeverity, AlertMessage,
AlertParameter1, AlertParameter2, AlertParameter3, AlertParameter4,
AlertParameter5, AlertParameter6, AlertParameter7, AlertParameter8,
AlertParameter9, AlertParameter10, MemberInMaintenance, MemberUnavailable,
IgnoreMemberInMaintenance, IgnoreMemberUnavailable""
At line:1 char:2
+ $override.Property = $parametername
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
error2 : Exception calling "AcceptChanges" with "0" argument(s): "Database error.
MPInfra_p_ManagementPackInstall failed with exception: Failed to validate item:
testrule1"
At line:193 char:1
+ $MP.AcceptChanges()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ManagementPackException
The error message looks rather clear to me. There is no property WarningThreshold in the ManagementPackMonitorProperty enumeration. I don't have much experience with SCOM, but you probably need to override the property AlertOnState for monitors where the property AlertSeverity has the value Warning.
Try something along the lines of this:
$mps | Get-SCOMMonitor | Where-Object {
# (other selection criteria) -and
$_.AlertSettings.AlertSeverity -eq 'Warning'
} | ForEach-Object {
$ctx = Get-SCOMClass -Id $_.Target.Id
# ...
$override = New-Object ...
$override.Monitor = $_
$override.Property = 'AlertOnState'
$override.Value = 80
$override.Context = $ctx
# ...
}
Code adopted from here (probably the same place where you found it). Not sure if this works, though. Like I said, I have very little experience with SCOM, and I don't have a SCOM server available for testing.
I'll try to debug it tomorrow in the office.
BTW, there is a third-party tool for override management called MPTuner: http://mpwiki.viacode.com/default.aspx?g=mptuner
It's free so you should try.
Roman.
It's quite confusing, but there are two different type of overrides for each workflow type. For a monitor there are:
MonitorPropertyOverride
MonitorConfigurationOverride
You are using the first one, wgich is for standard parameters only, like Enabled, for example. For any custom parameters use Configuration Override.

PowerShell InvokeGet the directory property cannot be found

We needed to retrieve the information in active directory concerning 'Terminal Services'. For this I've created a function that works fine most of the time. However, with some users we have issues.
The code:
Function Get-ADTSProfile {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[String] $DistinguishedName,
[parameter(Mandatory=$true,Position=1)]
[ValidateNotNullOrEmpty()]
[ValidateSet('UserProfile','AllowLogon','HomeDirectory','HomeDrive')]
[String]$Property
)
Begin {
$User = [ADSI]"LDAP://$DistinguishedName"
}
Process {
Switch ($Property) {
'AllowLogon' {if ($($User.psbase.InvokeGet('allowLogon')) -eq '1'){$True}else{$False}}
'HomeDirectory' {$User.psbase.InvokeGet('TerminalServicesHomeDirectory')}
'HomeDrive' {$User.psbase.InvokeGet('TerminalServicesHomeDrive')}
'UserProfile' {$User.psbase.InvokeGet('TerminalServicesProfilePath')}
}
}
}
The error:
Get-ADTSProfile -DistinguishedName 'CN=test\, test (Den Bosch) NLD,OU=Users,OU=Disabled,OU=NLD,OU=EU,DC=domain,DC=net' -Property 'UserProfile'
Exception calling "InvokeGet" with "1" argument(s): "The directory property cannot be fo
und in the cache.
"
At S:\Test\Brecht\Testie.ps1:84 char:38
+ 'UserProfile' {$User.psbase.InvokeGet('TerminalServicesPro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
I can't really figure out why it works on some and not on all..
I've been working on a recent project that uses ADSI to set and read Terminal Services attributes. From my testing anytime you perform a "InvokeGet({TS Attribute})" a COM exception will be thrown with the message "The directory property cannot be found in cache"
This seems to occur only when the "userParameters" attribute is not set in AD. Maybe the attribute internally checks the ADSI cache for userParameters? So i'm thinking logically you could check the DirectoryEntry for userParameters first, then try and read the properties, or else set it to construct the blob
if ($user.Properties.Contains("userParameters"))
{
#Read the Property from ADSI
Write-Host $user.InvokeGet("TerminalServicesProfilePath")
} else {
#Set the property to construct the userParameter blob
$user.InvokeSet("TerminalServicesProfilePath", "\\somepath")
$user.CommitChanges()
}
Even if the userParameters attribute is not set, you can still perform an InvokeSet to have it constructed

Multiple parameter in powershell

I have a powershell script to call the SP which is shown below
$sqlTableConnection = New-Object [System.Data.SqlClient.SqlConnection]("Server=1xx.xx.xxx; Database=dbName; Integrated Security= True");
$sqlTableCmd = New-Object [System.Data.SqlClient.SqlCommand]
$sqlTableCmd.CommandText = "[System_Control].[usp_Check_system]"
$sqlTableCmd.Connection = $sqlTableConnection;
$jobName1 = "MASTER_JOB";
$sqlTableCmd.Parameters.AddWithValue("#JobName", $jobName1) ;
$outParameter = new-object System.Data.SqlClient.SqlParameter;
$outParameter.ParameterName = "#JobSatatus";
$outParameter.Direction = [System.Data.ParameterDirection]'Output';
$outParameter.DbType = [System.Data.DbType]'Boolean';
$sqlTableCmd.Parameters.Add($outParameter) ;
$sqlTableCmd.Connection = $sqlTableConnection
$sqlTableConnection.Open();
$sqlTableCmd.ExecuteNonQuery();
$truth = $sqlTableCmd.Parameters["#JobSatatus"].Value;
$sqlTableConnection.Close();
$truth;
but when I am running this I am getting below error
Exception calling "ExecuteNonQuery" with "0" argument(s): "The variable name '#
JobName' has already been declared. Variable names must be unique within a quer
y batch or stored procedure."
At line:15 char:33
+ $sqlTableCmd.ExecuteNonQuery <<<< ();
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Where I am doing mistake?
You should only be getting that error if you aren't re-initializing the SqlCommand object and so it has #JobName already defined.
I suspect you are getting this when you run it manually, not when you execute the script as a whole..
OR, if you are seeing it all the time, then maybe you moved this code into a function but the original $sqlTableCmd was initialized in the main code and now when this executes, it is in a different scope, but is getting confused by the one that was defined in the higher scope?
As I understand it, this line here is the one that should be setting things up fresh for you:
$sqlTableCmd = New-Object [System.Data.SqlClient.SqlCommand]

Call to EnvDTE.TextSelection.FindPattern from PowerShell fails with type mismatch

I'm building a custom scaffolder to use with MvcScaffolding. Trying to automate adding code to the beginning of a method, I came up with the following code:
$codeElement = Get-ProjectType "MyType"
foreach ($member in $codeElement.Members)
{
if ($member.Name -eq "CreateMappings")
{
$editPoint = $member.StartPoint.CreateEditPoint()
# here's where it's crashing
$editPoint.FindPattern("\{")
$editPoint.Insert("text")
}
}
When I run my custom scaffolder, FindPattern fails with
Exception calling "FindPattern" with "1" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At Path\File.ps1:62 char:26
+ $editPoint.FindPattern <<<< ("\{")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
As opposed to this macro, which runs just fine:
Sub macro()
Dim objTD As TextDocument = DTE.ActiveDocument.Object("TextDocument")
Dim editPoint As EditPoint = objTD.StartPoint.CreateEditPoint()
If (editPoint.FindPattern("\{", vsFindOptions.vsFindOptionsRegularExpression)) Then
editPoint.CharRight()
editPoint.Insert("text")
End If
End Sub
What am I doing wrong?