Thursday, July 2, 2015

Powershell Useful Command Collection

RUN AS
C:\>runas /user:<DomainName>\<AdministratorAccountName> cmd

**************************REMOTE ACCESS******************************

Remote Session (Requires Powershell 3.0)
Enter-PSSession hostname

Enable WINRM on Windows 7
The WinRM service is configured for manual startup by default. You must change the startup type to Automatic and start the service on each computer you want to work with. At the PowerShell prompt, you can verify that the WinRM service is running using the following command: 
Get-Service -Name WinRM -ComputerName NAME
The value of the Status property in the output should be “Running”.

To configure Windows PowerShell for remoting, type the following command: 
Enable-PSRemoting –force

*****************************STANDARD STUFF***************************

Start a service on a remote computer
Get-Service -ComputerName CNUMBER -name SERVICENAME | Start-Service

To Install Windows Administrative Tools
Install-WindowsFeature RSAT-Feature-Tools

Check local Administrators group members
Net localgroup administrators

Get Newest 10 events in eventlogs
get-eventlog -LogName Security (or other log name) -Newest 10

Get Eventlog events on remote computer, amount of events, per eventID, formated to a table.
$Machine = "LocalHost"
Get-Eventlog -Logname System -ComputerName $Machine -newest 1000 | 
Where-Object {$_.EventID -lt '100'} | 
Format-Table MachineName, Source, EventID -auto


Get Running Services from another computer
Get-Service -ComputerName HOSTNAME |where-object {$_.Status -eq "Running"}

Get Running Process from another computer
Invoke-Command -ComputerName HOSTNAME -ScriptBlock {Start-Process NAME}

Last Boot time of remote server

$LastBootUpTime = Get-WmiObject Win32_OperatingSystem -Comp HOSTNAME | Select -Exp LastBootUpTime
[System.Management.ManagementDateTimeConverter]::ToDateTime($LastBootUpTime)

Last Boot time of remote server

Get-WmiObject Win32_OperatingSystem -computer HOSTNAME | Select CSNAME @{N='LastBoot';E={[System.Management.ManagementDateTimeCOnverter]::ToDateTime($_.LastBootUpTime)}}

Last Boot time of local server

PS C:\> $wmi = gwmi win32_operatingsystem
PS C:\> $wmi.ConvertToDateTime($wmi.LastBootUpTime)
Friday, August 22, 2014 4:39:23 AM



Get last boot time

Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime


Restart a remote computer
Restart-Computer -ComputerName HOSTNAME -Force

****************************BIT LOCKER********************************

Bitlocker Drive Status
Manage-dbe -status

***************************SCCM Configuration Manager******************

Get last three items of SCCM SMSPXE log
get-content -Path "\\server\drive$\Program Files\Microsoft Configuration Manager\Logs\SMSPXE.log" -Tail 3


Get installed application list on hostname
Get-WmiObject -ComputerName  HOSTNAME -class Win32_product
or
Get-WmiObject -ComputerName  HOSTNAME -class Win32Reg_AddRemovePrograms (SCCM Client Only)


Get any USB storage devices attached to your computer
Get-WmiObject -Class Win32_PnPEntity | Where-Object { $_.DeviceID -like 'USBSTOR*' }
Or
IN WMI Query
Get-WmiObject -Query 'Select * From Win32_PnPEntity where DeviceID Like "USBSTOR%"

This command will return the total number of bytes of the 32 largest files in the folder without listing the file names.

$big32 = Get-ChildItem C:\Users\ -recurse | Sort-Object length -descending | select-object -first 32 | measure-object -property length –sum
$big32.sum /1gb





***************ACTIVE DIRECTORY ********************************

Get add AD Users like "*shawn*" and formats list

Get-ADUser -Filter 'SamAccountName -like "*shawn*"' | FT SamAccountName -A

Get-ADUser -Filter 'SamAccountName -like "*shawn*"' | FT SamAccountName,GivenName,Name -A

SamAccountName GivenName Name              
--------------                ---------          ----              
shawn                        Shawn       Shawn Dunham      
shawnwise                Shawn       Shawn Dunham - Wise
shawntest                 Shawn       Shawn Dunham Test 


Get-AD User Name like "Dunham"
Get-ADUser -Filter 'Name -like "*Dunham"' | FT


Disting Enabled GivenNa Name    ObjectC ObjectG SamAcco SID     Surname UserPri
uishedN         me              lass    UID     untName                 ncipalN
ame                                                                     ame   
------- ------- ------- ----    ------- ------- ------- ---     ------- -------
CN=M...    True Marg... Marg... user    ca01... 60146   S-1-... Kobe    6014...
CN=D...    True Daniel  Dani... user    9931... 91620   S-1-... Kobe    9162...


Get-AD Computers (servers) like windows server) and total numbers
Get-ADComputer -LDAPFilter "(OperatingSystem=*windows server*)" | Measure-Object

Count    : 605
Average  :
Sum      :
Maximum  :
Minimum  :
Property :


Get-ADUser Created and Modified Dates
Get-ADUser 'shawn' -Properties Created,Modified | Select-Object Name,Created,Modified | Sort-Object Created

Get-ADUsers Created 7 days before today's date. Export to CSV
$When = ((Get-Date).AddDays(-7)).Date
Get-ADUser -Filter {whenCreated -ge $When} -Properties whenCreated | Export-Csv C:\Myscripts\GetDateCreated.csv


**********************************************************************

Open Web Page
#requires -Version 2

function Show-WebPage
{
    param
    (
        [Parameter(Mandatory = $true, HelpMessage = 'URL to open')]
        $URL
    )

    Start-Process -FilePath iexplore.exe -ArgumentList $URL
}


Create “Task Kill” Application

With just one pipeline command, PowerShell can open a list of running applications. You can then select one or more in the list (hold CTRL to select more than one), and PowerShell would kill the selected applications.

Get-Process |
  Where-Object { $_.MainWindowHandle -ne 0 } |
  Select-Object -Property Name, Description, MainWindowTitle, Company, ID |
  Out-GridView -Title 'Choose Application to Kill' -PassThru |
  Stop-Process -WhatIf

Note how the code uses –WhatIf to only simulate the kill. Remove –WhatIf to actually kill applications.
Killing applications will stop the selected applications immediately. All unsaved data is lost.


Moving Outdated Log Files to Archive

Occasionally, you may want to move files to an archive folder when they are older than a given number of days.
Here is an example that illustrates the basic strategy on how to identify outdated files, and how to move them to an archive:

#requires -Version 1
# how old (in days) would obsolete files be
$Days = 14

# where to look for obsolete files
$Path = $env:windir
$Filter = '*.log'

# where to move obsolete files
$DestinationPath = 'c:\archive'

# make sure destination folder exists
$destinationExists = Test-Path -Path $DestinationPath
if (!$destinationExists)
{
    $null = New-Item -Path $DestinationPath -ItemType Directory
}

$cutoffDate = (Get-Date).AddDays(-$Days)

Get-ChildItem -Path $Path -Filter $Filter -Recurse -ErrorAction SilentlyContinue |
Where-Object -FilterScript {
    $_.LastWriteTime -lt $cutoffDate
} |
Move-Item -Destination c:\archive -WhatIf

The example script looks for log files with the extension *.log inside the Windows folder and all of its subfolders. Any log file older than 14 days (defined as not being modified within the past 14 days) is moved to c:\archive. This folder is created if it does not yet exist.
Note that this is only an example. You would need Administrator privileges to actually move files out of the Windows folder.

Tuesday, June 18, 2013

How to Install SCCM 2012 Linux Unix client

SCCM 2012 Client on Linux and UNIX

Test machines I used were SCCM 2012 w/SQL 2012 (VM) and Linux Unbutu 32bit 12.04 (VM) client (details below)



First some standard Microsoft stuff so you don’t have to search a great deal followed by what I needed to do to get the client installed.



To install the client for Linux and UNIX, you run a script on each Linux or UNIX computer. The script is named install and supports command line properties that modify the installation behavior and reference the client installation package. The install script and client installation package must be located on the client. The client installation package contains the Configuration Manager client files for a specific Linux or UNIX operating system and platform. Each client installation package contains all the necessary files to complete the client installation and unlike Windows-based computers, does not download additional files from a management point or other source location. After you install the Configuration Manager client for Linux and UNIX, you do not need to reboot the computer. As soon as the software installation is complete, the client is operational. If you reboot the computer, the Configuration Manager client restarts automatically.
Following is the command format: ./install -mp <computer> -sitecode <sitecode> <property #1> <property #2> <client installation package>

Command line
Actions
./install –mp smsmp.contoso.com -sitecode S01 ccm-Universal-x64.<build>.tar
·    install is the name of the script file that installs the client for Linux and UNIX. This file is provided with the client software. 
·    -mp smsmp.contoso.com specifies the initial management point that is used by the client.
·    -sitecode S01 specifies the client is assigned to the site with the site code of S01.
·    ccm-Universal-x64.<build>.tar is the name of the client installation .tar package for this computer operating system, version, and CPU architecture. 

You can insert additional command line properties before the command line property that specifies the client installation .tar file. The client installation .tar file must be specified last.


Use the following procedure as an example of how to install the client for Linux and UNIX.
noteNote
The following example procedure installs the client from the cumulative update 1 release of the client for Linux and UNIX on a Red Hat Enterprise Linux 5 (RHEL5) x64 computer. To adjust this procedure for the operating systems that you use, replace the client installation file (ccm-Universal-x64.<build>.tar) with the applicable package for the computer where you are installing the client. Also plan to use additional command line properties to meet your requirements.




  1. Copy the install script and the client installation .tar file to a folder on the RHEL 5 x64 based computer.
  2. On the RHEL5 computer, use root credentials to run the following command to enable the script to run as a program: chmod +x install
  3. Next, with root credentials, run the following command to install the Configuration Manager client: ./install –mp <hostname> -sitecode <code> ccm-Universal-x64.<build>.tar
When you enter this command, use additional command-line properties you require.
  1. After the script runs, validate the install by reviewing the /var/opt/microsoft/scxcm.log file. Additionally, you can confirm that the client is installed and communicating with the site by viewing details for the client in the Devices node of the Assets and Compliance workspace in the Configuration Manager console.


When you install the client for Linux and UNIX on a Linux or UNIX computer, you run the install script with command-line properties that specify the following:
  • The client’s assigned site.
  • The management point with which the client initially communicates
  • The client installation .tar file for the computer’s operating system
  • Additional configurations you require
The properties described in the following table are available to modify the installation behavior.
noteNote
Use the property -h to display this list of supported properties.

Property
Required or optional
More information
-mp <server FQDN>
Required
Specifies by FQDN, the management point server that the client will use as an initial point of contact.
ImportantImportant
This property does not specify the management point to which the client will become assigned after installation.
noteNote
When you use the -mp property to specify a management point that is configured to accept only HTTPS client connections, you must also use the -UsePKICert property.
Specify the management point by FQDN.
-sitecode <sitecode>
Required
Specifies the Configuration Manager primary site to assign the Configuration Manager client to. Example: -sitecode S01
-fsp <server_FQDN>
Optional
noteNote
Beginning with cumulative update 1, the Configuration Manager client for Linux and UNIX supports the use of fallback status points.
Specifies by FQDN, the fallback status point server that the client uses to submit state messages.
For more information about the fallback status point, see the Determine Whether You Require a Fallback Status Point section in the Determine the Site System Roles for Client Deployment in Configuration Managertopic.
-dir <directory>
Optional
Specifies an alternate location to install the Configuration Manager client files.
By default, the client installs to the following location: /opt/microsoft.
-nostart
Optional
Prevents the automatic start of the Configuration Manager client service, ccmexec.bin, after the client installation completes.
After the client installs, you must start the client service manually.
By default, the client service starts after the client installation completes, and each time the computer restarts.
-clean
Optional
Specifies the removal of all client files and data from a previously installed client for Linux and UNIX, before the new installation starts. This removes the client’s database and certificate store.
-keepdb
Optional
Specifies that the local client database is retained, and reused when you reinstall a client. By default, when you reinstall a client this database is deleted.
-UsePKICert <parameter>
Optional
Specifies the full path and file name to a X.509 PKI certificate in the Public Key Certificate Standard (PKCS#12) format. This certificate is used for client authentication.
When you use -UsePKICert, you must also supply the password associated with the PKCS#12 file by use of the-certpw command line parameter.
If the certificate is not valid, or cannot be found, the client falls back to use HTTP and a self-signed certificate.
If you do not use this property to specify a PKI certificate, the client uses a self-signed certificate and all communications to site systems are over HTTP.
noteNote
You must specify this property when you install a client and use the -mp property to specify a management point that is configured to accept only HTTPS client connections.
Example: -UsePKICert <Full path and filename> -certpw <password>
-certpw <parameter>
Optional
Specifies the password associated with the PKCS#12 file that you specified by use of the -UsePKICertproperty.
Example: -UsePKICert <Full path and filename> -certpw <password>
-NoCRLCheck
Optional
Specifies that a client should not check the certificate revocation list (CRL) when it communicates over HTTPS by use of a PKI certificate. When this option is not specified, the client checks the CRL before establishing an HTTPS connection by use of PKI certificates. For more information about client CRL checking, see Planning for PKI Certificate Revocation.
Example: -UsePKICert <Full path and filename> -certpw <password> -NoCRLCheck
-rootkeypath <file location>
Optional
Specifies the full path and file name to the Configuration Manager trusted root key. This property applies to clients that use HTTP and HTTPS client communication. For more information, see Planning for the Trusted Root Key.
Example: -rootkeypath <Full path and filename>
-httpport
Optional
Specifies the port that is configured on management points that the client uses when communicating to management points over HTTP. If the port is not specified, the default value of 80 is used.
Example: -httpport 80
-httpsport
Optional
Specifies the port that is configured on management points that the client uses when communicating to management points over HTTPS. If the port is not specified, the default value of 443 is used.
Example: -UsePKICert <Full path and certificate name> -httpsport 443
-ignoreSHA256validation
Optional
Specifies that client installation skips SHA-256 validation. Use this option when installing the client on operating systems that did not release with a version of OpenSSL that supports SHA-256. For more information, see the About Linux and UNIX Operating Systems That do not Support SHA-256 section in thePlanning for Client Deployment for Linux and UNIX Servers topic.
-signcertpath <file location>
Optional
Specifies the full path and .cer file name of the exported self-signed certificate on the site server. This certificate is stored in the SMS certificate store and has the Subject name Site Server and the friendly nameSite Server Signing Certificate.
This certificate is used by the client for all HTTP and HTTPS communications with management points and distribution points.
Example: -signcertpath=<Full path and file name>



-rootcerts
Optional
If multiple root certificates exist in the Configuration Manager environment, you can specify additional root certificates that the client might need to validate site system servers.
Example: -rootcerts=<Full path and file name>,<Full path and file name>

Now here is the simple breakdown...

Download Here:

Install Instructions:
Mac Client:
1.     Download the Mac client msi file to a Windows system
2.     Run the msi and it will create a dmg file under the default location “C:\Program Files (x86)\Microsoft\System Center 2012 Configuration Manager Mac Client” on the Windows system
3.     Copy the dmg file to a network share or a folder on a Mac computer
4.     Access and open the dmg file on a Mac computer and install the client using instructions in the online documentation. http://technet.microsoft.com/en-us/library/jj591553.aspx

Unix/Linux Clients:
5.     Download the appropriate file for the UNIX/Linux operating system you wish to manage to a Windows computer
6.     The downloaded file is a self-extracting exe and will extract tar files for the different versions of your operating system.
7.     Copy the install script and the .tar file for your computer’s operating system version to a folder on your UNIX/Linux computer.
8.     Install the client using instructions in the online documentation.http://technet.microsoft.com/en-us/library/jj591553.aspx

So here is another fun part – You need to copy your files extracted from the .exe download (After you have extracted in Windows) to your Linux OS clients, Copy whichever architecture .tar file and the install script. To do so:
1.     Make sure SSH and PSCP are enabled on your Linux client/server and Firewalls are appropriate. For the time being I disabled my test machine firewall.
a.     How to see if firewall is active or not
                                i.    sudo iptables –L –n
b.     Sample output
                           
c.     How to save firewall rules
                                 i.    sudo iptables-save >firewall.rules
d.     How to stop firewalls
                                 i.    sudo iptables –X
                                ii.    sudo iptables –t nat –F
                               iii.    sudo iptables –t nat -X
                               iv.    sudo iptables –t mangle -F
                                v.    sudo iptables –t mangle –X
                               vi.    sudo iptables –P INPUT ACCEPT
                              vii.    sudo iptables –P FORWARD ACCEPT
                             viii.    sudo iptables –P OUTPUT ACCEPT

a.     Download the executable (.exe) from the link and launch a command line from the working directory you saved the PSCP executable.
b.     BUT WAIT THERE'S MORE…
c.     Run your command which should resemble the following
(Pscp c:\directory of .tar files and script extracted download\ccm-linux client name account@ipaddress of linux client(destination):/linux/destination/directory/)
i.e. pscp E:\source\NonWindowsOSSCCMClients\ccm-Universalx86.1.0.0.4648.tar shawn@ipaddress:/home/shawn/Downloads/
shawn@ipaddress’s password:



Command line to enable script to run as a program. After you download and move the script you need to enable the script w/execute privileges.
use root credentials to run the following command to enable the script to run as a program: chmod +x install











Command install line
Root@directory# ./install –mp servername.fqdn –sitecode ccm-client.tar
Following is the command format: ./install -mp <computer> -sitecode <sitecode> <property #1> <property #2> <client installation package>