Monday, November 14, 2022

How to Deploy CCM restart Notification

 

Create a dummy package with below settings.

Create a collection query with machines pending restart and deploy the package to this collection.



Monday, September 7, 2020

Power Shell Script - Get the OS build of Remote machines

 #add your hostname in a text file -d:\path.txt and Output will come in D:excel.csv

#Requires -Version 3.0
Function Get-LHSWindowsVersion
{
<#
.SYNOPSIS
    Get Windows version information from local or Remote Computer

.DESCRIPTION
Get Windows version information from local or Remote Computer.
    Get Windows Version information using CIM and Registry(over CIM).

.PARAMETER ComputerName
    The computer name(s) to retrieve the info from.
    Default to local Computer.

    When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that
    is used only to run the specified command and is then closed. If you need a persistent connection,
    use the Session parameter.

.PARAMETER CimSession
    Specifies the CIM sessions to use for this cmdlet.
    Enter a variable that contains the CIM session or a command that creates or
    gets the CIM session, such as the New-CimSession or Get-CimSession cmdlets.
    For more information, see about_CimSessions.

.PARAMETER Credential
    Alternate Credential to connect to the remote Computer.
    The default is the current user.

.EXAMPLE
    To List DefaultDisplayProperties from local Computer

    Get-LHSWindowsVersion

    ComputerName OSName                          ReleaseId MUILanguages
    ------------ ------                          --------- ------------
    PC1          Microsoft Windows 10 Enterprise 1709      de-DE

.EXAMPLE
    To list all Properties use Select * or Format-List *

    Get-LHSWindowsVersion -ComputerName PC2 | select *

    ComputerName                : PC2
    OSName                      : Microsoft Windows 10 Enterprise
    ReleaseId                   : 1709
    Version                     : 10.0.16299
    ServicePackMajorVersion     : 0
    ServicePackMinorVersion     : 0
    OSArchitecture              : 64-Bit
    OSLanguage                  : 1031
    MUILanguages                : de-DE
    WindowsDirectory            : C:\Windows
    Universal_Unique_Identifier : C8783A42-8BC7-5936-6E7D-AC4CF7E8E812
    BuildNumber                 : 16299
    SerialNumber                : 00329-00000-00003-AA779
    InstallDate                 : 13.11.2018 08:32:54
    LastBootUpTime              : 07.01.2019 10:56:09

.EXAMPLE
    Exaple to use pipeline input for ComputerName

    'Server1','Server2' | Get-LHSWindowsVersion

    ComputerName OSName                                 ReleaseId MUILanguages
    ------------ ------                                 --------- ------------
    Server1      Microsoft Windows Server 2016 Standard 1607      en-US
    Server2      Microsoft Windows Server 2016 Standard 1607      en-US

.EXAMPLE
    To list OS Information using existent CIMSessions as pipeline input

    Get-CimSession | Get-LHSWindowsVersion

.EXAMPLE
    To list OS Information using an existent CIMSession and using Parameter -CimSession

    $CimSession = New-CimSession -ComputerName Server1 -SessionOption (New-CimSessionOption -Protocol Dcom)
    Get-LHSWindowsVersion -CimSession $CimSession

.INPUTS
    you can pipe input ComputerNames or CimSessions to this Function

.OUTPUTS
    PSCustomObject with the following TypeNames

    TypeNames:
    ------------------
    LHS.Windows.Version
    System.Management.Automation.PSCustomObject
    System.Object

.NOTES
    Windows Universal Unique Identifier (UUID)
    Every Windows installation has a unique UUID that you can use to distinguish machines.
    While computer names can change, the UUID won’t.

    AUTHOR  : Pasquale Lantella
    LASTEDIT: 08.01.2019
    KEYWORDS: Windows,Version,UUID
    Version : 1.0
    History :

.LINK
    about_CimSessions

.LINK

#Requires -Version 3.0
#>

[cmdletbinding(DefaultParameterSetName = 'Default')]

[OutputType([System.Management.Automation.PSCustomObject])]
#[OutputType('LHS.Windows.Version')]

Param(

    [Parameter(ParameterSetName='Default',Position=0,
        ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True,
        HelpMessage='An array of computer names. The default is the local computer.')]
    [alias("CN")]
    [string[]]$ComputerName = $Env:COMPUTERNAME,

    [Parameter(
        ParameterSetName='CimSession',Position=0,
        ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [ValidateNotNullorEmpty()]
    [Microsoft.Management.Infrastructure.CimSession[]]$CimSession,

    [parameter(ParameterSetName='Default',Position=1)]
    [Alias('RunAs')]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential = [System.Management.Automation.PSCredential]::Empty

)

BEGIN {

    Set-StrictMode -Version 3.0
    ${CmdletName} = $Pscmdlet.MyInvocation.MyCommand.Name

    # custom PSTypeName for Output Objects
    $TypeName = 'LHS.Windows.Version'
    $TypeData = @{
        TypeName = $TypeName
        DefaultDisplayPropertySet = @('ComputerName','OSName','ReleaseId','MUILanguages')
        ErrorAction = 'SilentlyContinue'
    }
    Update-TypeData @TypeData

} # end BEGIN

PROCESS {

    switch ($PsCmdlet.ParameterSetName)
    {
        'Default'
        {
            #process computer names individually
            ForEach ($Computer in $ComputerName)
            {
                    IF (Test-Connection -ComputerName $Computer -count 2 -quiet)
                {
                    $CimSessionTemp = $null
                    Try
                    {
                        Test-WSMan -ComputerName $Computer -ErrorAction Stop | Out-Null

                        $SessionParams = @{
                              ComputerName  = $Computer
                              ErrorAction = 'Stop'
                              SessionOption = (New-CimSessionOption -Protocol DCOM -ErrorAction Stop)
                        }
                        if ($PSBoundParameters['Credential'])
                        {
                            Write-Verbose "Adding alternate credential for CIMSession"
                            $SessionParams.Credential = $Credential
                        }
                        Write-Verbose "Creating CimSession.."
                        $CimSessionTemp = (New-CimSession @SessionParams)
                    }
                    Catch
                    {
                        Write-Verbose "[PROCESS] \\$Computer Test-WSMan failed! `n if the remote computer is running PowerShell 2.0 this will fail. You have to manually create a CIMSession with a CIMSessionOption to use the DCOM protocol."
                        Write-Verbose "[PROCESS] $($_.exception.message)"
                        Write-Verbose "Trying using DCOM Protocol"
                        Try
                        {
                            $SessionParams = @{
                                  ComputerName  = $Computer
                                  ErrorAction = 'Stop'
                                  SessionOption = (New-CimSessionOption -Protocol DCOM -ErrorAction Stop)
                            }
                            if ($PSBoundParameters['Credential'])
                            {
                                Write-Verbose "Adding alternate credential for CIMSession"
                                $SessionParams.Credential = $Credential
                            }
                            Write-Verbose "Creating CimSession.."
                            $CimSessionTemp = (New-CimSession @SessionParams)

                        }
                        Catch
                        {
                            Write-Warning "[PROCESS] $_"
                        }

                    } # catch

                    Try
                    {
                        [uint32]$HKLM = 2147483650
                        $RegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                        $RegValue = 'ReleaseId'

                        $Params = @{
                            Namespace = 'root\default'
                            ClassName = 'StdRegProv'
                            MethodName = 'GetStringValue'
                            CimSession = $CimSessionTemp
                            Arguments = @{hDefKey=$HKLM; sSubKeyName =$RegKey; sValueName = $RegValue}
                        }
                        $ReleaseId = $null
                        $ReleaseId = Invoke-CimMethod @Params -ErrorAction Stop |
                            Select-Object -ExpandProperty sValue

                        $OperatingSystem = $null
                        $OperatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $CimSessionTemp -Property * -ErrorAction Stop

                        #Windows Universal Unique Identifier (UUID)
                        $UUID = $null
                        $UUID = Get-CimInstance -ClassName Win32_ComputerSystemProduct -CimSession $CimSessionTemp -ErrorAction Stop | Select-Object -ExpandProperty UUID
                    }
                    Catch
                    {
                        Write-Error "[PROCESS] $_"
                    }

                    foreach ($OS in $OperatingSystem)
                    {
                        $OutputObj = [pscustomobject][Ordered] @{
                            PSTypeName = $TypeName
                            ComputerName = $Computer
                            OSName = $OS.Caption
                            ReleaseId = $ReleaseId
                            Version = $OS.Version
                            ServicePackMajorVersion = $OS.ServicePackMajorVersion
                            ServicePackMinorVersion = $OS.ServicePackMinorVersion
                            OSArchitecture = $OS.OSArchitecture
                            OSLanguage = $Os.OSLanguage
                            MUILanguages = $OS.MUILanguages -join ','
                            WindowsDirectory = $OS.WindowsDirectory
                            Universal_Unique_Identifier = $UUID
                            BuildNumber = $OS.BuildNumber
                            SerialNumber = $OS.SerialNumber
                            InstallDate = $OS.InstallDate
                            LastBootUpTime = $OS.LastBootUpTime
                        }
                        $OutputObj
                    }

                    If($CimSessionTemp) { Remove-CimSession -CimSession $CimSessionTemp -ErrorAction SilentlyContinue }
                }
                Else
                {
                    Write-Warning "\\$Computer computer DO NOT reply to ping."
                } # end IF (Test-Connection $Computer -quiet)
            } # end ForEach ($Computer in $computerName)

        } # end 'Default'

        'CimSession'
        {
            Write-Verbose "[PROCESS] connecting via existing CIMSessions"

            foreach ($Session in $CimSession)
            {
                Try
                {
                    [uint32]$HKLM = 2147483650
                    $RegKey = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
                    $RegValue = 'ReleaseId'

                    $Params = @{
                        Namespace = 'root\default'
                        ClassName = 'StdRegProv'
                        MethodName = 'GetStringValue'
                        CimSession = $Session
                        Arguments = @{hDefKey=$HKLM; sSubKeyName =$RegKey; sValueName = $RegValue}
                    }
                    $ReleaseId = $null
                    $ReleaseId = Invoke-CimMethod @Params -ErrorAction Stop |
                        Select-Object -ExpandProperty sValue

                    $OperatingSystem = $null
                    $OperatingSystem = Get-CimInstance -ClassName Win32_OperatingSystem -CimSession $Session -Property * -ErrorAction Stop

                    #Windows Universal Unique Identifier (UUID)
                    $UUID = $null
                    $UUID = Get-CimInstance -ClassName Win32_ComputerSystemProduct -CimSession $Session -ErrorAction Stop | Select-Object -ExpandProperty UUID
                }
                Catch
                {
                    Write-Error $_
                }

                foreach ($OS in $OperatingSystem)
                {
                    $OutputObj = [pscustomobject][Ordered] @{
                        PSTypeName = $TypeName
                        ComputerName = $OS.PSComputerName
                        OSName = $OS.Caption
                        ReleaseId = $ReleaseId
                        Version = $OS.Version
                        ServicePackMajorVersion = $OS.ServicePackMajorVersion
                        ServicePackMinorVersion = $OS.ServicePackMinorVersion
                        OSArchitecture = $OS.OSArchitecture
                        OSLanguage = $Os.OSLanguage
                        MUILanguages = $OS.MUILanguages -join ','
                        WindowsDirectory = $OS.WindowsDirectory
                        Universal_Unique_Identifier = $UUID
                        BuildNumber = $OS.BuildNumber
                        SerialNumber = $OS.SerialNumber
                        InstallDate = $OS.InstallDate
                        LastBootUpTime = $OS.LastBootUpTime
                    }
                    $OutputObj
                }

            } # foreach ($Session in $CimSession)
        } # 'CimSession'
    } # end switch ($PsCmdlet.ParameterSetName)


} # end PROCESS

END { Write-Verbose "Function ${CmdletName} finished." }

} # end Get-LHSWindowsVersion

Get-Content "d:\path.txt" | Get-LHSWindowsVersion | Export-Csv -path d:\excel.csv

cm

Tuesday, October 22, 2019

Powershell Script-ResolveHostNamesToIPAddresses

function Get-HostToIP($hostname) {   
    $result = [system.Net.Dns]::GetHostByName($hostname)   
    $result.AddressList | ForEach-Object {$_.IPAddressToString }
}

Get-Content "D:\path.txt" | ForEach-Object {(Get-HostToIP($_)) + ($_).HostName >> d:\data\Addresses.txt}

Wednesday, May 31, 2017

Run a .reg file in the same folder as the .bat file


The erros message: "Cannot import C:\users....abc.reg". Error opening the file. There may be a disk or a file system error.


If you want to run a .reg file in the same folder as the .bat file, just write it like this:
@echo on
REGEDIT /S "%~dp0ABC.reg"

This will run the file ABC.reg in the same folder.


If you wan't to run something in a subfolder, you have to do it like this:
@echo on
REGEDIT /S "%~dp0SUBFOLDER\ABC.reg"
The brackets ("") are only needed, if there are whitespaces in the pathname.

The command line to add a local windows user with the Special Characters password

The command line to add a local windows user called “newuser” with the password “p&ssw^rd”
You try
1
net user newuser p&ssw^rd /ADD
Uh-oh – it fails!
1
2
3
4
5
6
7
C:\> net user newuser p&ssw^rd /ADD
The user name could not be found.
 
More help is available by typing NET HELPMSG 2221.
 
'sswrd' is not recognized as an internal or external command,
operable program or batch file.
If the password contains certain special characters – like an ampersand “&” or a caret “^”, the password will be garbled, broken, butchered.
One solution is to have it prompt for the password
1
net user newuser * /ADD
but if you are scripting, this isn’t really helpful.
No, you cannot use quotes.
The solution: All Ampersands must be escaped with a caret “^”, and all carets in the password must be similarly escaped.
UPDATE: turns out in more recent versions of windows, exclamation marks “!” must also be escape with two carets.
See here for a good list of how to escape things.
http://www.robvanderwoude.com/escapechars.php
So, to use the password p&ssw^rd in a command line, you would need to replace it with p^&ssw^^rd
1
net user newuser p^&ssw^^rd /ADD
This will do what you expect
Note that if you do not escape the carets, the command may succeed, but the password will be wrong.

Sunday, March 22, 2015

Unsolicited Windows 7 Remote Assistance






Description

Full, meaning no need for any manual user intervention regarding prompts. Works with Windows 7 to Windows 7 and Windows 7 to Windows XP. Not yet tested with Windows Vista. Note: This requires more files than just the source script.
-Alternate Download Link: https://hotfile.com/dl/150097193/0582e27/RA.zip.html
Let me know what you all think. Doesn't work too bad for one of my first scripts that I actually use quite often.
NEW! -- I recommend using the gui version created here by JAG1117: 

##Thx to Brentb######




@echo off
echo "Enter Computername or IP:"
set /p ComputerName=

echo %ComputerName%

copy "C:\RA\RAWIN7.exe" "\\%ComputerName%\C$\RAWIN7.exe" /y
C:\pstools\psexec /accepteula -i -h -d \\%ComputerName% C:\RAWIN7.exe

start /d "C:\RA" ra.lnk

echo "Press any key after you click Request Control"
pause

C:\pstools\psexec /accepteula -i -h -d \\%ComputerName% C:\RAWIN7.exe

PowerShell: Convert CSV to Excel

##########FyzelSalih#############


    #Add workbook
    $workbook = $excel.workbooks.Add()

    #Remove other worksheets
    $workbook.worksheets.Item(2).delete()
    #After the first worksheet is removed,the next one takes its place
    $workbook.worksheets.Item(2).delete()  

    #Define initial worksheet number
    $i = 1
    }

Process {
    ForEach ($input in $inputfile) {
        #If more than one file, create another worksheet for each file
        If ($i -gt 1) {
            $workbook.worksheets.Add() | Out-Null
            }
        #Use the first worksheet in the workbook (also the newest created worksheet is always 1)
        $worksheet = $workbook.worksheets.Item(1)
        #Add name of CSV as worksheet name
        $worksheet.name = "$((GCI $input).basename)"

        #Open the CSV file in Excel, must be converted into complete path if no already done
        If ($regex.ismatch($input)) {
            $tempcsv = $excel.Workbooks.Open($input)
            }
        ElseIf ($regex.ismatch("$($input.fullname)")) {
            $tempcsv = $excel.Workbooks.Open("$($input.fullname)")
            }  
        Else {  
            $tempcsv = $excel.Workbooks.Open("$($pwd)\$input")    
            }
        $tempsheet = $tempcsv.Worksheets.Item(1)
        #Copy contents of the CSV file
        $tempSheet.UsedRange.Copy() | Out-Null
        #Paste contents of CSV into existing workbook
        $worksheet.Paste()

        #Close temp workbook
        $tempcsv.close()

        #Select all used cells
        $range = $worksheet.UsedRange

        #Autofit the columns
        $range.EntireColumn.Autofit() | out-null
        $i++
        }
    }      

End {
    #Save spreadsheet
    $workbook.saveas("$pwd\$output")

    Write-Host -Fore Green "File saved to $pwd\$output"

    #Close Excel
    $excel.quit()

    #Release processes for Excel
    $a = Release-Ref($range)
    }
}


ConvertCSV-ToExcel -inputfile @(".\cv\allservers.csv") -output 'allservers.xlsx'