El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for the ‘Scripts’ Category

Modify machine.config (config files) using Powershell

Posted by kiquenet en 22 enero 2015

ConfigurationManager

$config = [System.Configuration.ConfigurationManager]::OpenMachineConfiguration() 

"{0,-25}     {1,25}"  -f "   Name", "   Allow Definition"
"{0,-25}     {1,25}"  -f "   —-", "   —————-"
$i = 0 

foreach ($section in $config.Sections) 

     "{0,-25}     {1,25}" -f $section.SectionInformation.Name,$section.SectionInformation.AllowExeDefinition 
     $i++ 

"Total number of sections: {0}" -f $i

get-content and DocumentElement

$xml = [xml](get-content $machineConfig)
$xml.Save($machineConfig + "_$currentDate")
$root = $xml.get_DocumentElement()
$system_web = $root."system.web"
if ($system_web.machineKey -eq $nul) {
$machineKey = $xml.CreateElement("machineKey")
$a = $system_web.AppendChild($machineKey)
}
$system_web.SelectSingleNode("machineKey").SetAttribute("validationKey","$validationKey")
$system_web.SelectSingleNode("machineKey").SetAttribute("decryptionKey","$decryptionKey")
$system_web.SelectSingleNode("machineKey").SetAttribute("validation","$validation")
$a = $xml.Save($machineConfig)

XmlDocument

if (!$origXml.configuration.’system.serviceModel’.bindings)
{
    $tempXmlDoc = new-object System.Xml.XmlDocument
    $tempXmlDoc.LoadXml($newXml)
    $newNode = $origXml.ImportNode($tempXmlDoc.DocumentElement, $true)
    $origXml.configuration.’system.serviceModel’.AppendChild($newNode)
}

Sources:
http://sunauskas.com/blog/edit-config-file-with-powershell/
http://geekswithblogs.net/nharrison/archive/2011/05/25/updating-the-machine.config–with-powershell.aspx

http://pshscripts.blogspot.com.es/2009/02/get-machineconfig.html
http://jeffgraves.me/2012/06/05/read-write-net-machine-key-with-powershell/
http://stackoverflow.com/questions/10342657/how-can-i-add-a-section-to-a-web-config-using-powershell

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

Installing PowerShell Active Directory Module for Windows 8.1

Posted by kiquenet en 21 enero 2015

STEP 1.) Download and install Remote Server Administration Tools (RSAT) for Windows 8.1
http://www.microsoft.com/en-us/download/details.aspx?id=39296

STEP 2.) For x64, install Windows8.1-KB2693643-x64.msu

STEP 3.) Active Feature

Select AD DS and AD LDS Tools and then select Active Directory Module for Windows PowerShell.

To turn off specific tools

  1. On the desktop, hover in the upper right corner of the screen, and then click Settings.
  2. On the Desktop menu, click Control Panel.
  3. Click Programs, and then in Programs and Features, click Turn Windows features on or off.
  4. In the Windows Features dialog box, expand Remote Server Administration Tools, and then expand either Role Administration Tools or Feature Administration Tools.
  5. Clear the check boxes for any tools that you want to turn off. Click OK, and then close Control Panel.

STEP 4.)
Open a PowerShell prompt and type PS C:\> Get-Module –ListAvailable.

STEP 5.)

To ensure the Active Directory Module is present, using PowerShell type PS C:> Import-Module ActiveDirectory.

NOTE: You will need to do this for every PowerShell session.

If you wish to have the Active Directory Module automatically loaded any time you run PowerShell, prepare a shortcut with the following content: %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command import-module ActiveDirectory

STEP 6.)

PS C:> Get-ADGroupMember "MY CUSTOM GROUP IN AD" | select name

Appenders:

Installation and Uninstallation of MSU in silent mode
http://msiworld.blogspot.com.es/2012/04/silent-install-and-uninstall-of-msu.html

MSU are the Microsoft Update files.
You can easily install the MSU file silently without reboot with the following command line:
wusa.exe Windows6.1-KB123456-x86.msu /quiet /norestart
To Uninstall it Silently you need to follow this simple procedure:
1) Run this command:
expand c:\temp\Windows6.0-KB123456-x86.msu –F:Windows6.0-KB123456-x86.xml c:\temp
2) This will create an XML file in temp folder as per the name above.
Edit this xml in notepad.
3)Find the assemblyidentity tag. Then, note the values of the following attributes:

  • The name attribute
  • The publickeytoken attribute
  • The processArchitecture attribute
  • The version attribute

4) Use the below command to uninstall the MSU from your machine.
start /w pkgmgr /up:name~publickeytoken~processArchitecture~~version
Note: The variables above need to be replaced by the vaules you have copied in step 3.

Using powershell view http://powershell.org/wp/forums/topic/installing-msu-via-powershell-psexec/ and http://www.nigelboulton.co.uk/2011/01/installing-a-windows-hotfix-on-multiple-machines-using-a-powershell-script/#comment-23005 and http://randygray.com/powershell-install-multiple-windows-updates-msu/

Sources:

https://support.software.dell.com/es-es/appassure/kb/117489

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

Arrays in Powershell

Posted by kiquenet en 9 enero 2015

Collections, Hashtables, Arrays, strings
https://www.simple-talk.com/sysadmin/powershell/powershell-one-liners–collections,-hashtables,-arrays-and-strings/

Define Array

$configs = @(

     "C:\tfs\Arquitectura\ConnectionStrings.config"; 
     "C:\tfs\VSIntegration\Test\App.config"; 
)

Foreach Array

for( $i = 0; $i -lt $configs.length; $i++) {
  $config = $configs[$i]
 
  Write-Host setting $config
 
}

Alternative

function ConvertTo-MyTypeOfItem
{
    PARAM (
        [ValidatePattern("([^_]+_){3}[^_]+")]
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$StringToParse
    )

    PROCESS {
        $custId, $invId, $prodId, [int]$value = $StringToParse -split "_"
        $myObject = New-Object PSObject -Property @{
            CustomerID = $custId;
            InvoiceID = $invId;
            ProductID = $prodId;
            Value = $value
        }
        Write-Output $myObject
    }
}

# In the test scenario I have replaced getting the list of files
# with an array of names. Just uncomment the first and second lines
# following this comment and remove the other $baseNames setter, to
# get the $baseNames from the file listing

#$files = Get-ChildItem test *.txt
#$baseNames = $files.BaseName
$baseNames = @(
    "cust1_inv1_prod1_1";
    "cust2_inv2_prod2_2";
    "cust3_inv3_prod3_3";
    "cust4_inv4_prod4_4";
)

$myObjectArray = $baseNames | ConvertTo-MyTypeOfItem

$myObjectArray

Sources:
http://stackoverflow.com/questions/21884828/powershell-array-to-store-strings
http://stackoverflow.com/questions/25191803/powershell-cli-foreach-loop-with-multiple-arrays
http://www.powershellpro.com/powershell-tutorial-introduction/variables-arrays-hashes/

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

Members, Contributor, Groups, Identities in TFS

Posted by kiquenet en 5 enero 2015

Get members of TFS Group

private List<Identity> ListContributors()
{
    const string projectName = "<<TFS PROJECT NAME>>";
    const string groupName = "Contributors";
    const string projectUri = "<<TFS PROJECT COLLECTION OR URL TFS SERVER>>";

    TfsTeamProjectCollection projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(projectUri));
    ICommonStructureService css = (ICommonStructureService) projectCollection.GetService(typeof(ICommonStructureService));
    IGroupSecurityService gss = projectCollection.GetService<IGroupSecurityService>();

    // get the tfs project
    var projectList = css.ListAllProjects();
    var project = projectList.FirstOrDefault(o => o.Name.Contains(projectName));

    // project doesn’t exist
    if (project == null) return null;

    // get the tfs group
    var groupList = gss.ListApplicationGroups(project.Uri);
    var group = groupList.FirstOrDefault(o => o.DisplayName.Contains(groupName));  // you can also use DisplayName or AccountName. AccountName is empty for me.

    // group doesn’t exist
    if (group == null) return null;

    Identity sids = gss.ReadIdentity(SearchFactor.Sid, group.Sid, QueryMembership.Expanded);

    // there are no users
    if (sids.Members.Length == 0) return null;

    // convert to a list
    List<Identity> contributors = gss.ReadIdentities(SearchFactor.Sid, sids.Members, QueryMembership.Expanded).ToList();

    return contributors;
}

Add SID to a Readers group

# load the required dll
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")

function get-tfs
{
    param(
    [string] $serverName = $(throw ‘serverName is required’)
    )

    $propertiesToAdd = (
        (‘VCS’, ‘Microsoft.TeamFoundation.VersionControl.Client’, ‘Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer’),
        (‘WIT’, ‘Microsoft.TeamFoundation.WorkItemTracking.Client’, ‘Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore’),
        (‘CSS’, ‘Microsoft.TeamFoundation’, ‘Microsoft.TeamFoundation.Server.ICommonStructureService’),
        (‘GSS’, ‘Microsoft.TeamFoundation’, ‘Microsoft.TeamFoundation.Server.IGroupSecurityService’)
    )

    [psobject] $tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($serverName)
    foreach ($entry in $propertiesToAdd) {
        $scriptBlock = ‘
            [System.Reflection.Assembly]::LoadWithPartialName("{0}") > $null
            $this.GetService([{1}])
        ‘ -f $entry[1],$entry[2]
        $tfs | add-member scriptproperty $entry[0] $ExecutionContext.InvokeCommand.NewScriptBlock($scriptBlock)
    }
    return $tfs
}
#set the TFS server url
[psobject] $tfs = get-tfs -serverName
http://YourTfsServer:8080/tfs/YourColleciton

$items = $tfs.vcs.GetAllTeamProjects( ‘True’ )
    $items | foreach-object -process {
    $proj = $_
    $readers = $tfs.GSS.ListApplicationGroups($proj.Name) | ?{$_.DisplayName -eq ‘Readers’ }

    $tfs.GSS.AddMemberToApplicationGroup($readers.Sid, ‘TheSidToTheGroupYouWantToAdd’)
}

var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://vsalm:8080/tfs/FabrikamFiberCollection"));

            var ims = tpc.GetService<IIdentityManagementService>();

            var tfsGroupIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                    "[FabrikamFiber]\\Fabrikam Fiber Web Team",
                                                    MembershipQuery.None,
                                                    ReadIdentityOptions.IncludeReadFromSource);           

            var userIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                    "VSALM\\Barry",
                                                    MembershipQuery.None,
                                                    ReadIdentityOptions.IncludeReadFromSource);

            ims.AddMemberToApplicationGroup(tfsGroupIdentity.Descriptor, userIdentity.Descriptor);

Sources:
http://stackoverflow.com/questions/16792995/get-members-of-tfs-group

http://stackoverflow.com/questions/7961727/how-to-grant-read-only-access-to-all-tfs-team-projects-to-a-group-of-users/7971731#7971731

http://blog.ronischuetz.com/2010/04/tfs-api-list-all-tfs-users.html

http://pauravlokesh.wordpress.com/2013/08/13/recursively-list-groups-users-tfsteamprojectcollection/

http://geekswithblogs.net/TarunArora/archive/2011/09/30/tfs-sdk-get-groups-users-permissions-using-tfs-api-with.aspx

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

Delete TestResults folder (Unit Testing Visual Studio)

Posted by kiquenet en 5 enero 2015

Cleaning up Visual Studio TestResults with PowerShell

If you write your unit tests using Visual Studio, then you know how quickly those pesky "TestResults" folders can eat up precious disk space over time.

Assuming all of your code is collocated in the same parent directory, replace "C:\TFS" with your parent directory.

(get-childitem C:\TFS\* -recurse) | where{$_.name -eq "TestResults"} |% {remove-item $_.fullname -recurse}

Improvements:

Error Handling when deleting folders and files.

Validating contents TestResults folder (subfolders In and Out, *.trx files, …)

$dir = "C:\TFS\"
(get-childitem $dir -recurse) | where { $_.name -eq "TestResults"} | foreach {

   $delete = $false;
   (get-childitem  $_.FullName -recurse) | where {$_.name -eq "Out"}  | foreach {
       
        $ParentS = ($_.Fullname).split("\")
        $Parent = $ParentS[@($ParentS.Length – 3)]
        if ($Parent -eq "TestResults") {$delete = $true;}

   }

   if ($delete)
   {
        Write-Host -ForegroundColor red ("Eliminando {0}" -f  $_.FullName )
        Remove-item $_.fullname -recurse
   }

}

Write-Host -ForegroundColor red ("Eliminado TestResults de {0}" -f  $dir )

Source:
http://captechconsulting.com/blog/mike-etheridge/cleaning-visual-studio-testresults-powershell

Posted in .NET, PowerShell, Productividad, Scripts, VisualStudio | Etiquetado: , , | Leave a Comment »

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:"/"

Scripting

@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"

Powershell

function Start-Webserver
{
    PARAM
    (
        [ValidateNotNull()]
        [int]$port = 8080,

        [ValidateNotNullOrEmpty()]
        [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)
        }
        return
    }

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

Sources:
http://learningpcs.blogspot.com.es/2011/08/utility-webdevwebserverexe.html
http://blog.gehtnicht.at/p/2014/06/24/start-webdev-webserver40-exe-with-powershell/

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"
if ERRORLEVEL 1 goto EXIT

:EXIT

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
}

Sources:
http://stackoverflow.com/questions/7151484/fail-on-post-build-event
http://ddkonline.blogspot.com.es/2010/06/how-to-change-read-only-attribute-of.html

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

UAC, Run As Administrator, Elevated Process

Posted by kiquenet en 22 agosto 2014

cmd.RedirectStandardInput = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.UseShellExecute = false; // true ???
cmd.Verb = “runas”

The Verb only works with UseShellExecute set to true

You must use ShellExecute. ShellExecute is the only API that knows how to launch Consent.exe in order to elevate.
In C#, the way you call ShellExecute is to use Process.Start along with UseShellExecute = true:






const int ERROR_CANCELLED = 1223; //The operation was canceled by the user. ProcessStartInfo info = new ProcessStartInfo(@"C:\Windows\Notepad.exe"); info.UseShellExecute = true; info.Verb = "runas"; try { Process.Start(info); } catch (Win32Exception ex) { if (ex.NativeErrorCode == ERROR_CANCELLED) MessageBox.Show("Why you no select Yes?"); else throw; }

You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to ‘runas’, as follows:

startInfo.Verb = "runas";

This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you’ll need to run your entire host process with elevated permissions by embedding the appropriate manifest in your application to require the ‘highestAvailable’ execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Edit: I see just just edited your question to state that "runas" didn’t work for you. That’s really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

Manifest for Application: http://msdn.microsoft.com/en-us/library/bb756929.aspx

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Executable: IsUserAdmin.exe 
Manifest:IsUserAdmin.exe.manifest
Sample application manifest file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> 
  <assemblyIdentity version="1.0.0.0"
     processorArchitecture="X86"
     name="IsUserAdmin"
     type="win32"/> 
  <description>Description of your application</description> 
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="requireAdministrator"
          uiAccess="false"/>
        </requestedPrivileges>
       </security>
  </trustInfo>
</assembly>

Update: The app manifest way is preferred:

Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.

(Properties Project –> Application –> Resources –> Icon and manifest (embed, first add it and then select)

How to set UAC settings in manifest (VS 2008)

http://justinyue.wordpress.com/2008/12/19/how-to-set-uac-settings-in-manifest-for-vs-2008/

if (IsAdministrator() == false)
{
    // Restart program and run as admin
    var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
    startInfo.Verb = "runas";
    System.Diagnostics.Process.Start(startInfo);
    Application.Current.Shutdown();
    return;
}

private static bool IsAdministrator()
{
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}


// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)


this error

The Process object must have the UseShellExecute property set to false in order to redirect IO streams.

The Process object must have the UseShellExecute property set to false in order to start a process as a user

you cannot have it both ways. UAC prevents an unelevated process from hi-jacking the capabilities of an elevated one. The only way you can redirect is to elevate yourself first.

You need to set UseShellExecute to true for the Verb to be respected and it must be set to ‘false’ to redirect standard output. You can’t do both.

I’m pretty sure Windows also won’t allow you to redirect standard input/output/error across the admin/non-admin security boundary. You’ll have to find a different way to get output from the program running as admin.

According to this article, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don’

http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx

  • UAC – What. How. Why.. The architecture of UAC, explaining that CreateProcess cannot do elevation, only create a process. ShellExecute is the one who knows how to launch Consent.exe, and Consent.exe is the one who checks group policy options.


Check out this code (I was inspired by the code here, but I’ve improved it – in my version there is no directory created and removed to check for admin privileges):

:::::::::::::::::::::::::::::::::::::::::

:: Automatically check & get admin rights

:::::::::::::::::::::::::::::::::::::::::

@echo off

CLS

ECHO.

ECHO =============================

ECHO Running Admin shell

ECHO =============================

:checkPrivileges

NET FILE 1>NUL 2>NUL

if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges

if '%1'=='ELEV' (shift & goto gotPrivileges) 
ECHO.

ECHO **************************************

ECHO Invoking UAC for Privilege Escalation

ECHO **************************************

setlocal DisableDelayedExpansion

set "batchPath=%~0"

setlocal EnableDelayedExpansion

ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs"

ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs"

"%temp%\OEgetPrivileges.vbs"

exit /B

:gotPrivileges

::::::::::::::::::::::::::::

:START

::::::::::::::::::::::::::::

setlocal & pushd .

REM Run shell as admin (example) - put here code as you like

cmd /k

The script takes advantage of the fact that NET FILE requires admin privilege and returns errorlevel 1 if you don’t have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the admin account and password.

I have tested it with Windows 7 and with Windows XP – works fine for both. Advantage is, after the start point you can place anything that requires admin privileges, e.g. if you intend to re-install and re-run a Windows service for debugging purpose (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script UAC would ask you three times for your admin user and password – now you’re asked only once at the beginning, and only if required.


Update: If your script just needs to show an error message and exit if there are no admin privilegesinstead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. & 
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects admin rights, otherwise exit with an error. If you don’t require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be in the same line, it is displayed here in multiple lines for better readability!


Update: On some machines, I’ve encountered issues, which are solved in the new version above already. One was due to different double quote handling, the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later and I’ve added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!, it contains no double quotes so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)  

checks if the script has already been called by the VBS to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Mt.exe Tool

Common Errors:

Exited with code 9009 (Post Build Event)

Values of attribute "name" not equal in different manifest snippets. mt.exe


http://stackoverflow.com/questions/4677055/visual-studio-post-build-event-mt-exe-command-fails-with-code-9009?rq=1#4865696

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\mt.exe"
"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"

References:

http://stackoverflow.com/questions/8690552/run-elevated-process

http://stackoverflow.com/questions/16926232/run-process-as-administrator-from-a-non-admin-application/20872219#20872219

http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically

http://msdn.microsoft.com/en-us/magazine/cc163486.aspx

http://stackoverflow.com/questions/7044985/how-can-i-auto-elevate-my-batch-file-so-that-it-requests-from-uac-admin-rights?answertab=votes#tab-top

http://justinyue.wordpress.com/2008/12/19/how-to-set-uac-settings-in-manifest-for-vs-2008/

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

Troubleshooting: Sharepoint Deployments and Powershell

Posted by kiquenet en 13 agosto 2014

 

Account for Installations

http://sharepointlearningcurve.blogspot.com.es/2010/04/sharepoint-2010-installation-account.html

http://serverfault.com/questions/349300/permissions-error-setting-up-powershell-account-privileges-for-sharepoint-2010

http://sharepoint.stackexchange.com/questions/26831/permissions-error-setting-up-sharepoint-2010-powershell-account-privileges

Error This operation uses the SharePoint Administration service (spadminV4), which could not be contacted.  If the service is stopped or disabled, start it and try the operation again.

http://support.microsoft.com/kb/925727

http://sharepoint.stackexchange.com/questions/72106/remove-spwebapplication-not-working-if-spadminv4-service-is-run-by-local-system

http://sharepoint.stackexchange.com/questions/110928/spadminv4-which-could-not-be-contacted-in-deployment

Term Store in sharepoint 2013 using powershell

Error Current user has insufficient permissions to perform this operation

To resolve the issue:

•Go the Central Administration

•Go to : “Manage service applications” ( _admin/serviceapplications.aspx).

•Select “Managed Metadata Service” to get the Terms Store admin interface.

•In the section : “Term Store Administrators”. Add the user that you use to run sharepoint management shell

•Save the changes.

In SharePoint 2013 Enterprise, I followed the steps above, but it still didn’t work.

Following on from there, I went to the ‘Term Store Management Tool’ in Central Admin (/_layouts/15/termstoremanager.aspx) and added the user there too. This resolved the permissions issue for me.

Cmdlets Sharepoint and Powershell

http://blog.falchionconsulting.com/index.php/tag/cmdlets/page/2/

Read Logging Files Sharepoint

Reading the log file.

The simplest way is opening the log files from the 14$\logs in Notepad. This might be quickest way but not the most efficient in a live multiuser environment. I usually use this in a development environment in combination with a text editor that automatically reloads the file when it’s updated (Notepad++).

Using powershell with a correlation id

You can use powershell to quickly track down a correlation ID and dump the related log files into a file

1

get-splogevent -starttime (get-date).addminutes(-20) | where-object { $_.correlation -eq “b66db71a-3257-4470-adf9-5c01dc59ecb3″ } | fl message > c:\errors.txt

More info can be found here :
http://www.mysharepointadventures.com/2011/08/175/

Uls viewer

A Windows application for viewing the ULS logs more easily. Very handy when you are (trying to) reproduce a specific error and during debugging
I use it when I’m trying to track down a specific error and during debugging.

http://ulsviewer.codeplex.com/

image.png

Farm solution

Codeplex also has a nice solution which you can query the SharePoint logs with from within Central Administration.
The solution installs in your Central Administration. Very handy if you want a quick look in your logs files without having to connect over remote desktop to the actual server.
For detailed log digging this tool might not be sufficient.

http://sp2010getcorrelation.codeplex.com/

Visual Studio Integrated ULS Viewer
https://integrateduls.codeplex.com/Wikipage?ProjectName=integrateduls

tool.png

 

References:
http://sharepoint.stackexchange.com/questions/73022/cannot-create-a-group-in-term-store-using-powershell-current-user-has-insuffic
http://sharepoint.stackexchange.com/questions/7868/best-way-to-get-reference-to-local-sitecollection-term-store-group
http://blog.amtopm.be/2010/12/27/error-occurred-in-deployment-step-activate-features-the-current-user-has-insufficient-permissions-to-perform-this-operation/

http://blog.amtopm.be/2012/02/21/read-logging-files-in-sharepoint/

http://blog.falchionconsulting.com/index.php/tag/cmdlets/page/2/

http://sharepointlearningcurve.blogspot.com.es/2010/04/sharepoint-2010-installation-account.html

Posted in .NET, PowerShell, Scripts, Sharepoint | 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.

Errors:

Couldn’t access SERVER:

Access is denied.

http://stackoverflow.com/questions/25035759/access-denied-using-psexec-when-connect-to-remote-server

http://serverfault.com/questions/616583/access-denied-using-psexec-when-connect-to-remote-server

References:

http://serverfault.com/questions/489822/psexec-is-not-connecting-to-machine-using-supplied-username-and-password/489845

http://serverfault.com/questions/216466/cannot-access-client-pc-remotely-due-to-time-date-issue-xp-win2k3-environment

http://stackoverflow.com/questions/20373885/psexec-and-windows-2008-server-access-denied

http://stackoverflow.com/questions/18791468/psexec-win7-to-win7-access-denied-psexesvc-remains

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