11 November 2016

Start SAFE MODE if Windows 7,8,10 didn't start

Boot from any boot USB and open command prompt
If this SCCM USB flash memory when you will see password windows request type F8 to open command line

After the command system prompt, enter the command for the safe mode option you want. Enter the information exactly.

Enable Safe Mode - Type:
bcdedit /set {default} safeboot minimal and press Enter.

Enable Safe Mode with Networking - Type:
bcdedit /set {default} safeboot network and press Enter.

Enable Safe Mode with Command Prompt - Type:
bcdedit /set {default} safeboot minimal and press Enter:
bcdedit /set {default} safebootalternateshell yes and press Enter.

The computer responds with the operation completed successfully when you have entered the command correctly.

Notice: This changing is permanent so for EXIT from safemode
Type the following command to exit Safe Mode:
bcdedit /deletevalue {default} safeboot and press Enter.


If Windows can start when you restart computer hold “Shift” key and after we can see start up option for troubleshooting (on Windows XP same as Windows 7 this is F8 when computer started).

31 October 2016

Low space issue

Very common trouble on corporative network that have laptop/computer with small hard drive or small SSD same as used by several persons especially if are working on Outlook
As example HP Elite Book Revolver 810 G1 (hard drive 120 GB) have 200 MB Free Space

First start any Space Analyzer like SpaceSniffer as Administrator to have access system and users folders and receive actual information. If you will see lot off Application Data that have big size it’s mean or probably .ost (Outlook) file or personal data. Remember - if .ost file have size 50 GB and more user can't send/receive e-mail. Same as from 25..30 till 50 GB can have trouble send/receive functions. We can delete .ost files use PowerShell script: OST_Delete.ps1
Function Convert-Size {
    <#
        .SYSNOPSIS
            Converts a size in bytes to its upper most value.

        .DESCRIPTION
            Converts a size in bytes to its upper most value.

        .PARAMETER Size
            The size in bytes to convert

        .NOTES
            Author: Boe Prox
            Date Created: 22AUG2012

        .EXAMPLE
        Convert-Size -Size 568956
        555 KB

        Description
        -----------
        Converts the byte value 568956 to upper most value of 555 KB

        .EXAMPLE
        Get-ChildItem  | ? {! $_.PSIsContainer} | Select -First 5 | Select Name, @{L='Size';E={$_ | Convert-Size}}
        Name                                                           Size                                                         
        ----                                                           ----                                                         
        Data1.cap                                                      14.4 MB                                                      
        Data2.cap                                                      12.5 MB                                                      
        Image.iso                                                      5.72 GB                                                       
        Index.txt                                                      23.9 KB                                                      
        SomeSite.lnk                                                   1.52 KB    
        SomeFile.ini                                                   152 bytes  

        Description
        -----------
        Used with Get-ChildItem and custom formatting with Select-Object to list the uppermost size.         
    #>
    [cmdletbinding()]
    Param (
        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias("Length")]
        [int64]$Size
    )
    Begin {
        If (-Not $ConvertSize) {
            Write-Verbose ("Creating signature from Win32API")
            $Signature =  @"
                 [DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
                 public static extern long StrFormatByteSize( long fileSize, System.Text.StringBuilder buffer, int bufferSize );
"@
            $Global:ConvertSize = Add-Type -Name SizeConverter -MemberDefinition $Signature -PassThru
        }
        Write-Verbose ("Building buffer for string")
        $stringBuilder = New-Object Text.StringBuilder 1024
    }
    Process {
        Write-Verbose ("Converting {0} to upper most size" -f $Size)
        $ConvertSize::StrFormatByteSize( $Size, $stringBuilder, $stringBuilder.Capacity ) | Out-Null
        $stringBuilder.ToString()
    }
}
function Find-File([string]$folderPath)
{
    if (Test-Path $folderPath)
    {
        try
        {
            [string[]]$childFolderPaths = [System.IO.Directory]::GetDirectories($folderPath)
            foreach($childPath in $childFolderPaths)
            {
                [System.IO.DirectoryInfo]$di = New-Object System.IO.DirectoryInfo($childPath)
                if (($di.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne [System.IO.FileAttributes]::ReparsePoint)
                {
                    <#
                    This is the recursive part. That is, this function calls itself in order to process child directories.
                    #>
                   Find-File $childPath
                }
            }
            [string[]]$filePaths = [System.IO.Directory]::GetFiles($folderPath, "*.*", [System.IO.SearchOption]::TopDirectoryOnly)
            foreach($filePath in $filePaths)
            {
                <#
                Here is where you'd take whatever action you want. I'm looking for files named AssemblyInfo.cs and displaying their full paths.
                #>
          
                if (([System.IO.Path]::GetFileName($filePath)) -like "*.ost")
                {
                    #Write-Host $filePath -ForegroundColor DarkGreen
                    Return $filePath
                }
            }
        }
        catch
        {Write-Host ($Error[0]) -ForegroundColor Red}
    }
}
#5297

cls
$AllUsersPath = "C:\Users"
$AllUsersPath = get-ChildItem $AllUsersPath -Name
for($counter = 0; $counter -lt $AllUsersPath.Count; $counter++)
    {
    #$AllUsersPath[$counter]
    $OST_Folder = "C:\users\"
    $OST_Folder += $AllUsersPath[$counter]
    $OST_Folder += "\AppData\Local\Microsoft\Outlook"
    #$OST_Folder
    if ((Test-Path -Path $OST_Folder) -eq $true)
        {
        if ((get-ChildItem $OST_Folder | where { $_.Extension -eq ".ost"}).Exists -eq $true)
            {
            $result = Find-File $OST_Folder
            $result_size = Convert-Size -Size ((Get-ItemProperty $result).Length)
            Write-Host "Do you want delete?"
            Write-Host "file name: " -ForegroundColor White -NoNewline
            Write-Host $result -ForegroundColor Green
            Write-Host "file size: " -NoNewline -ForegroundColor White
            Write-Host $result_size -ForegroundColor Green
            Write-Host "-------------------"
            $delete_request = Read-Host " Yes; any key - not"
            switch ($delete_request)
                {
                'y' {
                    cls
                    remove-Item $result; Write-Host "OST file "
                    Write-Host "file name: " -ForegroundColor White -NoNewline
                    Write-Host $result
                    Write-Host "file size: " -ForegroundColor White -NoNewline
                    Write-Host $result_size
                    Write-Host " DELETED" -ForegroundColor Green}
                default {
                        cls
                        Write-Host "OST file "
                        Write-Host "file name: " -ForegroundColor White -NoNewline
                        Write-Host $result
                        Write-Host "file size: " -ForegroundColor White -NoNewline
                        Write-Host $result_size
                        Write-Host " NOT DELETED" -ForegroundColor Red
                        }
                }
            }
        }
    }
Write-Host "-------------------"
Write-Host "script FINISHED" -ForegroundColor Green
Same can have free space profit by delete Search database (can have size 50 GB)
c:\>sc config wsearch start= disabled
c:\>sc stop wsearch
c:\>del C:\ProgramData\Microsoft\Search\Data\Applications\Windows\Windows.edb
and disable Hybernate mode (profit – 2..8 GB)
c:\>powercfg.exe /hibernate off
don’t forget check and clean if need “C:\Windows\ccmcache” and windows update folder same
P.S. Below start powershell script from command line and auto request UAC window for start as administrator. Script must be located on same folder where PS script: Start-Delete_OST.bat
::::::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights V2
::::::::::::::::::::::::::::::::::::::::::::
@echo off
CLS
ECHO.
ECHO =============================
ECHO Running Admin shell
ECHO =============================

:init
setlocal DisableDelayedExpansion
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion

:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
ECHO.
ECHO **************************************
ECHO Invoking UAC for Privilege Escalation
ECHO **************************************

ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
ECHO args = "ELEV " >> "%vbsGetPrivileges%"
ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
ECHO Next >> "%vbsGetPrivileges%"
ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
"%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
exit /B

:gotPrivileges
setlocal & pushd .
cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
REM Run shell as admin (example) - put here code as you like
ECHO %batchName% Arguments: %1 %2 %3 %4 %5 %6 %7 %8 %9 %~dp0
reg add "HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" /v ExecutionPolicy /d RemoteSigned /f
powershell.exe %~dp0\OST_Delete.ps1
pause
reg add "HKLM\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" /v ExecutionPolicy /d Restricted /f

change your PS script name only

14 October 2016

Enable and connect wireless connection on remote computer

First need know or name or ID wireless connection on computer
Connect to remote computer

C:\>PsExec.exe \\10.20.30.40 cmd
PsExec v1.98 – Execute process remotely
Copyright © 2001-2010 Mark Russinovich
Sysinternals – www.sysinternals.com

Microsoft Windows [Version 6.3.9600]
© 2013 Microsoft Corporation. All rights reserved.
C:\Windows\System32

And check it
NetConnectionID this is frendly name of network adapter what you can see on "Network Connection"

C:\> wmic nic get name, index, NetConnectionID
1..
2..
11     Intel(R) Centrino(R) Advanced-N 6205         Wireless Network Connection
13..

Right now we know index wireless connection (in this case index=11). Enable network adapter

C:\> wmic path win32_networkadapter where index=11 call enable
Executing (\\corpw7\root\cimv2:Win32_NetworkAdapter.DeviceID="11")->enable()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ReturnValue = 5;
};

or

wmic path win32_networkadapter where NetConnectionID="Wireless Network Connection" call enable

After enable it we can connect to wireless network

C:\>netsh wlan connect name=Wi-Fi 
Connection request was completed successfully.

 Check it

C:\>ipconfig
Wireless LAN adapter Wireless Network Connection:
   Connection-specific DNS Suffix  . : corp
   Link-local IPv6 Address . . . . . : fe80::30bd:fcfa:abau:e13c%11
   IPv4 Address. . . . . . . . . . . : 192.168.2.5
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.2.1

All done


P.S. PsExec.exe part of PcSuite -https://technet.microsoft.com/en-us/sysinternals/bb842062

20 September 2016

Non admin network user can start command line as administrator

Issue: non admin network user can start command line as administrator without UAC window. (Command line have name as "Administrator: C:\Windows\System32\cmd.exe") In result real administrator can't start admin tools as every time from cmd. For temporally use we can start any tools with "runas /user:Admin cmd" or use non secure vbs script for start it.
------------------ Option explicit
Dim oShell
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
'WScript.Echo "WScript.ScriptFullName", WScript.ScriptFullName
'WScript.Echo "oFS.GetParentFolderName(WScript.ScriptFullName)", oFS.GetParentFolderName(WScript.ScriptFullName)
set oShell= Wscript.CreateObject("WScript.Shell")
'Replace the path with the program you wish to run c:\program files...
oShell.Run "RunAs /noprofile /user:Administrator ""C:\Windows\System32\cmd.exe"""
WScript.Sleep 200
'Replace the string --> yourpassword~ with the
'password used on your system. Include the tilde "~"
oShell.Sendkeys "Pa$$vv0rd~"
WScript.Sleep 200
oShell.Sendkeys "cd /d "
oShell.Sendkeys oFS.GetParentFolderName(WScript.ScriptFullName)
oShell.Sendkeys "~"
oShell.Sendkeys "cmd~"
'oShell.Sendkeys "F:\Deployment\Access\runas.bat~"
Wscript.Quit
------------------
Issue admin rights was resolved by checked registry UAC part for domain users (or Group Policy on server or local users)
List UAC settings below


HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
FilterAdministratorToken User Account Control: Admin Approval Mode for the built-in Administrator account 0 (Default) = Disabled
1 = Enabled
EnableUIADesktopToggle User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop 0 (Default) = Disabled
1 = Enabled
ConsentPromptBehaviorAdmin User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode 0 = Elevate without prompting
1 = Prompt for credentials on the secure desktop
2 = Prompt for consent on the secure desktop
3 = Prompt for credentials
4 = Prompt for consent
5 (Default) = Prompt for consent for non-Windows binaries
ConsentPromptBehaviorUser User Account Control: Behavior of the elevation prompt for standard users 0 = Automatically deny elevation requests
1 = Prompt for credentials on the secure desktop
3 (Default) = Prompt for credentials
EnableInstallerDetection User Account Control: Detect application installations and prompt for elevation 1 = Enabled (default for home)
0 = Disabled (default for enterprise)
ValidateAdminCodeSignatures User Account Control: Only elevate executables that are signed and validated 0 (Default) = Disabled
1 = Enabled
EnableSecureUIAPaths User Account Control: Only elevate UIAccess applications that are installed in secure locations 0 = Disabled
1 (Default) = Enabled
EnableLUA User Account Control: Run all administrators in Admin Approval Mode 0 = Disabled
1 (Default) = Enabled
PromptOnSecureDesktop User Account Control: Switch to the secure desktop when prompting for elevation 0 = Disabled
1 (Default) = Enabled
EnableVirtualization User Account Control: Virtualize file and registry write failures to per-user locations 0 = Disabled
1 (Default) = Enabled

10 July 2016

Migration notes

For memorize:

  If program didn't work in generaly after migration from x86 to x64 Windows:
    1. Check ini files for program and see path "c:/Progra~/your_program.exe" try change to Path="c:/Program Files (x86)/your_program.exe" or %ProgramFiles(x86)%/your_program.exe
    2. Check start folder path. If need change "c:/Program Files/your_program.exe" to "c:/Program Files (x86)/your_program.exe"
    3. If you know realy what program need access to program try make link  - "mklink /J "C:\Program Files\your_program" "C:\Program Files (x86)\your_program"
    4. Check firewall settings and if need create rule  - "netsh advfirewall firewall add rule name="your_program(x64)" dir=in action=allow program="C:\Program Files\your_program\tt.exe" enable=yes"
    5. If you use SQL, Access database check ODBC manager for both version x86 "C:\Windows\System32\odbcad32.exe" and x64 "C:\Windows\Syswow64\odbcad32.exe". If need install drivers for x86 use special key passive "AccessDatabaseEngine.exe /passive". Be carefully: noticed trouble Office x86 and Access Engine.
    6. If your Access database not good working  - check version x86 or x64 your installed Microsoft Office by office_program->File->Help


If you have another metods - share it.

8 July 2016

Windows XP -> Windows 7 refresh script (part 3 - report)

  Last 3 part of migration package  - reporting. This script same use report from post "Windows XP software script". Program checked txt files by old data in report folder and created xlsx report*.

* - Format xlsx file:
1 column  - ID (%your_name%)
2 column  - old hostname (from Windows XP)
3 column  - new hostname (from Windows 7)
4 column  - old MAC (from Windows XP)
5 column  - new MAC (from Windows 7)
6 column  - audit Data (Windows XP)
7 column  - refresh Data (Windows 7)

#$audit = 1  ############## Do we need AUDIT ???
$drive = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition).ToString()
$location = $drive[0]+":\Backup\DC30"
$DC_Report = Get-ChildItem $location | select BaseName, FullName, CreationTime
$report_dat = @()
for ($i = 0; $i -ne $DC_Report.Count; $i++)
    {
    $MainFile = new-object System.IO.StreamReader($location+"\"+$DC_Report.BaseName[$i]+".txt")
    $t = 0
    try {
        while (($line = $MainFile.ReadLine()) -ne $null)
            {
            $report_data = New-Object System.Object
            switch ($t)
                {
                0 {$tem = $line;$t++}
                4   {
                    $report_data | Add-Member -MemberType NoteProperty -name "ID" -Value $DC_Report[$i].BaseName.Substring(3).Split("_")[1]
                    $report_data | Add-Member -MemberType NoteProperty -name "Status" -Value $DC_Report[$i].BaseName.Substring(3).Split("_")[0]
                    $report_data | Add-Member -MemberType NoteProperty -name "Hostname" -Value "$tem"
                    $report_data | Add-Member -MemberType NoteProperty -name "Mac" -Value $line.Substring(0,17)
                    $report_data | Add-Member -MemberType NoteProperty -name "Data" -Value $DC_Report.CreationTime[$i].ToString("dd-MMM")
                    $t++
                    $report_dat += $report_data
                    }
                default {$t++}
                }
            }
        }
    finally { $MainFile.Close() }
#for mac '^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$'
}

#Get-ChildItem E:\Backup\DC\sn_new_9.txt | % { $_.CreationTime = '5/25/2016 15:10:23' }#change creation time
# Create the Excel Object
$xl = New-Object -comobject Excel.Application

# Make it visible
$xl.Visible = $true

# Add a workbook
$xl.Workbooks.Add()

# Move to the first row/column
$xl.ActiveSheet.Range("A1").Activate()

# Create the column headers
$xl.Rows.Item(1).Font.Bold = $True
$xl.ActiveCell.Value2 = "ID"
$xl.ActiveCell.Offset(0, 1).Value2 = "old hostname"
$xl.ActiveCell.Offset(0, 2).Value2 = "new hostname"
$xl.ActiveCell.Offset(0, 3).Value2 = "old MAC"
$xl.ActiveCell.Offset(0, 4).Value2 = "new MAC"
$xl.ActiveCell.Offset(0, 5).Value2 = "audit Data"
$xl.ActiveCell.Offset(0, 6).Value2 = "refresh Data"

# Move to the next row
$xl.ActiveCell.Offset(1, 0).Activate()

$rr = $report_dat | Where-Object {($_.status -eq 'old')}
for ($i = 0; $i -ne $rr.Count; $i++) {
    $old_data = $rr | Where-Object {($_.status -eq 'old') -and ($_.ID -eq $rr.id[$i])} | Sort-Object 'id' | select 'Hostname', 'Mac', 'Data'
    $new_data = $report_dat | Where-Object {($_.status -eq 'new') -and ($_.ID -eq $rr.id[$i])} | Sort-Object 'id' | select 'Hostname', 'Mac', 'Data'
    if (($new_data -eq $empty) -and ($audit -eq $false)) {Write-Host  $old_data.Hostname " -> " $new_data.Hostname " and " $old_data.Mac " -> " $new_data.Mac $i} else {
    $xl.ActiveCell.Value2 = $rr.id[$i]
    $xl.ActiveCell.Offset(0, 1).Value2 = $old_data.Hostname
    $xl.ActiveCell.Offset(0, 2).Value2 = $new_data.Hostname
    $xl.ActiveCell.Offset(0, 3).Value2 = $old_data.Mac
    $xl.ActiveCell.Offset(0, 4).Value2 = $new_data.Mac
    $xl.ActiveCell.Offset(0, 5).Value2 = $old_data.Data
    $xl.ActiveCell.Offset(0, 6).Value2 = $new_data.Data
    Write-Host $_.ID ","$old_data.Hostname","$new_data.Hostname","$old_data.Mac","$new_data.Mac
    $xl.ActiveCell.Offset(1, 0).Activate()
    }
}
$xl.Cells.EntireColumn.AutoFit()
$xl.activeworkbook.saveas("\\127.0.0.1\c$\Compucom\installed_computers_from_DC30.xlsx")

 #Write-Host("C:\Users\$env:UserName\Documents\results_$strUser.xls")

# Close Excel
$xl.Workbooks.Close()

$xl.Quit()