The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,862 other subscribers

Archive for the ‘PowerShell’ Category

PowerShell conditional and logical operators (via: PowerShell Pro!)

Posted by jpluimers on 2014/04/03

Switching between many different languages, I tend to forget the exact names and symbols of the PowerShell operators.

Most of the ones I use have to do with comparison and logic, o here they are:

Most used comparison operators

Operator Description
-eq Equal to
-lt Less than
-gt Greater than
-ge Greater than or Eqaul to
-le Less than or equal to
-ne Not equal to

Logical operators

Operator Description
-not Not
! Not
-and And
-or Or

I find it funny that you have ! and -not, but not -!. Oh well (:

Talking about logicals: PowerShell can coerce a couple of values to $false, but I’m ambivalent to use that: it does shorten code, but is very PowerShell specific.

Before I forget: an operator that is undervalued, is the -f operator that does formatting.

It uses the standard .NET formatting strings, so that is an easy way to put your .NET knowledge to use. Some further reading on the -f operator:

–jeroen

via: Conditional Logic | PowerShell Pro! :: PowerShell Pro!.

Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Tagged: , , | Leave a Comment »

Escaping in PowerShell: the back-tick ` is the escape character.

Posted by jpluimers on 2014/04/03

Somehow I always forget this:

The PowerShell escape character is the backtick “`” character.

Use it for escaping quotes within quotes, or inserting special characters.

Don’t abuse it (see the great debate: do not use it as a line continuation).

Often you can avoid line continuation characters by using splatting, which is one of the “best kept secrets” in PowerShell.

–jeroen

via: Escaping in PowerShell.

Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »

Not only only important in Windows PowerShell: “Whitespace, Please” (via: TechNet Magazine)

Posted by jpluimers on 2014/03/06

In this series of PowerShell postings, the below quote by Don Jones from Concentrated Technology is a must:

Proper formatting, including a little whitespace here and there, can make your Windows PowerShell commands a heck of a lot easier to understand.

But please don’t limit this to PowerShell code.

I see too many code at clients, even at conferences and magazine articles that are badly formatted.

Even more important: when you ask or provide for help on a forum or community site: please properly format your code examples. That makes it much easier for your audience (often yourself) to grasp the meaning.

For PowerShell: note that most syntactic elements provide for a very natural line continuation (so you can write really readable code), except for CmdLets, so often you will see { at the end of a line to make the most readable code.

–jeroen

via: Windows PowerShell: Whitespace, Please | TechNet Magazine.

Posted in .NET, Delphi, Development, PowerShell, Scripting, Software Development | Leave a Comment »

PowerShell – Special Characters And Tokens (via: Welcome to Neolisk’s Tech Blog)

Posted by jpluimers on 2014/02/27

This and next week, a few PowerShell posts appear on my blog.

Victor Zakharov, also known as Neolisk collected all the Special Characters and Tokens used in PowerShell on one page (they are scattered around the PowerShell documentation if documented at all).

The page is so immensely useful when learning PowerShell that I’m really glad I found it.

It is even better than Less Than Dot – Blog – A Cheat Sheet for All the *{_(%#$] PowerShell Punctuation.

–jeroen

via: PowerShell – Special Characters And Tokens – Welcome to Neolisk’s Tech Blog.

Posted in .NET, Development, PowerShell, Scripting, Software Development | Leave a Comment »

PowerShell: fixing script signing errors even after you had “Set-ExecutionPolicy RemoteSigned”

Posted by jpluimers on 2013/06/27

Once every while PowerShelll users get an error like this:

PS C:\bin> . .\DownloadedScript.ps1
. : File C:\bin\DownloadedScript.ps1 cannot be loaded.
The file C:\bin\DownloadedScript.ps1 is not digitally signed.
The script will not execute on the system. For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . .\DownloadedScript.ps1
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
PS C:\bin>

I recently had it too, but was surprised this happened as I took the steps in my previous blog posts on this topic: Read the rest of this entry »

Posted in CommandLine, Development, PowerShell, PowerShell, Scripting, Software Development | Leave a Comment »

.NET/C# small program that shows you your proxy settings, demonstrates LINQ to Registry, and String.Contains

Posted by jpluimers on 2013/03/05

I’ve been working at a client where they have hardened most of their systems in a not so programmer friendly way. One of the things you cannot to is start RegEdit, not even for viewing. Since I need Fiddler2 to poke through their Internet Proxy in order to get access to an external TFS server, and their machines often reboot due to maintenance cycles, sometimes my proxy settings are dead. This tiny app shows you how to get display your proxy settings, demonstrating:

Enjoy! (Note, you could have done this with PowerShell in a very easy way too, as it access the Registry just like it was a file system).

When using Fiddler, it shows output like this:

AutoConfigProxy=wininet.dll
ProxyEnable=1
MigrateProxy=1
ProxyHttp1.1=1
ProxyOverride=<-loopback>
ProxyServer=http=127.0.0.1:8888;https=127.0.0.1:8888;

LINQ to Registry

One of the drawbacks of Registry work is that you need to dispose of your keys. That is handled inside ReadOnlyAccessToRegistryKey.Run which also handles your Code Access Security. This means that the lambda expression (could just as well have been an anonymous method) can just concentrate on the LINQ stuffreturning an enumeration of anonymous types. You need the ‘let’ portion if you also want to perform ‘where’ on the values.

using System;
using System.Collections.Generic;
using System.Linq;
using BeSharp.Win32;
using Microsoft.Win32;

namespace LinqToRegistryShowProxySettings
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }

        static void run()
        {
            const string internetSettingsKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";

            ReadOnlyAccessToRegistryKey.Run(Registry.CurrentUser, internetSettingsKey,
                registryKey =>
                {
                    var keyValues = from name
                                 in registryKey.GetValueNames()
                                    //let keyValue = new { key = name, value = registryKey.GetValue(name).ToString() } // only if you need the Value in the Where, as it created for all occurences
                                    where
                                    name.Contains("proxy", StringComparison.OrdinalIgnoreCase) ||
                                    name.Contains("autoConfig", StringComparison.OrdinalIgnoreCase)
                                    select new { key = name, value = registryKey.GetValue(name).ToString() };

                    foreach (var keyValue in keyValues)
                    {
                        Console.WriteLine("{0}={1}", keyValue.key, keyValue.value);
                    }
                }
            );

        }
    }
}

ReadOnlyAccessToRegistryKey

This manages the Code Access Security since you will access the registry readonly. It also disposes the RegistryKey instance. The Code Access Security access and revert must be in the same method, so you cannot create a class that does the Assert in the constructor, and the dispose in the Disposer.

using System;
using Microsoft.Win32;
using System.Security.Permissions;
using System.Security;

namespace BeSharp.Win32
{
    public class ReadOnlyAccessToRegistryKey
    {
        public static void Run(RegistryKey hiveRegistryKey, string subKeyName, Action action)
        {
            string fullKeyName = hiveRegistryKey.Combine(subKeyName);
            RegistryPermission readRegistryPermission = new RegistryPermission(RegistryPermissionAccess.Read, fullKeyName);
            readRegistryPermission.Assert();
            try
            {
                using (RegistryKey registryKey = hiveRegistryKey.OpenSubKey(subKeyName))
                {
                    action(registryKey);
                }
            }
            finally
            {
                CodeAccessPermission.RevertAssert();
            }
        }
    }
}

Extensions for the Registry:

  • easy way to get the full names for HKLM, HKCU, etc.
  • Combine key names (and insert \ between them)
  • implements a Contains method for strings (thanks to StackOverflow); should be in a separate class, will do that in the library.
using System;
using Microsoft.Win32;

namespace BeSharp.Win32
{
    public static class RegistryExtensions
    {
        // Hives: http://en.wikipedia.org/wiki/Windows_Registry
        public readonly static string HKCC = Registry.CurrentConfig.Name;
        public readonly static string HKCR = Registry.ClassesRoot.Name;
        public readonly static string HKCU = Registry.CurrentUser.Name;
#if Obsolete
        [Obsolete]
        public readonly static string HKDD = Registry.DynData.Name;
#endif
        public readonly static string HKLM = Registry.LocalMachine.Name;
        public readonly static string HKPD = Registry.PerformanceData.Name;
        public readonly static string HKU = Registry.Users.Name;

        public static string Combine(this string keyName, string subKeyName)
        {
            string result = string.Format(@"{0}\{1}", keyName, subKeyName);
            return result;
        }

        public static string Combine(this RegistryKey registryKey, string subKeyName)
        {
            string result = registryKey.Name.Combine(subKeyName);
            return result;
        }

        public static string Combine(this RegistryKey registryKey, RegistryKey subRegistryKey)
        {
            return registryKey.Combine(subRegistryKey.Name);
        }

        //http://stackoverflow.com/questions/444798/case-insensitive-containsstring/444818#444818

        public static bool Contains(this string value, string substring, StringComparison stringComparison = StringComparison.CurrentCulture)
        {
            int index = value.IndexOf(substring, stringComparison);
            bool result = (index >= 0);
            return result;
        }
    }
}

–jeroen

Posted in .NET, .NET 4.0, .NET 4.5, C#, C# 4.0, C# 5.0, Development, PowerShell, Scripting, Software Development, Visual Studio 11, Visual Studio 2010, Visual Studio and tools | 2 Comments »

.NET/PowerShell: Get-Host, quick way to get CurrentCulture and CurrentUICulture

Posted by jpluimers on 2013/01/28

A quick and easy way of getting the CurrentCulture and CurrentUICulture is to use the get-host cmdlet from PowerShell.

This is what PowerShell 2.0 shows on my system:

C:\Users\jeroenp>powershell get-host

Name             : ConsoleHost
Version          : 2.0
InstanceId       : 1ce173fb-70a7-403b-a2bd-3800fe740f7c
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-IE
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

The SeaTools from Seagate can’t cope with that because they don’t manage the Resource Fallback Process properly.

My machine is on en-IE, as it is English, and USA as location.

The main advantage for me is to use the that it is a good mix between English and Dutch settings:

  • English language (so you get proper error messages that you can find back using Google)
  • USA as location (to force more search engines to use .com domains)
  • EUR money settings (most software in Western Europe expects EUR, but displays USD when using en-US)
  • decimal dot (far easier import/export with non-Dutch stuff)
  • DD/MM/YYYY date format (I tried ISO 8601 YYYYMMDD, but that breaks too much software)
  • 24 hour clock format (just as it should be)
  • comma list separator (too much software is not configurable to use a certain separator for CSV, especially Excel depends on the system settings for list separator and decimal)
  • metric system (just as it should be)

–jeroen

via: Get-Host.

Posted in .NET, CSV, Development, Excel, ISO 8601, Office, Power User, PowerShell, Scripting, Software Development | Leave a Comment »

Dodgy Coder: Coding tricks of game developers

Posted by jpluimers on 2012/04/26

Some very interesting tips from game development that apply juts as well to general software development.

On code health:

Now I always try to dig right down to the root cause of a bug, even if a simple, and seemingly safe, patch is available. I want my code to be healthy. If you go to the doctor and tell him “it hurts when I do this,” then you expect him to find out why it hurts, and to fix that.

Though tools like SourceMonitor can help you track your code health, the best tool is between your ears.

–jeroen

via: Dodgy Coder: Coding tricks of game developers.

Posted in .NET, Batch-Files, C#, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Delphi, Delphi x64, Delphi XE2, Development, JavaScript/ECMAScript, PHP, PowerShell, Scripting, Software Development | 1 Comment »

Powershell links (via: Scott Hanselmans 2011 Ultimate Developer and Power Users Tool List for Windows)

Posted by jpluimers on 2012/04/06

If you like .NET and scripting, then PowerShell and the PowerShell Community Extensions is what you should try:

PowerShell – The full power of .NET, WMI and COM all from a command line. PowerShell has a steep learning curve, much like the tango, but oh, my, when you really start dancing…woof. I also use PowerShell Prompt Here. Its built into Windows 7, by the way.

  • I also recommend after installing PowerShell that you immediately go get PowerTab to enable amazing “ANSI-art” style command-line tab completion.
  • Next, go get the PowerShell Community Extensions to add dozens of useful commands to PowerShell.
  • Want a more advanced GUI for PowerShell? Get the free PowerGUI.

Thanks Scott for summarizing :)

–jeroen

via: Scott Hanselmans 2011 Ultimate Developer and Power Users Tool List for Windows – Scott Hanselman.

Posted in .NET, Development, Power User, PowerShell, Scripting, Software Development | 1 Comment »

Some PowerShell SCCM links

Posted by jpluimers on 2012/03/22

http://www.powershell.nu/2010/10/07/powershell-sccm-client/

http://www.powershell.nu/tag/sccm-2007/

 

http://devinfra-us.blogspot.com/2008/04/sccm-and-powershell-part-1.html

http://devinfra-us.blogspot.com/2008/04/sccm-and-powershell-part-2.html

 

http://thepowershellguy.com/blogs/posh/archive/2008/05/16/sccm-and-powershell-series-using-my-powershell-wmi-explorer.aspx

http://thepowershellguy.com/blogs/posh/archive/tags/WMI+Explorer/default.aspx

http://thepowershellguy.com/blogs/posh/archive/2007/03/22/powershell-wmi-explorer-part-1.aspx

 

http://tfl09.blogspot.com/2010/03/sccm-powershell-module.html

 

http://www.snowland.se/2010/03/10/sccm-module-for-powershell/

http://www.snowland.se/sccm-posh/

 

Posted in .NET, PowerShell, Scripting, Software Development | Leave a Comment »