Enable tls1.2 on windows 7 with powershell 2.0 - powershell

Cannot enable TLS1.2 on Windows 7SP1 with powershell 2.0 :
PS C:\Windows\system32> $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.8806
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
I guess P.Sv2.0 is using .NET v2.0 :
PS C:\Windows\system32> $PSVersionTable.CLRVersion
Major Minor Build Revision
----- ----- ----- --------
2 0 50727 8806
PS C:\Windows\system32> [System.Environment]::Version
Major Minor Build Revision
----- ----- ----- --------
2 0 50727 8806
Moreover, the following .NET versions are installed on this system :
PS C:\Windows\system32> Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version, Release -ErrorAction 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select Version, Release, PSChildName
Version Release PSChildName
------- ------- -----------
2.0.50727.5420 v2.0.50727
3.0.30729.5420 v3.0
3.0.4506.5420 Windows Communication Foundation
3.0.6920.5011 Windows Presentation Foundation
3.5.30729.5420 v3.5
4.8.03761 528049 Client
4.8.03761 528049 Full
4.0.0.0 Client
However, I cannot set TLSv1.2 with that configuration :
PS C:\Windows\system32> [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Exception lors de la définition de « SecurityProtocol » : « Impossible de convertir la valeur Null en type « System.Net.SecurityProtocolType » en raison de valeurs d'énumération non valides. Spécifiez l'une des valeurs d'énumération suivantes et réessayez. Les valeurs d'énumération possibles sont « Ssl3, Tls ». »
Au niveau de ligne : 1 Caractère : 28
+ [Net.ServicePointManager]:: <<<< SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
PS C:\Windows\system32> [enum]::GetNames([Net.SecurityProtocolType])
Ssl3
Tls
PS C:\Windows\system32>
EDIT 0 : #mclayton Setting up [Net.ServicePointManager]::SecurityProtocol to the integer value of 3072 does not work either :
PS C:\Windows\system32> [Net.ServicePointManager]::SecurityProtocol = 3072
Exception lors de la définition de « SecurityProtocol » : « Impossible de convertir la valeur « 3072 » en type « System.Net.SecurityProtocolType » en raison de valeurs d'énumérati
on non valides. Spécifiez l'une des valeurs d'énumération suivantes et réessayez. Les valeurs d'énumération possibles sont « Ssl3, Tls ». »
Au niveau de ligne : 1 Caractère : 28
+ [Net.ServicePointManager]:: <<<< SecurityProtocol = 3072
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Can you help me ?

To expand on #Abraham Zinala's comment, the Tls12 enumeration value wasn't added to the System.Net.SecurityProtocolType enum until Dot Net Framework version 4.5 (see https://learn.microsoft.com/en-us/dotnet/api/system.net.securityprotocoltype?view=netframework-4.5).
Your PowerShell 2.0 install is using a lower version than this, so it can't resolve the value of [Net.SecurityProtocolType]::Tls12.
What you can do instead is use the integer value of the enum:
# assign the magic number to a variable for clarity
$tls12 = 3072;
[Net.ServicePointManager]::SecurityProtocol = $tls12;

Related

"Set-PSDebug -Trace 2" causes a variable assignment to fail

This two-line PS script fails if debug tracing is set to level 2:
Set-PSDebug -Trace 2
$Process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
It fails with this error:
Cannot convert value to type System.String.
At line:1 char:1
+ $Process = Start-Process -FilePath ping -ArgumentList localhost -NoNe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromAnyTypeToString
If I set -Trace 1 or no tracing, it works. If I don't try to assign $Process in -Trace 2, it works.
I wouldn't expect Set-PSDebug to modify the execution environment, but that seems to be the case here. Is this expected behavior? Or perhaps a bug in PowerShell?
Version information:
PS C:\Users\Eric> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.19041.2364
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.2364
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

PowerShell cmdlet Test-NetConnection not available

I noticed that the cmdlet Test-NetConnection was not installed on Server 2012. Since Server 2012 comes with PowerShell version 3 so I thought it might help to update to the latest version 5.1.
I did the update but the cmdlet Test-NetConnection is still not available.
Only Test-Connection is present, but I need Test-NetConnection to test ports.
How can I get Test-NetConnection now?
PS C:\Windows\system32> $PSVersionTable
Name Value
---- -----
PSVersion 5.1.14409.1005
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14409.1005
CLRVersion 4.0.30319.34209
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
PS C:\Windows\system32> Get-Command Test-NetConnection
Get-Command : The term 'Test-NetConnection' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-Command Test-NetConnection
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
The availability of many cmdlets is tied to the Windows version, not the PowerShell version. If you can't upgrade your Windows version you can't have Test-NetConnection.
You could use a commandline port scanner like nmap or scanline for port tests, or you could connect to the port(s) yourself:
function Test-Port($server, $port) {
$client = New-Object Net.Sockets.TcpClient
try {
$client.Connect($server, $port)
$true
} catch {
$false
} finally {
$client.Dispose()
}
}
$ipaddress = "serverName"
$port = "portNum"
$connection = New-Object System.Net.Sockets.TcpClient($ipaddress, $port)
if ($connection.Connected) {
Write-Host "Success"
} else {
Write-Host "Failed"
}

Error PSRemoting using Session and CredSSP

I use Windows 8.1 Enterprise 64 bit and Powershell 4.0.
I want execute powershell remoting and using authentication CredSSP.
I open Console Powershell, run as Administrator, and execute Enter-PSSession command to connect to remote computer.
But I get error about connection.
PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
Anyways, I test command from Windows XP and Windows 7, and connection is OK.
PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
[dc]: PS C:\Users\Administrator\Documents> exit
Now, I test in Windows 8.1.
I test command enable-psremoting and I get error:
PS C:\Windows\system32> Enable-PSRemoting -force
WinRM ya está configurado para recibir solicitudes en este equipo.
WinRM has been updated to receive requests.
Set-WSManQuickConfig : <f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="2"
Machine="localhost"><f:Message><f:ProviderFault provider="Config provider"
path="%systemroot%\system32\WsmSvc.dll"><f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"
Code="2" Machine="MYCOMPUTERW8.mycompany.net"><f:Message>Unable to check the status of the firewall.
</f:Message></f:WSManFault></f:ProviderFault></f:Message></f:WSManFault>
En línea: 69 Carácter: 17
+ Set-WSManQuickConfig -force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Set-WSManQuickConfig], InvalidOperationException
+ FullyQualifiedErrorId : WsManError,Microsoft.WSMan.Management.SetWSManQuickConfigCommand
Same error using the command Enable-PSRemoting -force -SkipNetworkProfileCheck.
I test command winrm quickconfig and I get error:
PS C:\Windows\system32> winrm quickconfig -force
WinRM service is already running on this machine.
WSManFault
Message
ProviderFault
WSManFault
Message = Unable to check the status of the firewall.
Nº de error: -2147024894 0x80070002
The system cannot find the file specified.
I have SmartScreen and Firewall disabled in my Windows 8.1. (I have Symantec Endpoint protection disabled)
Any suggestions?
update:
I test those commads:
PS C:\> Enable-PSRemoting -SkipNetworkProfileCheck -Force
PS C:\>Set-NetFirewallRule –Name "WINRM-HTTP-In-TCP-PUBLIC" –RemoteAddress Any
but I get error:
PS C:\Windows\system32> Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
Set-NetFirewallRule : No se encontraron objetos MSFT_NetFirewallRule cuya propiedad 'InstanceID' sea igual a
'WINRM-HTTP-In-TCP-PUBLIC'. Compruebe el valor de la propiedad e inténtelo de nuevo.
En línea: 1 Carácter: 1
+ Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (WINRM-HTTP-In-TCP-PUBLIC:String) [Set-NetFirewallRule], CimJobException
+ FullyQualifiedErrorId : CmdletizationQuery_NotFound_InstanceID,Set-NetFirewallRule
Reference: http://technet.microsoft.com/en-us/library/hh849694.aspx
Update 2
Now,I execute Net stop MPSSVC (Windows Firewall Service), and I get this error
Enter-PSSession -ComputerName DC -credential dersg.com\Administrator
Enter-PSSession : Connecting to remote server DC failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
En línea: 1 Carácter: 1
+ Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (DC:String) [Enter-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
Update 3.
I execute this command (https://stackoverflow.com/a/22816386/206730)
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell
Now, I execute the command and all is OK
PS C:\Documents and Settings\kiquenet> Enter-PSSession -ComputerName DC -credential devrsg.com\Administrator
[dc]: PS C:\Users\Administrator\Documents> exit
Now, I enable CredSSP in server and in client:
Enable-WSManCredSSP -Role Server –Force
Enable-WSManCredSSP -Role Client -DelegateComputer * -Force
Now, I test command using CredSSP:
$serverName = "DC"
$username = "devrsg\Administrator"
$password = "xxxxxx"
$adjPwd = $password | ConvertTo-SecureString -asPlainText -Force
$testCred = (New-Object System.Management.Automation.PSCredential($username,$adjPwd))
$scriptBlock = {
Write-Host ("hello, world: {0}, {1}" -f $env:USERNAME, (hostname))
}
Invoke-Command $scriptBlock -computername $serverName -credential $testCred -Authentication Credssp
and I get the error:
PS C:\> .\testRemoteCredSSP.ps1
[DC] Error de conexión al servidor remoto DC. Mensaje de error: El cliente WinRM no puede procesar la solicitud. Una
directiva de equipo no permite delegar credenciales de usuario en el equipo de destino porque éste no es de confianza.
La identidad del equipo de destino se puede comprobar si configura el servicio WSMAN para usar un certificado válido
con el siguiente comando: winrm set winrm/config/service '#{CertificateThumbprint="<huellaDigital>"}' O bien puede
comprobar en el Visor de eventos si hay un evento que especifique que no se pudo crear el siguiente SPN:
WSMAN/<FQDNdelEquipo>. Si encuentra este evento, puede crear manualmente el SPN con setspn.exe . Si el SPN existe,
pero CredSSP no puede usar Kerberos para validar la identidad del equipo de destino y desea permitir la delegación de
credenciales de usuario en el equipo de destino, use gpedit.msc y mire la siguiente directiva: Configuración del
equipo -> Plantillas administrativas -> Sistema -> Delegación de credenciales -> Permitir credenciales nuevas con
autenticación solo NTLM de servidor. Compruebe que esté habilitada esta opción y configurada con el correspondiente
SPN para el equipo de destino. Por ejemplo, para un nombre de equipo de destino "miservidor.dominio.com", el SPN puede
ser alguno de los siguientes: WSMAN/miservidor.dominio.com o WSMAN/*.dominio.com. Pruebe de nuevo la solicitud después
de realizar estos cambios. Para obtener más información, consulte el tema de la Ayuda about_Remote_Troubleshooting.
+ CategoryInfo : OpenError: (DC:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : -2144108124,PSSessionStateBroken
English message:
Enter-PSSession : Connecting to remote server failed with the following error me
ssage : The WinRM client cannot process the request.
A computer policy does not allow the delegation of the user credentials to the target computer because the computer is not trusted. The identity of the target computer can be verified if you configure the WSMAN service to use a valid certificate using the following command: winrm set winrm/config/service '#{CertificateThumbprint="<thumbprint>"}'
Or you can check the Event Viewer for an event that specifies that the following SPN could not be created: WSMAN/<computerFQDN>. If you find this event, you can manually create the SPN using setspn.exe .
If the SPN exists, but CredSSP can not use Kerberos to validate the identity of the target computer and you still want to allow the delegation of the user credentials to the target computer, use gpedit.msc and look at the following policy: Computer Configuration -> Administrative Templates -> System -> Credentials Delegation -> Allow Fresh Credentials with NTLM-only Server Authentication.
Verify that it is enabled and configured with an SPN appropriate for the target computer.
For example, for a target computer name "myserver.domain.com", the SPN can be one of the following: WSMAN/myserver.domain.com or WSMAN/*.domain.com.
Try the request again after these changes.
For more information, see the about_Remote_Troubleshooting Help topic.
CredSSP will not send your credentials to a machine it does not trust, you can add a trust with the remote server in two ways.
Set the GPO setting in Admin templates/System/Credentials Delegation/Allow delegating fresh credentials to either the server (WSMAN/dc.domain.com) or wildcard for everything in the domain (WSMAN/*.domain.com).
Get the Certificate thumbprint for that machine and run winrm set winrm/config/service '#{CertificateThumbprint="<thumbprint>"}'.
You can get the Certificate thumbprints of the server by running: Get-ChildItem "Cert:\LocalMachine\Remote Desktop\"

Add-PsSnapin WebAdministration in Windows7

I want to use PowerShell to administer my IIS7 on Windows7 64 bits.
I try install IIS7 Powershell snap-in http://www.iis.net/download/PowerShell
I "Run as administrator", then typing the command listed below: msiexec /I iis7psprov_x64.msi but I get this error message: "The PowerShell snap-in is part of Windows Operating System. Please install via Programs and Features or Server Manager"
I think this particular feature is not necessary to load the WebAdministration module but I active all options in "Programs and features |
turn Windows features on or off | IIS | Web Management Tools | IIS Management Scripts and Tools
I do those checks:
1.) Power-Shell is installed
PS C:\Program Files\IIS> $Host.Version
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
PS C:\Program Files\IIS> $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.5448
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
PS C:\Program Files\IIS> get-host
Name : ConsoleHost
Version : 2.0
InstanceId : 445ad8f5-87fc-48f7-b010-f7faf948b86c
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : es-ES
CurrentUICulture : es-ES
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
2.) Set-ExecutionPolicy -ExecutionPolicy {Your Execution Policy}
PS C:\Program Files\IIS> get-ExecutionPolicy
Unrestricted
3.)Import-Module WebAdministration
PS C:\Program Files\IIS> Import-Module WebAdministration
PS C:\Program Files\IIS>
4.) C:\Windows\System32\WindowsPowerShell\v1.0\Modules\WebAdministration path exists
5.) Modules and Snap-in
PS C:\Program Files\IIS> get-module -listavailable
ModuleType Name ExportedCommands
---------- ---- ----------------
Manifest AppLocker {}
Manifest BitsTransfer {}
Manifest PSDiagnostics {}
Manifest TroubleshootingPack {}
Manifest WebAdministration {}
PS C:\Program Files\IIS> Get-PSSnapin -Registered
Name : SqlServerCmdletSnapin100
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.
Name : SqlServerProviderSnapin100
PSVersion : 2.0
Description : SQL Server Provider
Name : TfsBPAPowerShellSnapIn
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes Team Foundation Server cmdlets.
PS C:\Program Files\IIS> get-pssnapin
Name : Microsoft.PowerShell.Diagnostics
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene cmdlets de Eventos de Windows y de contador de rendimient
o.
Name : Microsoft.WSMan.Management
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene cmdlets (como Get-WSManInstance y Set-WSManInstance) que
usa el host de Windows PowerShell para administrar operaciones WSMan.
Name : Microsoft.PowerShell.Core
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene cmdlets usados para administrar los componentes de Window
s PowerShell.
Name : Microsoft.PowerShell.Utility
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene cmdlets de utilidad que sirven para manipular datos.
Name : Microsoft.PowerShell.Host
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene cmdlets (como Start-Transcript y Stop-Transcript) proporc
ionados para su uso con el host de la consola de Windows PowerShell.
Name : Microsoft.PowerShell.Management
PSVersion : 2.0
Description : El complemento Windows PowerShell contiene cmdlets de administración para administrar los componentes de
Windows.
Name : Microsoft.PowerShell.Security
PSVersion : 2.0
Description : Este complemento de Windows PowerShell contiene varios cmdlets para la administración de la seguridad de
Windows PowerShell.
PS C:\Program Files\IIS> [System.Reflection.Assembly]::LoadFrom( "C:\windows\system32\inetsrv\Microsoft.Web.Administration.dll" )
GAC Version Location
--- ------- --------
True v2.0.50727 C:\Windows\assembly\GAC_MSIL\Microsoft.Web.Administration\7.0.0.0__31bf3856ad364e35\Microsoft....
PS C:\Program Files\IIS> (New-Object Microsoft.Web.Administration.ServerManager)
ApplicationDefaults : Microsoft.Web.Administration.ApplicationDefaults
ApplicationPoolDefaults : Microsoft.Web.Administration.ApplicationPoolDefaults
ApplicationPools : {DefaultAppPool}
SiteDefaults : Microsoft.Web.Administration.SiteDefaults
Sites : {Default Web Site}
VirtualDirectoryDefaults : Microsoft.Web.Administration.VirtualDirectoryDefaults
WorkerProcesses : {}
PS C:\Program Files\IIS> (New-Object Microsoft.Web.Administration.ServerManager).Sites
ApplicationDefaults : Microsoft.Web.Administration.ApplicationDefaults
Applications : {Default Web Site/}
Bindings : {[http] *:80:}
Id : 1
Limits : Microsoft.Web.Administration.SiteLimits
LogFile : Microsoft.Web.Administration.SiteLogFile
Name : Default Web Site
ServerAutoStart : True
State : Started
TraceFailedRequestsLogging : Microsoft.Web.Administration.SiteTraceFailedRequestsLogging
VirtualDirectoryDefaults : Microsoft.Web.Administration.VirtualDirectoryDefaults
Attributes : {name, id, serverAutoStart, state}
ChildElements : {bindings, limits, logFile, traceFailedRequestsLogging...}
ElementTagName : site
IsLocallyStored : True
Methods : {Start, Stop}
RawAttributes : {[name, Default Web Site], [id, 1], [serverAutoStart, True], [state, 1]}
Schema : Microsoft.Web.Administration.ConfigurationElementSchema
6.) I try in ps1 file
$succeeded = import-module WebAdministration
Write-Host $succeeded
if (($succeeded -ne $null) -and ($succeeded.GetType() -eq [System.Exception]))
{
#Could not import, trying to snapin
add-pssnapin WebAdministration
}
$succeeded is null, and "add-pssnapin WebAdministration" produces error message: Add-PSSnapin : The Windows PowerShell snap-in 'WebAdministration' is not installed on this machine.
PS C:\Program Files\IIS> Add-PSSnapin WebAdministration
Add-PSSnapin : El complemento WebAdministration de Windows PowerShell no está instalado en este equipo
En línea: 1 Carácter: 13
+ Add-PSSnapin <<<< WebAdministration
+ CategoryInfo : InvalidArgument: (WebAdministration:String) [Add-PSSnapin], PSArgum
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand
any suggestions about it ? Why fails Add-PSSnapin WebAdministration ?
UPDATE:
I'm confused when exactly do I use Add-PSSnapin and when do I use Import-Module
http://social.technet.microsoft.com/Forums/en/ITCG/thread/3e1ca6e1-d197-4c04-a145-1e922814a618
surely, WebAdministration is only Module, and has'nt PSSnapin. May be...
References:
PowerShell IIS Snapin
Cannot install Powershell Snap-in
http://www.iis.net/download/PowerShell
http://learn.iis.net/page.aspx/429/installing-the-iis-powershell-snap-in/
http://learningpcs.blogspot.com.es/2010/08/powershell-iis-7-webadministration.html
Versión de PowerShell instalada
Determine installed PowerShell version
Here is the function I have in my profile.ps1 for loading the WebAdmin module. It covers IIS 7 and 7.5
# Web administration is loaded as a module on Windows 2008 R2 but as a set of snapins
# for Windows 2008 (not R2)
function Util-Load-Web-Administration
{
$ModuleName = "WebAdministration"
$ModuleLoaded = $false
$LoadAsSnapin = $false
if ($PSVersionTable.PSVersion.Major -ge 2)
{
if ((Get-Module -ListAvailable | ForEach-Object {$_.Name}) -contains $ModuleName)
{
Import-Module $ModuleName
if ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName)
{ $ModuleLoaded = $true } else { $LoadAsSnapin = $true }
}
elseif ((Get-Module | ForEach-Object {$_.Name}) -contains $ModuleName)
{ $ModuleLoaded = $true } else { $LoadAsSnapin = $true }
}
else
{ $LoadAsSnapin = $true }
if ($LoadAsSnapin)
{
try
{
if ((Get-PSSnapin -Registered | ForEach-Object {$_.Name}) -contains $ModuleName)
{
if ((Get-PSSnapin -Name $ModuleName -ErrorAction SilentlyContinue) -eq $null)
{ Add-PSSnapin $ModuleName }
if ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName)
{ $ModuleLoaded = $true }
}
elseif ((Get-PSSnapin | ForEach-Object {$_.Name}) -contains $ModuleName)
{ $ModuleLoaded = $true }
}
catch
{
Write-Error "`t`t$($MyInvocation.InvocationName): $_"
Exit
}
}
}

How use system.tuple in powershell?

Just for curiosity, it's not a 'I must have it', but how declare a tuple using system.tuple class in powershell?
I'm using powershell.exe.config to load framework 4.0 but I'm not able to create a tuple.
Trying this:
PS C:\ps1> $a = [System.Tuple``2]::Create( "pino", 34)
Chiamata al metodo non riuscita. [System.Tuple`2] non contiene un metodo denominato 'Create'.
In riga:1 car:31
+ $a = [System.Tuple``2]::Create <<<< ( "pino", 34)
+ CategoryInfo : InvalidOperation: (Create:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
sorry for Italian sample...
Thank you for help.
EDIT:
if i try:
PS C:\ps1> $a = [System.Tuple]::Create(34,"pino")
Impossibile trovare un overload per "Create" e il numero di argomenti: "2".
In riga:1 car:28
+ $a = [System.Tuple]::Create <<<< (34,"pino")
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Here is a way
PS> $a = New-Object 'Tuple[string,int]'("Jack", 78)
PS> $a
Item1 Item2
----- -----
Jack 78
Another one
PS> $dpt = New-Object 'Tuple[string,string,int]'("Cantal", "Aurillac", 15)
PS> $dpt.Item2
Aurillac
------EDIT------
Recall
to see which CLR you are using, just use $PSVersionTable
PS C:\> $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.4959
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
if you want PowerShell to start using CLR 4.0 you have to put the file powershell.exe.config in the folder $PSHOME (C:\Windows\System32\WindowsPowerShell\v1.0)
powershell.exe.config :
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
Result :
PS C:\Users\JPB> $PSVersionTable
Name Value
---- -----
PSVersion 2.0
PSCompatibleVersions {1.0, 2.0}
BuildVersion 6.1.7600.16385
PSRemotingProtocolVersion 2.1
WSManStackVersion 2.0
CLRVersion 4.0.30319.225
SerializationVersion 1.1.0.1