Category Archives: PowerShell

How to filter particular TypeScript errors in build result

Hi interwebz.
I just want to share this short poor man’s fix when migrating TypeScript to filter out some particular errors in TypeScript build.

Why the hell you (might) need it?

So what would be the common use case , why to bother mask/mute errors on build? Compile is the first test our code need to undergo, like first pass of “unit tests”.

Our situation : currently we have a lot of .js files that let’s say most of the time worked and we need to iterate on way to migrate fully from JavaScript only to TypeScript only. So we rename .js to .ts and then we ran into errors like (among others) :

  1. error TS2365 Operator ‘>=’ cannot be applied to types ‘string’ and ‘number’.
  2. error TS2365 Operator ‘==’ cannot be applied to types ‘string’ and ‘number’.
  3.  error TS2345 Argument of type ‘number’ is not assignable to parameter of type ‘string’.

Yes indeed these are against the “logic” of TypeScript – bring types to JavaScript. But I know I want it there for some short timespan. Just to test. I don’t want to wade through 1500 same errors I know I will have to fix, but among them TypeScript also tells me big and real problems, but buried under many same errors about types.

We are not alone in this, more ppl write about it here :
https://github.com/Microsoft/TypeScript/issues/6114

https://github.com/Microsoft/TypeScript/issues/4094

https://github.com/Microsoft/TypeScript/issues/9448

and also here https://github.com/Microsoft/TypeScript/issues/11051

Solution :

So the solutions vary from custom branch of TypeScript as such to stupid grep on the command line output. And since I am on Windows 10 (my dev box) , I chose to stick with PowerShell so this is snippet that should do the job.

Lets say we want to mute TS2365 and TS2345 errors and your TS build gulp task has name someTSBuildTaskName.

PS script – output to some file :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345" | Out-File "grepts.txt"

PS script – output just to console (just drop the last part after pipe) :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345"

PS: I am calling here the gulp task without gulp installed with -g flag (global) so you can just call

gulp someTSBuildTaskName

with globally installed gulp and you are also good to go.

Found any better solution? Pls let us know in comments! 🙂

AD: you can also use this console log parser on Jenkins:

Regular Expression :

([\w\\\.]+)\((\d+),\d+\):\s+\w+\s+((?!TS2365|TS2345)\w+):\s+(.*)$

Mapping Script :

import hudson.plugins.warnings.parser.Warning

String fileName = matcher.group(1)
String line = matcher.group(2)
String category = matcher.group(3)
String message = matcher.group(4)

return new Warning(fileName, Integer.parseInt(line), "TS Error", category, message);

and plug this into your build pipeline.

How to use NuGet packages even with PowerShell projects with Visual Studio 2015

Most of developers doesn’t use PowerShell on day to day basis, but Microsoft in Visual Studio 2015 made it 1rst class citizen by making PowerShell Tools for Visual Studio 2015 plugin optional on install. (Before that, we had just optional plugin for VS 2013 and VS2012 by same author).

More on this here : http://blogs.msdn.com/b/powershell/archive/2015/04/19/do-not-delete-publish-powershell-tools-for-visual-studio-now-available.aspx

and here

https://channel9.msdn.com/Shows/MsftPowerShell/Visual-Studio-2015-PowerShell-Tools-Overview

and would all be good, but there is still one downside and that is :

you can’t use NuGet packages in PowerShell projects in VS2015 (at least that is how stuff works on my machine). I am really not sure, if this “feature” was introduced with VS 2015 or with NuGet 3.x, but my project worked with VS 2013 + plugin for VS2013.

On my dev box I get error like this one when trying to right clicking References and Manage NuGet Packages…:

powershell nuget error menu

and like this one using Package Manager Console :

powershell nuget error console

The problem is, that it seems like NuGet doesn’t support .pssproj projects, so however your project contains packages.config it will be ignored and you will not be able to update packages. You will have track what you installed and reinstall same version, but you will not be able to update these. Which is quite shame.

There is currently no simple solution to this but you can do these workarounds :

Solution 1 :

If you have small number of packages, install them by hand from command line with help of command line NuGet.

  • download NuGet.exe from https://www.nuget.org/  ,
  • cd to directory where NuGet.exe is (or if you have NuGet.exe in your PATH, you don’t need to cd),
  •  nuget install package_name -o “path_to_packages_folder_or_folder_where_to_store_packages” – which will install latest version of package you want,
  • use the package

You can indeed make a shell script for this. With this solution, the shell script will hold the information about packages you need/want to have installed.

Solution 2 :

If for some reason you want to preserve packages.config file, than you will have to manually update latest versions of packages it contains (since update is not working). Then this file will bear the information about what packages NuGet will install/restore. If this is your way to go, you can follow these steps :

  • download NuGet.exe from https://www.nuget.org/  ,
  • cd to directory where NuGet.exe is (or if you have NuGet.exe in your PATH, you don’t need to cd),
  • update the packages.config file with latest version numbers from https://www.nuget.org/  ,
  • nuget install “path_to_packages.config\packages.config” -o “path_to_packages_folder_or_folder_where_to_store_packages”,
  • use the package

All these solutions are for for scenarios where you need NuGet packages in Packages folder (inside solution folder).

But what there is another way, if you can install chocolatey on you dev box and if you can find in chocolatey repository the package you need.

Then you can do this :

Solution 3 :

  • install Chocolatey from https://chocolatey.org/,
  • run “choco install package_name” (choco should also make sure your new tool will be in PATH),
  • use the package

I would suggest you will make a shell script and automate install of your packages. Again, the file that will hold the information about packages is the shell script.

And if you ask, what is the reason for all this, what NuGet package you might want to use in PowerShell project, my answer is : https://github.com/pester/Pester

Hope this helps,

Dušan

How to create simple DTO “object” in PowerShell

Why this sample :

I needed simple and short solution for creating custom DTO objects with simple logic for later reuse elsewhere. Function essentialy takes “constructor” argument and returns object with properties that have getters with small piece of logic and are using constructor parameter. No inheritance, no access modificators or any advanced OOP stuff. Just above mentioned functionality as “helper”. There are many other way of creating object in PowerShell (that also vary from PowerShell version to version – I used v4 here), but I needed something I can have in a function to call several times in a loop and create array of these objects.

Code :

function getMeMyObject {
	[CmdletBinding()]
	Param([Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)][string]$propertyName)

    Process {
        $retObj = @{}

        $retObj | Add-Member -Name Prop1 -MemberType ScriptProperty -Value {
            'Prop1-' + $propertyName
        }.GetNewClosure()

        $retObj | Add-Member -Name Prop2 -MemberType ScriptProperty -Value {
            'Prop2-' + $propertyName
        }.GetNewClosure()

        return $retObj
    }
}

Usage :

Just call the function and assign the output to the variable of your choice.

$yourVar = getMeMyObject -propertyName 'qqqq'

I strongly typed variable -propertyName so it has to be string, but it’s just for purpose of this demo, feel free to modify this snippet as you like/need.

There is only one small thing worth notice, the “secret” why at runtime we can access the input variable -propertyName is quite simple. I am calling

.GetNewClosure()

after each getter code, which is capturing all the variables. Without this the property

$propertyName

would be empty but code will not fail which is quite tricky I would say. You can try for your self 🙂

More on this method here : http://blogs.msdn.com/b/powershell/archive/2009/03/27/get-closure-with-getnewclosure.aspx and here http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/10/hey-scripting-guy-weekend-scripter-getting-closure-with-the-getnewclosure-method.aspx.

Other great article can be found here : http://www.padisetty.com/2014/05/all-about-powershell-scriptblock.html

Two possible versions of calling :

You can use two methods of calling the code. Either use dedicated .ps1 file with function in it, or inline copy a script block that creates variable you can call, choice is yours.

Code repo :

Feel free to play here : https://github.com/rostacik/PSCreateObjectFromFunctionSample

Simple PowerShell snippet to search file or array for content

Since I play these days a lot with PowerShell I need from time to time some simple functionality. Sometimes dead simple. Like today , snippet to search file content or array of data if you will and return true/false if text is present in it.

function File-Contains-Row {
	[CmdletBinding()]
	Param([array]$fileContent, [string]$searchedString)

	Process {
		#is there any string we search for in any of the rows?
		[array]$resArray = $fileContent | where { $_ | Select-String –caseSensitive -Pattern $searchedString }

		if ($resArray.Count -eq 0) {
			return $false
		} else {
			return $true
		}
	}
}

As a project, you can find it here :
https://github.com/rostacik/PSSearchFileOrArrayForContent

.ps1 file is here :
https://github.com/rostacik/PSSearchFileOrArrayForContent/blob/master/PSSearchFileOrArrayForContent/Array-Contains-Row.ps1

Enjoy.

How to “grep” for multiple strings in files on Windows with PowerShell

So you want to search for multiple strings in your files on Windows?

Sure, you can do the job several ways, but if you have PowerShell installed on your box, you might use this snippet :

get-childitem "folder_where_to_look" -include *.txt -rec | where { $_ | Select-String -Pattern 'find_me_1' } | where { $_ | Select-String -Pattern 'find_me_2' }

Basically what this snippet does this :

  • find all .txt files in supplied folder and recursively in all subfolders, pass this list to
  • first pattern search for “find_me_1 string, than pass list of matching files with this string to
  • second pattern search
  • pass result to console

Nice this is, that you can also use RegEx in patterns that will be searched for and you can also dump found files to file for later use.

Hope this helps someone.

PowerShell Tools for Visual Studio 2013 – unable to run and/or debug PowerShell script – execution policies problem

The problem :

Some time ago I wrote this article :

http://rostacik.net/2013/11/13/powershell-tools-for-visual-studio-2012-problem-ps1-cannot-be-loaded-because-running-scripts-is-disabled-on-this-system-for-more-information-see-about_execution_policies

about my problems running and debugging PowerShell scripts in VS 2012 with help of http://visualstudiogallery.msdn.microsoft.com/e3f9d3bf-e630-4b3e-968a-f86ac67b836c – PowerShell Tools for Visual Studio 2012 – wonderful tool by Adam Driscoll.

Currently after switching to Windows 8.1 + VS 2013 I reopened my project and started to work with new version of PowerShell Tools for Visual Studio 2013 – http://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597

And  I was shocked! The very same problem got even worse! I wasn’t able to fix this with steps in the article. I was able to edit scripts in VS but still, I wasn’t able to debug my stuff. After some messing with other stuff I found out, that the very same problem was here some time ago and is already fixed by another people – with help of this link : http://davidfrette.wordpress.com/2011/01/20/creating-powershell-pre-build-and-post-build-events-for-visual-studio-projects/ (yes, it was the same back then in 2011)….

Solution to the problem is quite simple :

PowerShell installs in one package however there are two versions : x86 and x64 (as separate executables that I had to find on my drive) and as you might guessed correctly : they don’t share the same Get-ExecutionPolicy setting!

So you need to :

  • Find x64 version of PowerShell
  • set ExecutionPolicy

On my machine while running VS2013 as 32b executable :

vs 2013 32b

And with the starting position like this (please note that there is no difference in title bars, you only can tell what PS you are using by the path):

ps two versions

 

I Set-ExecutionPolicy to RemoteSigned like this :

ps two versions 64 fixed

 

and the output in VS 2013 changed from this :

vs ps error

 

to this :

vs ps fixed

 

No PowerShell package on my box in add/remove programs :

I have to state 1 small thing at the end, I didn’t installed PowerShell on my box as a downloaded .exe file.  If I search my installed programs, I see this (nothing) :

ps uninstall

 

While I can see PowerShell 2.0 in add/remove feature in Windows 8.1 like this :

ps feature

So your box setup may vary. If so, please comment below for others… Thank you! 🙂

Hope this helps/saves you some time….

PowerShell Tools for Visual Studio 2012 problem – .ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies

Solution to your problem :

For some reason,  account on which you run VS on and on which VS hosts PowerShell has restricted ExecutionPolicy (you can type Get-ExecutionPolicy , select the text and hit CTRL+F8 and should see Restricted as the answer).

So the solution is simple (should be): override the settings and set it to RemoteSigned with this command :

Set-ExecutionPolicy RemoteSigned

select the text, hit CTRL+F8. Now hitting F5 should make your PS behave.

(Alternatively Unrestricted is also viable option, but this is considered unsafe. More on this here : http://technet.microsoft.com/en-us/library/ee176961.aspx)

More on the topic :

I wanted to create some PowerShell script and I thought there has to be something better than PowerShell ISE (sry, I am just too used to VS and debugger and all that goodness I have at my disposal) so I discovered this wonderful plugin for VS 2012 – PowerShell Tools for Visual Studio – http://visualstudiogallery.msdn.microsoft.com/c9eb3ba8-0c59-4944-9a62-6eee37294597 and all worked as expected, until (as far as I remember) I restarted OS and had this strange error in VS in my output window :

Error: File C:\users\your_name\documents\visual studio 2012\Projects\PowerShell Script Project1\PowerShell Script Project1\Script.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.

The program ‘PowerShell Script’ has exited with code 0 (0x0)
(Small side note here to make you more puzzled but this might also help you in some way : I work in a company where admins takes security seriously and our “normal” day to day accounts are restricted and don’t have access to this and that so we have another accounts to install sw, make changes to the system, etc. I need to run my VS under this account, not my own.)
Great, no what? There is a link to documentation about what execution policies are and how to set them, etc, I changed it from vanilla restricted state to RemoteSigned and the very same .ps1 file worked after I set RemoteSigned for my and my admin account. It looks like PS stores policies per user in registry. More on this here : http://dusan.kuzmanovic.net/2012/01/04/powershell-execution-policy/

 

Than I had “brilliant” idea to try PowerShell commands in NuGet Package Manager Console because it is using PowerShell under the hood, I was just looking for some prompt to query the ExecutionPolicy. And the magic happened, after query the PowerShell worked!!!! Brilliant but this is just workaround and not the solution.

 

After this the best idea seemed to contact the author so I mailed directly Adam Driscoll (apologies for distraction) which led to few discoveries like :
  • Writing some text in the .ps1 file in VS and selecting some code and right click reveals Execute selection option that is able to run your code event if it fails running it F5,
  • Adam downloaded in his spare time NuGet sources and it looks like : “NuGet sets the process scoped execution policy to RemoteSigned when it is initialized. “

So next logical step would be to try to run Set-ExecutionPolicy from VS to set it for account that VS is using to run PowerShell. And it looks like it is working.

Enjoy guys and thanks Adam for your plugin and your time.

How to split string in PowerShell with multiple delimiters

Hello world.

I just wanted to share with you one simple stupid snippet (please note, I am PowerShell newbie so have mercy and if there is any better way, please share in comments, thank you).

Because in my current work we need to parse and update some .aspx files (I will try to publish this later on my github),  I am fiddling a bit with PowerShell and Regex and such stuff.

I wanted to split a row in processed .aspx file and I wanted to use multiple delimiters while splitting. But according to this :

http://technet.microsoft.com/en-us/library/hh847811.aspx

you can’t use multiple delimiters as parameter, like say array of delimiters like I was used to in C# :

http://msdn.microsoft.com/en-us/library/vstudio/ms228388.aspx

OK so without any further  ado :

you can chain .Split in PowerShell like this :

$splittedRow = "<tag id='abcd' id2="efgh"></tag>".Split("""").Split("'")
Write-Host $splittedRow

This will return string splitted with delimiter ” and ‘.

Enjoy.