El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for the ‘Comandos’ Category

Open WebServer for SVC (WCF Host) in development

Posted by kiquenet en 9 octubre 2014

From Visual Studio, open WebServer with View in Browser (about svc file):

Using Process Monitor, I get full command line:

"C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\WebDev.WebServer40.exe" /port:9195 /path:"C:\TFS\VSIntegration\VSIntegration.SvcDespliegue.Host" /vpath:"/"


@echo off
SET WEBDEV40="%ProgramFiles(x86)%\Common Files\Microsoft Shared\DevServer\11.0\"
SET WEBSERVER40="WebDev.WebServer40.exe"
START /D %WEBDEV40% /B WebDev.WebServer40.exe /port:9195 /path:"C:\TFS\VSIntegration\VSIntegration.SvcDespliegue.Host" /vpath:"/"
SET mypath=%~dp0

REM Error: WebServer crash when I call Svc ¿? Maybe relative path
REM START /D %WEBDEV40% /B WebDev.WebServer40.exe /port:9195 /path:"%mypath%..\..\VSIntegration\VSIntegration.SvcDeployment.Host"


function Start-Webserver
        [int]$port = 8080,

        [ValidateScript({Test-Path $_})]
        [string]$path = (pwd)

    Set-Variable PROCESSDIRECTORY -Option Constant -value ([System.Environment]::ExpandEnvironmentVariables('%CommonProgramFiles(x86)%\Microsoft Shared\DevServer\11.0\'))
    Set-Variable PROCESSNAME -Option Constant -value 'WebDev.WebServer40.exe'

    $matchingProcesses = Get-WmiObject Win32_Process -Filter " name = '$PROCESSNAME' " |
        Where-Object { $_.CommandLine -like "*/port:$port*" }

    if($matchingProcesses -ne $null)
        # output a warning if another path than given path is used by existing process
        if(-not($matchingProcesses.CommandLine -like "*/port:$port /path:$path"))
            Write-Warning ('Process "{0}" with PID "{1}" already listening to port "{2}"
CommandLine: "{3}"' -f $matchingProcesses.Name, $matchingProcesses.Handle, $port, $matchingProcesses.CommandLine)

    & "$PROCESSDIRECTORY$PROCESSNAME" /port:$port /path:$path
    & start http://localhost:$port/


Posted in .NET, Comandos, Scripts | Etiquetado: , , | Leave a Comment »

Error in Pre Build (Post Build) Event

Posted by kiquenet en 9 octubre 2014

About this error when you compiles a project.

Unable to copy file "C:\TFS\Main\AddIn\FicPwd.key" to "bin\Debug\FicPwd.key". Access to the path ‘bin\Debug\FicPwd.key’ is denied.

$(TargetDir) = C:\TFS\Main\AddIn\bin\Debug

For PreBuild Event:

attrib -r "$(TargetDir)FicPwd.key"


Maybe using Powershell

$computer = gc env:computername

$fileList = Get-ChildItem ".\InfoPath Form Template" | Where-Object {$_.name -like "*.dll" -or $_.name -like "*.pdb" -or $_.name -like "*.xsf"  }

foreach ($fileItem in $fileList)
$fileItem.set_IsReadOnly($false) # Remove readonly flag


Posted in Comandos, Scripts, VisualStudio | Etiquetado: , , , | Leave a Comment »

Undo, unlock file (User’s checkout) in TFS

Posted by kiquenet en 6 octubre 2014

    Like Brett Rogers posted in StackOverflow:

    There are at least 2 different ways to do this:

    Command Line

    There is a command-line utility called Tf.exe that comes with Team Explorer. Find the documentation here. It can be accessed by launching a Visual Studio Command Prompt window.

  • Open up Visual Studio command prompt (Start -> Programs -> Microsoft Visual Studio 200X -> Visual Studio Tools -> Visual Studio 200X Command Prompt)
  • Run the following command: tf.exe

tf Command

Deleting the workspace

tf workspace /delete WorkspaceName;User

tf lock /lock:none /workspace:WorkspaceName;USERNAME /recursive $/

To get the list of workspaces for a user, just run the following command from the same prompt:

tf workspaces /owner:username

Real sample:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>tf undo /workspace:TeamAdministration;mydomain\myuser $/Administration/WebUI/App_Data/Web.sitemap /recursive

No pending changes were found for $/Administration/WebUI/App_Data/Web.sitemap.

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>tf lock /lock:none /workspace:TeamAdministration;mydomain\myuser $/Administration/WebUI/App_Data/Web.sitemap /recursive

TF10152: The item $/Administration/WebUI/App_Data/Web.sitemapmust remain locked because its file type prevents multiple check-outs.

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>tf workspace /delete TeamAdministration;mydomain\myuser

A deleted workspace cannot be recovered.

Workspace ‘TeamAdministration;mydomain\myuser’ on server ‘http://myteamserver:8080/ has 0 pending change(s).

Are you sure you want to delete the workspace? (Yes/No) Y

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>tf undo /workspace:TeamAdministration;mydomain\myuser $/Administration/WebUI/App_Data/Web.sitemap /recursive

TF14061: The workspace TeamAdministration;mydomain\myuser does not exist.


The second is via the GUI, but does not come standard – you have to install the TFS Power Tools. See here for details on how to use this method.

Keep in mind that with either method you will need the appropriate rights. The permissions are called "Undo other users’ changes" and "Unlock other users’ changes". These permissions can be viewed by:

  1. Right-clicking the desired project, folder, or file in Source Control Explorer
  2. Select Properties
  3. Select the Security tab
  4. Select the appropriate user or group in the Users and Groups section at the top
  5. View the "Permissions for [user/group]:" section at the bottom

Another good option, use the free TFS Sidekick application






Posted in Comandos, Soporte, TFS | Etiquetado: , , , , | Leave a Comment »

Introducing MSMQ–MS Queues

Posted by kiquenet en 6 agosto 2014

MSMQ uses flat files located in %windir%\system32\msmq.

If you want to implement your own queueing, I suggest you take a look at Ayende’s blog post on queueing


Surviving poison messages in MSMQ



Invoke-Command -ComputerName "mycomputer" -ScriptBlock {

        ## if public then $queuename = ".\YOUR_Q_NAME" 
        $queuename = ".\private$\YOUR_Q_NAME"  

        [Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
        $queue = New-Object -TypeName "System.Messaging.MessageQueue"
        $queue.Path = $queuename 
        $messagecount = $queue.GetAllMessages().Length
        Write-Host "$queuename has been purged of $messagecount messages."
Write-Host ""
Write-Host "Examples using the .NET System.Messaging assembly to access MSMQ"
Write-Host ""

Write-Host "... load the .NET Messaging assembly"

Write-Host ""

if ([System.Messaging.MessageQueue]::Exists(".\private$\MyQueue"))
  Write-Host "... delete old myqueue"
if ([System.Messaging.MessageQueue]::Exists(".\private$\BtsQueue"))
  Write-Host "... delete old btsqueue"

Write-Host "... create a new queue"
$q1 = [System.Messaging.MessageQueue]::Create(".\private$\MyQueue")

Write-Host "... create new queue, set FullControl permissions for RBC\BIZTALK"
$qb = [System.Messaging.MessageQueue]::Create(".\private$\BtsQueue")


Write-Host "... list existing queues" 
$pqs = [System.Messaging.MessageQueue]::GetPrivateQueuesByMachine(".")
Write-Host "    Count: "$pqs.length  -ForegroundColor gray
foreach($q in $pqs)
    Write-Host "       "$q.QueueName  -ForegroundColor gray

Write-Host "... access existing queue"
$q2 = New-Object System.Messaging.MessageQueue ".\private$\MyQueue"

Write-Host "... adding string Formatter and additional properties "
$q2.Formatter.TargetTypeNames = ,"System.String"
$q2.MessageReadPropertyFilter.ArrivedTime = $true 
$q2.MessageReadPropertyFilter.SentTime = $true 

Write-Host "... create a new High priorty message "
$msg = New-Object System.Messaging.Message "TestMessage"
$msg.label = "Test Msg Label"
$msg.body = "Add some body to test message"
$msg.priority = [System.Messaging.MessagePriority]::High

Write-Host "... send the High message"

$msg.body = "Some more text for the test message"
$msg.priority = [System.Messaging.MessagePriority]::Low

Write-Host "... send the Low message"

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host "... peek at queue"
$ts = New-Object TimeSpan 10000000 # 1 sec. timeout just in case MSMQ is empty
$pk = $q2.Peek($ts)
Write-Host "    ArrivedTime: "$pk.ArrivedTime.DateTime -ForegroundColor gray
Write-Host "    SentTime   : "$pk.SentTime.DateTime -ForegroundColor gray

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length -ForegroundColor gray

Write-Host "... receive from queue"
$rmsg = $q2.receive($ts)
Write-Host "    Body : "$rmsg.body  -ForegroundColor gray
Write-Host "    Label: "$rmsg.label -ForegroundColor gray

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host "... purge the queue "

Write-Host "... check the queue "
Write-Host "    Count: "$q2.GetAllMessages().length  -ForegroundColor gray

Write-Host ""
Write-Host "All done, but remember to delete the test queues !!"

Queue Journal

var systemJournalQueue = new MessageQueue("FormatName:Direct=os:.\\System$;JOURNAL"); var systemDeadLetterQueue = new MessageQueue("FormatName:Direct=os:.\\System$;DEADLETTER"); var systemDeadXLetterQueue =new MessageQueue("FormatName:Direct=os:.\\System$;DEADXACT")); systemJournalQueue.Purge();
private static void PurgeQueues(int archiveAfterHowManyDays, MessageQueue queue)
    queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });
    queue.MessageReadPropertyFilter.ArrivedTime = true;

    using (MessageEnumerator messageReader = queue.GetMessageEnumerator2())
        int counter = 0;
        while (messageReader.MoveNext())
            Message m = messageReader.Current;
            if (m.ArrivedTime.AddDays(archiveAfterHowManyDays) < DateTime.Now)


$queues = Get-WmiObject Win32_PerfFormattedData_msmq_MSMQQueue
$queues | ft -property Name,MessagesInQueue

$host = ...
$cred = get-credential
$queues = Get-WmiObject Win32_PerfFormattedData_msmq_MSMQQueue -computer $host -credential $cred
$queues | ft -property Name,MessagesInQueue
private static int GetMsmqMessageCount(string queuePath, string machine,
  string username, string password)
  var options = new ConnectionOptions
    {Username = username, Password = password};
  var path = string.Format(@"\\{0}\root\CIMv2", machine);
  var scope = new ManagementScope(path, options);

  string queryString = 
    String.Format("SELECT * FROM Win32_PerfFormattedData_msmq_MSMQQueue WHERE Name = '{0}'",
  var query = new ObjectQuery(queryString);

  var searcher = new ManagementObjectSearcher(scope, query);

  IEnumerable<int> messageCountEnumerable = 
    from ManagementObject queue in searcher.Get()
    select (int) (UInt64) queue.GetPropertyValue("MessagesInQueue");

  return messageCountEnumerable.First();




xcopy, zero administration, queuing service

Posted in .NET, Comandos | Etiquetado: , | Leave a Comment »

PSExec Troubleshooting

Posted by kiquenet en 6 agosto 2014

Version PsExec v2.11

PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c
time /t

PsExec \\SERVER -u myDomain\UserDeployTFS -p xxx cmd.exe /v /c echo ^%computername^%

Useful commands:

Checked the ports used by PSExec, 445 and 135, and both are open on the SERVER machine (nc is a unix commad)

nc –z SERVER 445
nc –z SERVER 135

Telnet SERVER 445

net user administrator /enable:yes

runas /user:myDomain\UserDeployTFS cmd

cmdkey.exe /add: SERVER /user:myDomain\UserDeployTFS /pass:XXXX

cmdkey.exe /delete: SERVER

all network based authentication/credentials between the two computers with differing clocks will fail. Local accounts will still be able to login. If you use something like psexec and instead of using your domain credentials, you specify valid administrative credentials on the local machine, it should connect just fine and allow you to fix the clock.

schtasks.exe /create /F /S $RemoteHost /ru domain\User /rp password /tn Sync-Time /sc Once /st $NowPlusOneMinute /tr "w32tm /resync"

PsExec needs the local administrator account on windows to be enabled. Recent Windows(following linux) has made this account default set to disabled(the logic is the same as for ‘sudo’ in linux: security). Enable this account by the following command(run command prompt as administrator)…

net user administrator /enable:yes

set the network credentials:
cmdkey /list:%DOMAIN% | find "%DOMAIN_USER%" >NUL || cmdkey /add:%DOMAIN% /user:%DOMAIN%\%DOMAIN_USER% /pass:%DOMAIN_USER_PWD% >>%LOGFILE% 2>>&1

Runas was not possible with local shares and other permissions.


Couldn’t access SERVER:

Access is denied.








Posted in Comandos, Errores, Scripts | Etiquetado: , | Leave a Comment »

How to Create, Modify and Delete Scheduled Tasks from the Command Line

Posted by kiquenet en 10 septiembre 2012


Windows XP/Server 2003 introduced us to the SchTasks command line tool which usurped the At tool offered in Windows 2000. This tool offers the ability to control every aspect of your Scheduled Tasks through calls to this command.

While the wizard Windows uses to help you graphically create Scheduled Tasks is very good, the command line tool is ideal for situations such as:

  • Manipulate tasks in batch scripts.
  • Control and create tasks on networked machines without having to login to them.
  • Mass create/sync task across multiple machines.
  • Use in custom applications to communicate with the Task Scheduler instead of having to make API calls.

As you can probably imagine, the SchTasks command has more options than we can cover in this article so we are going to focus on showing some examples of common task configurations and what the respective task looks like in the Task Scheduler.

Referencia: http://www.howtogeek.com/51236/how-to-create-modify-and-delete-scheduled-tasks-from-the-command-line/

Create ‘My Task’ to run C:RunMe.bat at 9 AM everyday:

SchTasks /Create /SC DAILY /TN “My Task” /TR “C:RunMe.bat” /ST 09:00

Modify ‘My Task’ to run at 2 PM:

SchTasks /Change /TN “My Task” /ST 14:00


Create ‘My Task’ to run C:RunMe.bat on the first of every month:

SchTasks /Create /SC MONTHLY /D 1 /TN “My Task” /TR “C:RunMe.bat” /ST 14:00

Create ‘My Task’ to run C:RunMe.bat every weekday at 2 PM:

SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN “My Task” /TR “C:RunMe.bat” /ST 14:00


Delete the task named ‘My Task’:

SchTasks /Delete /TN “My Task”

Note: this will raise a warning which you will need to confirm.

Bulk Creation

Like any other command line tool, you can include multiple instructions in a batch file to accomplish bulk creation (or deletion).

For example, this script:

SchTasks /Create /SC DAILY /TN “Backup Data” /TR “C:Backup.bat” /ST 07:00
SchTasks /Create /SC WEEKLY /D MON /TN “Generate TPS Reports” /TR “C:GenerateTPS.bat” /ST 09:00
SchTasks /Create /SC MONTHLY /D 1 /TN “Sync Database” /TR “C:SyncDB.bat” /ST 05:00

Produces these tasks: Backup Data, Generate TPS Reports, Sync Database


The ability to do this is a quick way to roll out new tasks or change existing schedules to many machines at once. As a way to ensure the tasks are updated, you could include the appropriate SchTasks commands in a domain login script which will update user machines when they log in.

Microsoft Documentation on SchTasks Command


Posted in Comandos, Scripts | Etiquetado: , , | Leave a Comment »

osql.exe y encoding UTF8

Posted by kiquenet en 29 julio 2010

OSQL accepts ANSI and Unicode encoded files, BUT I tried opening my file with notepad++ changed the encoding to UTF-8 and I got similar errors.

MS SQL Server’s osql utility (SQL Server 2000) is deprecated.

Mejor usar SQLCMD.

I have been trying to run MS SQL Server’s osql utility (SQL Server 2000) to insert some default data. My SQLServer’s target database collation is Croatian_CI_AS. After some time I’ve realized a few things about the ways in which you can save the input file.

Using Notepad++ as my editor I thought that formatting a file as UTF-8 would cause everything to be wonderful and magically work.

Not so. In fact, osql will not even read the UTF-8 encoded file (this was a real surprise)! That was a weird thing but I kept on getting this error message about first line and some weird character displayed there. Turns out that osql accepts unicode or ANSI encoded files (and there’s no way to control the input file encoding from the command line so we’re stuck with that … which is not that bad after all).
So, no.1: don’t format your input file for osql as UTF-8. That’s a different animal from a unicode encoded file.

Notepad++ offers several formatting options. Turns out that UCS-2 Little Endian is the wizard. For those interested, read on UCS-2 on wikipedia. I just realized it was actually a 16-bit Unicode encoding. Just looking at it in the list of encodings in Notepad++ didn’t ring bells.

I’m not sure why UCS-2 Big Endian encoding does not play nice (I get gibberish for most of my special characters).

Formatting a file as ANSI in Notepad++ and then running through osql was a bit of a surprise that it did not work (special characters like diacritics became gibberish, although osql did execute everything). I even changed my Windows code page to Croatian in hope that it will all somehow sort itself out but it didn’t. From what I can tell,osql will read the ANSI encoded file as probably English Latin encoding and loose the special characters in the process.

So, bottom line, UCS-2 Little Endian is our friend. Use that for encoding files that are to be executed with osql


osql.exe and unicode files – how to save your sql scripts with encoding

osql.exe is a great application for running sql scripts in a batch.  I use a batch file to execute multiple sql scripts that I use to rebuild my current application database from scratch.  When developing a brand new application, deploying a database in this way makes it really easy to recreate the database just like it will be created on Day 1 when you build out the Production environment. This requires scripting out all of your sql objects and then also having a way to execute all of those sql scripts easily.  That is where osql.exe comes in handy.

But osql.exe does have one issue that I ran into this week where it does not like UTF-8 (codepage 65001) or UTF-7 (codepage 65000) encoded files.  And sometimes you need to include unicode characters in your sql scripts.  At first I thought osql just did not support unicode but that is not the case… it just does not like the UTF-8 or UTF-7 encoding.

Trying to run a UTF-8 (codepage 65001) or UTF-7 (codepage 65000) encoded file with osql.exe will give you errors such as:

Incorrect syntax near ‘+’.
Incorrect syntax near ‘ ‘.
Incorrect syntax near ‘ï’.

Saving the same file with Unicode Encoding (codepage 1200) will work just fine.  Here is how to save sql scripts in Microsoft SQL Server Management Studio with a particular encoding (you can also use this method to see what type of encoding the file is saved in in the first place).  One other thing to note is that Visual Studio has this same type of Save As… functionality.

From the Microsoft SQL Server Management Studio (or Visual Studio) File menu chooseSave [FILENAME] As…


Then when the Save File As dialog appears you will see a little black arrow (inverted triangle) as part of the Save button.


Clicking the just the inverted triangle portion of the button will give you a menu.


Choosing the Save with Encoding… option will then present you with an Advanced Save Options dialog.



Here is where you can specify the encoding to use for the file.  For osql.exe make sure you specify either Western European (Windows) – Codepage 1252 or Unicode – Codepage 1200.  Do not select UTF-8 (codepage 65001) or UTF-7 (codepage 65000) or osql.exe will give errors when trying to parse the file.



Posted in Comandos, SQL | Etiquetado: , , | Leave a Comment »

How to clear your Internet Explorer (version 7) cache from the command line

Posted by kiquenet en 20 julio 2010

Normally, you have to open IE and choose Tools | Delete Browsing History | Delete All…

Another way would be to open the command line and type the following commands:

  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255 (Deletes ALL History)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1 (Deletes History Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2 (Deletes Cookies Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8 (Deletes Temporary Internet Files Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16 (Deletes Form Data Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32 (Deletes Password History Only)

    Delete All – “Also delete files and settings stored by add-ons”
    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351

These commands should work in Internet Explorer 7 on XP or on Windows Vista.



Posted in Comandos, IE, Scripts | Etiquetado: , , | Leave a Comment »


Posted by kiquenet en 7 mayo 2010

Command line builds:

devenv solutionfile.sln /build [ solutionconfig ] [ /project projectnameorfile [

/projectconfig name ] ]

Available command line switches:

/Build Builds the solution or project with the specified solution

configuration. For example "Debug". If multiple platforms

are possible, the configuration name must be enclosed in quotes

and contain platform name. For example: "Debug|Win32".

/Clean Deletes build outputs.

/Command Starts the IDE and executes the command.

/Deploy Builds and then deploys the specified build configuration.

/Edit Opens the specified files in a running instance of this

application. If there are no running instances, it will

start a new instance with a simplified window layout.

/LCID Sets the default language in the IDE for the UI.

/Log Logs IDE activity to the specified file for troubleshooting.

/NoVSIP Disables the VSIP developer’s license key for VSIP testing.

/Out Appends the build log to a specified file.

/Project Specifies the project to build, clean, or deploy.

Must be used with /Build, /Rebuild, /Clean, or /Deploy.

/ProjectConfig Overrides the project configuration specified in the solution

configuration. For example "Debug". If multiple platforms are

possible, the configuration name must be enclosed in quotes

and contain platform name. For example: "Debug|Win32".

Must be used with /Project.

/Rebuild Cleans and then builds the solution or project with the

specified configuration.

/ResetAddin Removes commands and command UI associated with the specified Ad


/ResetSettings Restores the IDE’s default settings, optionally resets to

the specified VSSettings file.

/ResetSkipPkgs Clears all SkipLoading tags added to VSPackages.

/Run Compiles and runs the specified solution.

/RunExit Compiles and runs the specified solution then closes the IDE.

/SafeMode Launches the IDE in safe mode loading minimal windows.

/Upgrade Upgrades the project or the solution and all projects in it.

A backup of these files will be created as appropriate. Please

see Help on ‘Visual Studio Conversion Wizard’ for more

information on the backup process.

Product-specific switches:

/debugexe Open the specified executable to be debugged. The

remainder of the command line is passed to this

executable as its arguments.

/useenv Use PATH, INCLUDE, LIBPATH, and LIB environment variables

instead of IDE paths for VC++ builds.

To attach the debugger from the command line, use:

VsJITDebugger.exe -p <pid>

Posted in .NET, Comandos, VisualStudio | Etiquetado: | Leave a Comment »

Comando gacutil

Posted by kiquenet en 6 noviembre 2009

Se puede utilizar en Eventos Pre-Build de Visual Studio

“%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe” /u “Frk.Common, Version=, Culture=neutral, PublicKeyToken=151111f474b3ca5b”

Posted in Comandos | Etiquetado: | Leave a Comment »