Wednesday, November 30, 2016

Tuesday, November 22, 2016

Random Numbers and File Testing

Just a little test script. 
Random numbers and File object test....
Goes Nowhere Does Nothing


$random = get-random -maximum 20
echo $random
if ($random -like "?8")
    {
    echo "bang"
    }
if ($random -eq 2)
    {
    echo "2 ME"
    }

$WinUpdLog = "C:\Windows\WindowsUpdate.log"
$values = Get-ItemProperty $WinUpdLog

if ($values.Length -le 1500000)
    {
    echo "Low"
    }
else
    {echo "High"}

Monday, November 21, 2016

Delete a registry key queried from WMI





$key = "hklm:\software\microsoft\windows\currentversion\appx"

$LastUserSID = get-wmiobject -namespace root\CIMV2 -Class Win32_UserProfile | select LastUseTime,SID | sort lastusetime -Descending | select -expand SID -first 1

$target = $key+"\"+$LastUserSID

Remove-Item $target -Recurse



Use Remove-ItemProperty to target individual values for removal

Remove-ItemProperty -Path "HKLM:\Software\SmpApplication" -Name "SmpProperty"

Friday, November 18, 2016

The power of the group - oh and arrays


To find the number of occurrences of items in an array, the group object is fantastic.

Say you have a variable containing an array with a big list of names which are in the array multiple times.  This command returns how many times each name occurs in the array.  Easy or what?

#Create the Array Variable
$ArrayVariable = New-Object System.Collections.Generic.List[System.Object]

#Define a bunch of groups
$GroupsList = get-adgroup -filter {name -like "GROUP-G-*Bentley*" -or name -like "GROUP-G-*Microstation*"} | select -expand name | sort name

#Put all the users in all the group into an array
foreach ($Group in $GroupsList)

    {
    $GroupUsers = Get-ADGroupMember $Group | where {$_.objectclass -eq "user"} | select -expand samaccountname

    foreach ($GroupUser in $GroupUsers)
        {
        $AllFoundUsersArray.Add($GroupUser)
        echo $GroupUser
        }
     }


#Display the number of groups each user is in.
$ArrayVariable | group | sort count -Descending | select name,count

Output:

Name            Count
----               ----
John              5
Alice             4
Bob              3
Tim               2
Baltar           1

Now check out this neat trick.  Reverse the array order :)

[array]::Reverse($ArrayVariable)



Monday, November 7, 2016

The size limit for this request was exceeded


get-adgroupmember is unable to return results when the number of members is very high.  To work around this use the get-adobject cmdlet with a LDAPFilter as follows

Get-ADObject -LDAPFilter "(memberOf=CN=MyGroupName,OU=OUNAME1,OU=OUNAME2,OU=OUNAME3,DC=xxx,DC=xxx,DC=local)" | where {$_.ObjectClass -eq "user"} | measure



Use this get-adobject string to get the objects like groups in an OU

Get-ADObject -Filter {Name -like "*"} -Searchbase 'OU=UserAccounts,DC=Fabrikam,DC=com'

https://technet.microsoft.com/en-us/library/dd391882%28v=ws.10%29.aspx

Thursday, August 25, 2016

Run Remote Powershell sessions


To prep a machine for a remote powershell session
  • Start the Windows Remote Management (WS-Management) Service on the remote machine.
  • psexec \\machinename cmd -i
  • winrm quickconfig
Once these tasks are complete you can run a remote powershell session in Powershell ISE.  Start this from File_New Remote Powershell Tab

The session displays the machine name at the prompt to signify that the commands are directed at the remote machine.

More here
http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/

Sunday, August 21, 2016

Change the file date


Here's a little look at file properties and particularly changing the date.

This lists all the properties you might want to use/set/mess with

get-item "c:\test.txt" | get-member *

This list the time relevent properties

get-item "c:\test.txt" | get-member *time

This changes the CreationTime (remember to use US date format)

get-item "c:\test.txt" | % {$_.CreationTime = '07/28/2016 15:28'}

keywords metadata

Here's an explanation of the % sign usage courtesy of Jeffery Hicks who posted this here


The % symbol is also an alias for ForEach-Object. You would use it in an
expression like this:

cat servers.txt | % { get-wmiobject win32_operatingsystem -computer $_}

And you're right, it is also the modulo operator. In the example you saw,
the expression went through numbers 0 to 15 and formatted them using the -f
operator. The $_ is the current object in the pipeline, ie the numbers 0
through 15.

Hope this explanation helps.

--
Jeffery Hicks MCSE, MCSA, MCT
Microsoft PowerShell MVP

Friday, August 5, 2016

Loops and Call


This is an example of a loop and a call to launch an executable.

This link has examples of other loop types
http://www.winserverhelp.com/2010/04/powershell-tutorial-loops-for-foreach-while-do-while-do-until/2/




# after logon, check for a appv package to be present and then launch it when available.
$IsTextHelpPublishedForMe = $Null

$Count =0
While ($Count -le 10)
    {
       
        $IsTextHelpPublishedForMe = Get-AppvClientPackage -packageid 3227A4B4-269A-4970-84B5-302DC1255E40 | select -expand IsPublishedToUser
                       
        If ($IsTextHelpPublishedForMe -eq "True")
       
            {
            $target = $env:LOCALAPPDATA+"\Microsoft\AppV\Client\Integration\3227A4B4-269A-4970-84B5-302DC1255E40\Root\ReadAndWrite.exe"
            & $target
            exit
            }
       
        Else
            {
            #integer is seconds to wait
            Start-Sleep -s 5
            $Count; $Count +=1
            }
    }

Thursday, August 4, 2016

Real World

This post will be updated with Real World quick powershell uses.....

How many Citrix servers are there?
Get-ADComputer -Filter {name -like "*Citrix*Server*Naming*Convention*Pattern*"} | measure

Friday, June 3, 2016

Quickies


Boolean existence check
Test-Path -Path <Path to check>
returns True or False

Split a variable into two new variables
$RemGroupID, $RemVersionID = $CGDef.Split(" ",2) 

Get  the logged on User SID
$GetUserSID = whoami.exe /USER /NH
$UserName, $UserSID = $GetUserSID.Split(" ",2)

Get the latest file and create an object with no empty lines
#get the most recent *CGClearList.txt file
$CGCLFileLoc = $env:PUBLIC+"\*CGClearList.txt"
$CGCLFile = get-childitem $CGCLFileLoc | sort lastwritetime | select -last 1 -expand Name
$CGCLFileLoc = $env:PUBLIC+"\"+$CGCLFile


#Create an object with no empty lines
$CGCLObj = get-content $CGCLFileLoc | where {$_ -ne ""}
 

Get the a user's logon history -it will probably return events of GroupPolicy associated with the user logging on.
Get-Eventlog system -username *<username>


Search for users in a target OU with a property which matches a critera
get-aduser -SearchBase "OU=xxx,OU=xxx,OU=Administration,DC=xxx,DC=xxx,DC=local" -Properties employeeid -Filter {name -like "*"} | ?{$_.employeeid -notlike $null} | select name,employeeid

List all the properties for the class
get-wmiobject -computername "$TargetName" -namespace root\CIMV2 -Class Win32_OperatingSystem |sort name |select-object [a-z]*

Check a file exists
if ([System.IO.File]::Exists($FilePath))

Create an Array
$myarray = @(1,2,3)

List Environmental Variables
dir env:

Crazy File copy command - This copies all the files in the subdirectories to the current directory.  Run it from the folder where you want all the files copied to
Copy-item -path C:\test\music -filter *.mp3 -recurse -Container:$false

Tabs and Character Returns
$line = "1"+"`t"+"2"+"`r`n"+"3"
$line
Outputs
1    2
3

Thursday, June 2, 2016

Clear or Remove your variables.


Variables hanging around could be not what you want.

Remove-Variable -Name *

Clear-Variable -Name 

or indeed just get them

Get-Variable

Friday, May 20, 2016

Enable Preview of ps1 files in Windows Explorer


One liner, works instantly, no restart of explorer required.

Set-ItemProperty Registry::HKEY_CLASSES_ROOT\.ps1 -Name PerceivedType -Value text

Monday, May 16, 2016

Text manipulation


Replace, Remove

A simple character removal from a string
$SapSName = "El-Asswi"
If ($SapSName -like "*-*")
        {
        $SapSName = $SAPSName.Replace("-","")
        }
$SapSName


The following manipulates this $DeploymentTypeRef


<DeploymentTypeReference AuthoringScopeId="ScopeId_AA0BA009-8B99-4F9F-A54D-4E5F3F43F0FA" LogicalName="DeploymentType_a1c9acc4-a0fa-4f79-b0a0-b0da75418f9d" Changeable="true" />

into this $DeploymentTypeRefExtract

ScopeId_AA0BA009-8B99-4F9F-A54D-4E5F3F43F0FA/DeploymentType_3d3239d1-e3dd-4be0-bcbf-cde7e0a84c7f



$DeploymentTypeRefExtract = $DeploymentTypeRef.Remove(0,61).Replace(""" LogicalName=","").Replace("""DeploymentType","/DeploymentType").Replace(""" Changeable=","").Replace("true"" />","").Replace("""","")

Thursday, May 12, 2016

out-file

out-file is brilliant.  It is so helpful to get stuff out into txt files both for logging what has happened but also for helping you during the script design to understand what is  going on.

The best why to do it is to create a the variable which specifies the output file name.  You can even use variables to create the variable which can be very useful.

During testing it is useful to write stuff out to public which is always successful regardless of the user context the script is running it.


$OutputFile = $env:PUBLIC+"\Documents\"+$AnotherVar+".txt"

command | out-file $OutputFile

Thursday, May 5, 2016

Use of NULL


$null is available to represent nothing.  You can use this if you need to check for nothing, or indeed, "not nothing" i.e. something.  This command is an example of its use.  In this case it only returns items where the ExcludeFileList value in not blank or null.

Get-WmiObject -Namespace ROOT\ccm\SoftMgmtAgent -Class CacheInfoEx | where {$_.excludefilelist -notlike $null}

Wednesday, May 4, 2016

Customise the powershell prompt

When you're happily typing powershell commands all day long, you may want to check when you executed a particular command.

With this little bit of code you can configure the prompt to record the day, time and location so that the powershell window can be a record of when each command was run.

One liner !

function prompt {$(get-date -UFormat %d/%m) + " " + $(get-date -UFormat %H:%M) + " " + $(get-location) +" > "}

Tuesday, February 16, 2016

Quest AD Powershell cmdlets



https://support.software.dell.com/download-install-detail/5024645

Run this command to make the cmdlets available in Powershell ISE

import-module -name "C:\Program Files\Quest Software\Management Shell for AD\ActiveRolesManagementShell" -Verbose

Thursday, February 4, 2016

Check a machine is valid.

This was part of a solution to check that a PC was a valid PC to launch on.  I've posted it here to illustrate several techniques including deleting files, generating files, evaluating variables, block coments and querying machine information using WMI.

-computername <machname> can direct a get-wmiobject query to a remote machine


#reset
Remove-Item ".\Application Data\Folder\PCValid.txt"
#read current PC name
$machname = get-wmiobject -namespace root\CIMV2 -Class Win32_ComputerSystem | select -expand name
#read AssignedPC.txt
$AssignedPC = get-content ".\Application Data\Folder\AssignedPC.txt"
# create a file if the values match.
if ($machname -eq $AssignedPC) {out-file ".\Application Data\Folder\PCValid.txt"}

<#
This is a block comment
#>