How to Search Spotify Using PowerShell & Spotify’s Metadata API

December 8th, 2011 No comments

Windows PowerShell V3 includes a command, Invoke-WebRequest, which we can use to grab information using Spotify’s Metadata API.


PS > Invoke-WebRequest http://ws.spotify.com/search/1/track.json?q=Black+Label+Society

StatusCode        : 200
StatusDescription : OK
Content           : {"info": {"num_results": 417, "limit": 100, ..
                    "spotify:album:396vQgjfPsC0lisMX...
RawContent        : HTTP/1.1 200 OK
                    Vary: Accept-Charset
                    X-Varnish: 1580131781 1580105616
                    Age: 1908
                    Access-Control-Allow-Origin: *
                    Content-Length: 51642
                    Content-Type: application/json; charset=utf-8
                    Date: Thu, 01 ...
Forms             : {}
Headers           : {[Vary, Accept-Charset], [X-Varnish, 1580131..
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 51642

Let's check out the information in the Content property.


PS > Invoke-WebRequest http://ws.spotify.com/search/1/track.json?q=Black+Label+Society |
  Select-Object -ExpandProperty Content


{"info": {"num_results": 417, "limit": 100, "offset": 0,
"query": "Black Label Society", "type": "track", "page": 1},
"tracks": [{"album": {"released": "2009", "href":
"spotify:album:396vQgjfP
sC0lisMXkrQ2A", "name": "Skullage", "availability":
{"territories": "AT CH DE DK FI IS IT NO PT SE"}}, "name":
"In This River", "popularity": "0.56160", "external-ids":
[{"type": "isrc", "id": "USAR50451581"}], "length":
235.466, "href": "spotify:track:1LgNG6JFuM3E4......

The output from isn’t as nicely formatted as you might have hoped, however, using the cmdlet ConvertFrom-Json converts the json document to usable object.


PS > $bls = Invoke-WebRequest http://ws.spotify.com/search/1/track.json?q=Black+Label+Society |
Select-Object -ExpandProperty Content |
ConvertFrom-Json

Now we can simply call on a property and the information is displayed nicely formatted.


PS > $bls.info

num_results : 417
limit       : 100
offset      : 0
query       : Black Label Society
type        : track
page        : 1

Here’s an example on how you can display information about each track


PS > $bls.tracks

album        : @{released=2009; href=spotify:album:396vQgjfPsC0lisMXkrQ2A; name=Skullage; availability=}
name         : In This River
popularity   : 0.56160
external-ids : {@{type=isrc; id=USAR50451581}}
length       : 235.466
href         : spotify:track:1LgNG6JFuM3E4R7YsJgdf5
artists      : {@{href=spotify:artist:0zfT626RwO6zN3RDYeRit5; name=Black Label Society}, @{href=spotify:artist:1AeC9AuzqGc3IXMC2T5xny; name=Zakk Wylde}}
track-number : 10

album        : @{released=2010; href=spotify:album:7yji7GJSmvIpjMoEykLQq7; name=Order Of The Black; availability=}
name         : Crazy Horse
popularity   : 0.48597
external-ids : {@{type=isrc; id=USKO11000885}}
length       : 246.2
href         : spotify:track:2quyhkBRqiv56dQcfuLops
artists      : {@{href=spotify:artist:0zfT626RwO6zN3RDYeRit5; name=Black Label Society}}
track-number : 1

Rating 4.00 out of 5
[?]
Categories: Media, V3 Tags: ,

Reading Lsa Service Account Secrets using PowerShell

August 13th, 2011 1 comment

Reading Lsa Service Account Secrets using PowerShell

Intro

The Local Security Authority (Lsa) in Windows is designed to manage a Systems sec policy, auditing, logging users on to the system and storing private data such as Service Account Passwords, Cached Password hashes, FTP and Web-User Passwords, Remote Access Service (RAS) dial-up account Names and Passwords and Computer Account passwords for domain Access.

The LSA Secrets are stored under the HKLM:\Security\Policy\Secrets key. This key contains additional sub-keys that store encrypted Secrets. The HKLM:\Security\Policy\Secrets key is not accesible from regedit or other tools by default, but you can access it by running as SYSTEM.

Each Secret conatins five values:

  • CurrVal – Current Encrypted Value
  • CupdTime – Last Update Time
  • OldVal – Old Value
  • OupdTime< - Old Update Time/li>
  • SecDesc – Security Descriptor

Reference

Hacking Exposed
PassCape Software

P/Invoke

Windows PowerShell V 2.0 includes a Cmdlet, Add-Type, which is used to add a Microsoft .NET Framework type (a class) to a Windows PowerShell session. It’s also possible to call native Windows APIs in Windows PowerShell.

If you want to learn how to call the Native Windows APIs, check out PInvoke.net. Pinvok.net is a wiki that allows developers to share PInvoke signatures, user-defined types, and any other info related to calling Win32 and other unmanaged APIs from managed code (C# VB.NET and PowerShell, Yaay).

As for this particular little example (I think Yngwie Malmsteen used those words in ‘Arpeggios from hell’) we’ll check out advapi32 and the LsaRetrievePrivateData function. The function is described here.

Reference

P/Invoke
Yngwie Malmsteen

PowerShell

As mentioned earlier, you can’t access the HKLM:\Security\Policy\Secrets key as a User, however, you can access it as SYSTEM. A simple way of running PowerShell as NT AUTHORITY\SYSTEM is by using psexec.exe.


PS > .\PsExec.exe -i -s powershell.exe

PS > whoami
nt authority\system

Step two is to use the sample code from P/Invoke in PowerShell. Thanks to the Add-Type CmdLet, we can simply place the C# sample code in a variable and pass it to the CmdLet using the MemberDefinition parameter.


$signature = @"
[StructLayout(LayoutKind.Sequential)]
public struct LSA_UNICODE_STRING
{
  public UInt16 Length;
  public UInt16 MaximumLength;
  public IntPtr Buffer;
}

[StructLayout(LayoutKind.Sequential)]
public struct LSA_OBJECT_ATTRIBUTES
{
  public int Length;
  public IntPtr RootDirectory;
  public LSA_UNICODE_STRING ObjectName;
  public uint Attributes;
  public IntPtr SecurityDescriptor;
  public IntPtr SecurityQualityOfService;
}

public enum LSA_AccessPolicy : long
{
  POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
  POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
  POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
  POLICY_TRUST_ADMIN = 0x00000008L,
  POLICY_CREATE_ACCOUNT = 0x00000010L,
  POLICY_CREATE_SECRET = 0x00000020L,
  POLICY_CREATE_PRIVILEGE = 0x00000040L,
  POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
  POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
  POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
  POLICY_SERVER_ADMIN = 0x00000400L,
  POLICY_LOOKUP_NAMES = 0x00000800L,
  POLICY_NOTIFICATION = 0x00001000L
}

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaRetrievePrivateData(
  IntPtr PolicyHandle,
  ref LSA_UNICODE_STRING KeyName,
  out IntPtr PrivateData
);

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaStorePrivateData(
  IntPtr policyHandle,
  ref LSA_UNICODE_STRING KeyName,
  ref LSA_UNICODE_STRING PrivateData
);

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaOpenPolicy(
  ref LSA_UNICODE_STRING SystemName,
  ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
  uint DesiredAccess,
  out IntPtr PolicyHandle
);

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaNtStatusToWinError(
  uint status
);

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaClose(
  IntPtr policyHandle
);

[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern uint LsaFreeMemory(
  IntPtr buffer
);
"@

Add-Type -MemberDefinition $signature -Name LSAUtil -Namespace LSAUtil

In the example above we store the Sample Code from P/Invoke in a variable and then use the Add-Type CmdLet to Add it to our PowerShell Session.

Now for the tricky part. You can access the Lsa Secrets for Service Accounts using the NT AUTHORITY\SYSTEM account but you can’t decrypt them. To decrypt the Values you have to own them. How to solve this? The simplest way is to use the reg.exe command.

In this example i’ll use the SC_OSearch14 key (SharePoint 2010 Timer) and create a temporary key where i’ll copy each of the represented values described above.


"CurrVal","OldVal","OupdTime","CupdTime","SecDesc" | ForEach-Object {
  $copyFrom = "HKLM\SECURITY\Policy\Secrets\_SC_OSearch14\" + $_
  $copyTo = "HKLM\SECURITY\Policy\Secrets\MySecret\" + $_
  $regCopy = reg COPY $copyFrom $copyTo /s /f
}

Next, I’ll create three objects holding the objectAtrtibutes, localSystem and secretName.


$objectAttributes = New-Object LSAUtil.LSAUtil+LSA_OBJECT_ATTRIBUTES
$objectAttributes.Length = 0
$objectAttributes.RootDirectory = [IntPtr]::Zero
$objectAttributes.Attributes = 0
$objectAttributes.SecurityDescriptor = [IntPtr]::Zero
$objectAttributes.SecurityQualityOfService = [IntPtr]::Zero

# localSystem
$localsystem = New-Object LSAUtil.LSAUtil+LSA_UNICODE_STRING
$localsystem.Buffer = [IntPtr]::Zero
$localsystem.Length = 0
$localsystem.MaximumLength = 0

# Secret Name
$secretName = New-Object LSAUtil.LSAUtil+LSA_UNICODE_STRING
$secretName.Buffer = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni("MySecret")
$secretName.Length = [Uint16]("MySecret".Length * [System.Text.UnicodeEncoding]::CharSize)
$secretName.MaximumLength =
[Uint16](("MySecret".Length + 1) * [System.Text.UnicodeEncoding]::CharSize)

With the objects at hand i can go ahead and retrieve the Lsa Policy Handle.


$lsaPolicyHandle = [IntPtr]::Zero
[LSAUtil.LSAUtil+LSA_AccessPolicy]$access =
[LSAUtil.LSAUtil+LSA_AccessPolicy]::POLICY_GET_PRIVATE_INFORMATION
$lsaOpenPolicyHandle =
[LSAUtil.LSAUtil]::LSAOpenPolicy(
  [ref]$localSystem,
  [ref]$objectAttributes,
  $access,
  [ref]$lsaPolicyHandle
)

$lsaNtStatusToWinError = [LSAUtil.LSAUtil]::LsaNtStatusToWinError($ntsResult)

If the LsaOpenPolicy function works out, it returns ’0′, otherwise you’ll have a nice error. A good tip is to check the output.


if($lsaOpenPolicyHandle -ne 0) {
  Write-Warning "lsaOpenPolicyHandle Windows Error Code: $lsaOpenPolicyHandle"
}

Next, we retrieve the Private Data using the LsaRetrievePrivateData function and close the LsaPolicyHandle.


$privateData = [IntPtr]::Zero
$ntsResult =
[LSAUtil.LSAUtil]::LsaRetrievePrivateData(
  $lsaPolicyHandle,
  [ref]$secretName,
  [ref]$privateData
)

$lsaClose = [LSAUtil.LSAUtil]::LsaClose($lsaPolicyHandle)

Again, it’s a good idea to check the exit code from the LsaRetrievePrivateData function.


if($lsaNtStatusToWinError -ne 0) {
  Write-Warning "lsaNtsStatusToWinError: $lsaNtStatusToWinError"
}

Next step is to convert the output to a managed object and then convert it to a string.


[LSAUtil.LSAUtil+LSA_UNICODE_STRING]$secretData =
[LSAUtil.LSAUtil+LSA_UNICODE_STRING][System.Runtime.InteropServices.marshal]::PtrToStructure(
  $privateData,
  [LSAUtil.LSAUtil+LSA_UNICODE_STRING]
)

[string]$value = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($secretData.Buffer)
$value = $value.SubString(0, ($secretData.Length / 2))
$freeMemory = [LSAUtil.LSAUtil]::LsaFreeMemory($privateData)

At this point, you should have a Password in clear text. To find the account associated with the ‘_SC_OSearch14′ Service Account you can simply use WMI as demonstrated below.


$serviceName = "_SC_OSearch14" -Replace "^_SC_"
$service = Get-WmiObject -Query "SELECT StartName FROM Win32_Service WHERE Name = '$serviceName'"
$account = $service.StartName

Last step is to return the Account and Password as demonistraed below.


New-Object PSObject -Property @{
  Account = $account;
  SETEC_ASTRONOMY = $value
}

Account             SETEC_ASTRONOMY
-------             ---------------
POWERSHELL\spAdmin  Password1

I would like to thank my mentor and friend Johannes Gumbel for pointing me in the right direction regarding Lsa Secrets. Stay tuned for more.

Click here to download the Lsa PowerShell function

Usage


PS > Get-LsaSecret -Key "_SC_OSearch14"

PS > Split-Path (Get-ChildItem HKLM:\SECURITY\Policy\Secrets |
>> Select -ExpandProperty Name) -Leaf | Get-TSLSASecret

Rating 4.60 out of 5
[?]
Categories: Uncategorized Tags: ,

Fiddler using PowerShell

March 14th, 2011 4 comments

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. It’s a freeware application and can debug traffic from any application, including Internet Explorer, Mozilla Firefox, Opera, alot more.

Click here for more information

So whats this got to do with PowerShell? Well, Fiddler (FiddlerCore) also provides a .NET class library that can be consumed by any .NET application (such as PowerShell).

Click here for more information

FiddlerCore shows a couple of examples of how you can program against FiddlerCore. Lets see how we can do it using Windows PowerShell.

First, we need to install FiddlerCore. You can download FiddlerCore here.

Next, click on FiddlerCoreAPISetup.exe to start the installation.

After the installation is completed you’ll see FiddlerCore.ddl in the folder where you installed FiddlerCore.

Time for some PowerShell. Download the Fiddler.psm1 module and start PowerShell. Use Import-Module to add the module to your current scope. In the example below the location of the module is C:\FiddlerCore\Fiddler.psm1


PS > Import-Module C:\FiddlerCore\Fiddler.psm1

When the module is added to your current scope you cab use Get-Command to display the commands (actually functions) avaialable from the module.

Note that the module currently includes three commands: Start-Fiddler, Receive-Fiddler and Stop-Fiddler. You can also use Get-Help to display information about each command. Here’s an example.


PS > Get-Help Start-Fiddler -Full

NAME
    Start-Fiddler

SYNOPSIS
    Uses FiddlerCore to listen on a specified port.

SYNTAX
    Start-Fiddler [-Path]  [-ListenPort]  [-RegisterAsSystemProxy] [-WhatIf] [-Confirm]
    []

DESCRIPTION
    Start-Fiddler loads the FiddlerCore DLL and uses Fiddler.FiddlerApplication to listen on a specified port.
    When http(s) traffic is generated Fiddler logs the traffic. The result is exposed through a job interface.
    Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification
    capabilities into your .NET application.

PARAMETERS
    -Path 
        Specifies the path to the assembly DLL file that contain the types (FiddlerCore.dll).

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -ListenPort 
        Specifies the Port that Fiddler listens to.

        Required?                    true
        Position?                    2
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -RegisterAsSystemProxy []
        Registers as the system proxy, default set to False.

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -WhatIf []

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -Confirm []

        Required?                    false
        Position?                    named
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, type,
        "get-help about_commonparameters".

INPUTS

OUTPUTS

NOTES

        Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and
        modification capabilities into your .NET application.

    -------------------------- EXAMPLE 1 --------------------------

    C:\PS>Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy

    Starts Fiddler and listens to Port 8877, registers as the system proxy.

    -------------------------- EXAMPLE 2 --------------------------

    C:\PS>Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy -Whatif

    Displays what would happen if you run Start-Fiddler.

RELATED LINKS

https://www.fiddler2.com/fiddler/core/

Let’s go ahead and start Fiddler and do some monitoring. As you might have guessed, the Start-Fiddler command uses Fiddler.FiddlerApplication to listen on a specified port. In the example below the -RegisterAsSystemProxy parameter is used. Internet Explorer and many other applications use the system proxy by default and are notified when it changes. When Start-Fiddler is used with the -RegisterAsSystemProxy parameter the Proxy Server checkbox in Local Area Network (LAN) Settings is checked.


PS > Start-Fiddler -Path C:\FiddlerCoreAPI\FiddlerCore.dll -ListenPort 8877 -RegisterAsSystemProxy

Here’s what happens to the Local Area Network (LAN) Setting in Internet Explorer when the RegisterAsSystemProxy parameter is used.

In the resource monitor you’ll also notice that PowerShell is Listening to the Port you specified as input to ListenPort.

The Start-Fiddler function actually loads the FiddlerCore DLL and uses Fiddler.FiddlerApplication to listen on a specified port. When starting Fiddler.FiddlerApplication the Startup() method is used, here’s a reference post. In this version the function only allows two inputs, ListenPort and RegisterAsSystemProxy. As soon as I get some time off, i’ll update the function (and module) to support even more cool fiddler stuff. Next, the function subscribes to an event using Register-ObjectEvent. In this version the arguments are simply outputted in the Action. Finally, two script variables are created. These are used to keep track of the Event and background job.

Now we can generate some traffic. Start up Internet Explorer and surf the web for a while. In this example I’m checking out www.bing.com.

When your done, type Receive-Fiddler in powershell.

Notice how the traffic generated from Internet Explorer is returned in PowerSHell. Pretty Cool.

The Receive-Fiddler function uses Receive-Job to get the result from the background job created by the event. The function also supports the -Keep parameter which allows you to save the results so that you can receive them again.

Let’s do some more fiddling. In this example I use Internet Explorer and navigate to www.powershell.nu. Back in PowerShell, I use Receive-Fiddler, but this time i store the result in a variable


PS > $result = Receive-Fiddler

Calling the variable displays the logged traffic.


PS > $result | Select-Object -First 1


BitFlags          : None
isHTTPS           : False
isFTP             : False
LocalProcessID    : 1040
SuggestedFilename : 190.txt
bypassGateway     : False
clientPort        : 49407
state             : ReadingResponse
PathAndQuery      : /
fullUrl           : http://www.powershell.nu/
url               : www.powershell.nu/
host              : www.powershell.nu
hostname          : www.powershell.nu
port              : 80
id                : 190
clientIP          : ::ffff:127.0.0.1
responseCode      : 0
bHasResponse      : False
bBufferResponse   : False
Timers            : ClientConnected: 21:14:29.027, ClientBeginRe
                    ateway Determination: 0ms, DNS Lookup: 13ms,
                    ected: 21:14:29.074,FiddlerBeginRequest: 21:
                    esponse: 21:14:30.715,ServerDoneResponse: 21
                    neResponse: 21:14:31.199, Overall Elapsed: 0
ViewItem          :
isTunnel          : False
oResponse         : Fiddler.ServerChatter
oRequest          : Fiddler.ClientChatter
oFlags            : {x-clientport, x-responsebodytransferlength,
requestBodyBytes  : {}
responseBodyBytes :
m_clientIP        : ::ffff:127.0.0.1
m_clientPort      : 49407
m_hostIP          : 217.25.34.124

There are a couple of properties available that contain logged information such as: fullUrl, hostnam, port and so on. Some properties contain simple string values and others contain objects with even more information. As an example, let’s see what oResponse contains.


PS > $result[0].oResponse


MIMEType            : text/html
iTTFB               : 1640
iTTLB               : 2125
bWasForwarded       : False
bServerSocketReused : False
headers             : HTTP/1.1 200 OK
                      Date: Tue, 15 Mar 2011 20:14:29 GMT
                      Server: Apache
                      X-Powered-By: PHP/5.2.16
                      X-Pingback: http://www.powershell.nu/xmlrpc.php
                      Keep-Alive: timeout=5, max=100
                      Connection: Keep-Alive
                      Transfer-Encoding: chunked
                      Content-Type: text/html; charset=UTF-8

pipeServer          :

When your done, use Stop-Fiddler to proparly remove the event, background job and Shut Down Fiddler. Here’s an example:


PS > Stop-Fiddler

Remember to use Stop-Fiddler to close the Fiddler connection. This is important, if you do not use Stop-Fiddler and simply shut down PowerShell the Local Area Network (LAN) Settings will not be unchecked and Internet Explorer may not work proparly.

What if i forgot to use Stop-Fiddler and closed my PowerShell session? Start Internet Explorer, Click on Internet Options/Connections/Local Area Network (LAN) Settings and uncheck “Use a proxy server for your LAN”..

Note that the Fiddler.psm1 module is not fully tested (or fully completed) and should be used in a test-envirnment only. With that said:

Click here to download Fiddler.psm1

Rating 3.00 out of 5
[?]
Categories: 2W, Fiddler Tags: ,

Second Wednesday

March 14th, 2011 No comments

The second Wednesday of each month LabCenter arranges a free Tech Meeting. The meeting starts at 5pm with some discussion, food and beverages before we go deeper into some exciting technology for the rest of the evening.

 

This week, I had the oppurtunity to do a presentation on Windows PowerShell and show some of the cool stuff that you can accomplish using Windows PowerShell in your IT-Environment.

My Demo’s included:

You can click each topic to see a description of the Demo and Code used.

Rating 3.00 out of 5
[?]
Categories: 2W, Demo Tags: ,

$Error

March 14th, 2011 No comments

This post is part of the Second Wednesday Demo Session, Click here for more info about additional demo posts.

The $error variable contains an array of errors generated in the current session. If we want to check the latest occured error we can type:


PS > cd C:\FolderThatDoesntExist

Set-Location : Cannot find path 'C:\FolderThatDoesntExist' because it does not exist.
At line:1 char:3
+ cd <<<<  C:\FolderThatDoesntExist
    + CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-Location], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

PS > $Error[0]

Set-Location : Cannot find path 'C:\FolderThatDoesntExist' because it does not exist.
At line:1 char:3
+ cd <<<<  C:\FolderThatDoesntExist
    + CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationC

We can also list detailed information about the error by pipe:ing the object to Format-List as shown below.


PS > $Error[0] | Format-List -Force


Exception             : System.Management.Automation.ItemNotFoundException: Cannot fi
                         because it does not exist.
                           at System.Management.Automation.LocationGlobber.ExpandMshG
                        NonexistingPaths, PSDriveInfo drive, ContainerCmdletProvider
                        ntext)
                           at System.Management.Automation.LocationGlobber.ResolveDri
                        tProviderContext context, Boolean allowNonexistingPaths, Cmdl
                           at System.Management.Automation.LocationGlobber.GetGlobbed
                        h, Boolean allowNonexistingPaths, CmdletProviderContext conte
                        ce)
                           at System.Management.Automation.SessionStateInternal.SetLo
                        Context context)
                           at System.Management.Automation.PathIntrinsics.SetLocation
                        t context)
                           at Microsoft.PowerShell.Commands.SetLocationCommand.Proces
TargetObject          : C:\FolderThatDoesntExist
CategoryInfo          : ObjectNotFound: (C:\FolderThatDoesntExist:String) [Set-Locati
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {0, 1}
PSMessageDetails      :

If we want to count the number of errors in the $error variable we use the Count property.


PS > $error.Count

1

And we can even clear the error list by using the Clear() method.


PS > $error.Clear()

The number of errors that are listed in the $error variable is determined in $MaximumErrorCount. By default the variable is set to 256, meaning that the error
list holds a maximunm of 256 errors. We can, of course change this to a higher number by typing:


PS > $MaximumErrorCount = 500

Rating 4.00 out of 5
[?]
Categories: 2W, Error Tags: ,