Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

How do you execute a PS script to run on multiple remote computers simultaneously?

$
0
0

I have a PS script that accomplishes the following process: sets the start-up service attribute to "disabled", stops the service, kills process if its running, then copies updated files, sets start-up service attribute to "automatic", starts service if found not running. 

This  is the process that needs to happen to update an in-house critical application. It used to be manually done to about 12 Windows 2012 R2 servers and would take about 45 - 50 mins. Takes even longer when "ini" or "config" files are modified in addition to the above process. I'm not an expert in PS but I managed to put together a PS script that execute the manual process. Problem is, I'm calling a "Computers.txt" file that adds all server hostnames to the "$Srvs" variable and runs the entire script one server at a time. 

How can I get the script to run all 12 servers simultaneously??? Running it simultaneously would mean cutting the script process down to 3 -5 mins tops! Thanks!

Script:

$Srvs = gc D:\Computers.txt
$source = "D:\5.3.2.0\*.*"
$dest = "\\$_\c$\Program Files\InHouse\App"
$exclude = @('*.ini','*.config')
$Svc = "AppService"

# Changing service start-up type to "disabled" 
set-service -computername $Srvs -name $Svc -startuptype disabled

# Stopping service
get-service -computername $Srvs -name $Svc | stop-service | out-null

# Check if process is running. If it is, kill process.
$check1 = get-process -computername $Srvs -name AppProcess -ErrorAction SilentlyContinue
if ($check1 -ne $null){
write-host "Start wait"
Start-Sleep -s 10
write-host "End wait"
invoke-command -computername $Srvs {stop-process -name AppProcess -force}
write-host "AppService has been killed!!!"
}
else {
         "AppService is not running on $Srvs"
}
 
pause
# Copy new service files.
write-host "Copying new App Service files..." 

foreach ($computer in $Srvs) {
1
    if (test-Connection -Cn $computer) {
2
        Copy-Item $source -Destination \\$computer\$dest -Recurse -Force -Exclude $exclude
3
    } else {
4
        "$computer is not online"
5
    }
6
}
write-host "File copy complete!!!"
pause
# Change service start-up type to "automatic"
set-service -name $Svc -computername $Srvs -startuptype automatic

# If service does not start, start it.
$check2 = get-service -computername $Srvs -name $Svc -ErrorAction SilentlyContinue
if ($check2 -ne $null){
$check2 | start-service 
}
write-host "AppService is running!!!"
write-host "AppService update is complete!"
pause

exit


export-CSV question

$
0
0

I have the following script 

(get-content "C:\users\jmateo\Desktop\LiquidNetGlobalUS\test.txt")-replace("bin.*")-replace("\\itg")-replace("\\triton")-replace("\\")-replace(":")

pretty basic 

the result looks like this 

Connections string found on tri-vtsf05-scSolutions_LiquidnetTSF_beutel1t

how could I use that string to create three different string and apply a header to it

Status  servertsf

Connections string found on       servername        Solutions_LiquidnetTSF_beutel1t

I am more interested in just getting the string split into three different parts 

How to get UPN from Get-MailboxPermission

$
0
0

I'm trying to get my Get-MailboxPermission output to show the Alias from the mailbox i'm asking the permissions for, AccessRights and the users who have permissions. The problem is: the users who have permissions are show as "DOMAIN\User". Is there some kind of way i can change that into UserPrincipalName?

I'm using the following script:

$mailbox = Get-Mailbox
    FOREACH ($line in $mailbox)
        {
        $perm = Get-MailboxPermission -Identity $line.DisplayName | Where-Object {$_.IsInherited -like $False -AND $_.User -NotLike "NT*"}
        $perm | Add-Member NoteProperty Alias $line.Alias
        $perm | Select Alias,User,AccessRights,UserPrincipalName
        }
I tried adding "$perm | Add-Member NoteProperty UserPrincipalName $line.UserPrincipalName" but that would show me the UserPrincipalName of the mailbox i'm asking the permissions for, not the users who have the permissions. Would be glad to know if this is possible.

Set-execution policy

$
0
0

Hello there ,

Just make home work and trying to understand something .


In Powershell there are the 4 modes in order to run any Powershell Scripts ,

I thins that i know the modes learned them from this website ;

http://www.hanselman.com/blog/SigningPowerShellScripts.aspx

just confused and don't understanding what is the difference between 

All-signed to RemoteSigned  Maybe some body can explain me 

and another questions - Very difficult 

My question is , once it say that condition " Restricted " it committed from us download script with trusted publisher , when i'm downloading some scripts from Microsoft Technet how can i know who is the Trusted Publisher ?

how can we know who is the Trusted Publisher in Powershell ?

How Restricted Mode knows that some script that i donwloaded from Technet is Trusted Publisher or not ?

using powershell and task scheduler to send email

$
0
0

I'm a newbie trying to use powershell and the task scheduler in windows 7 pro to automate distribution of a file via email on a daily basis.  I've done a lot of searching on the web to learn this process.  I've succeeded in writing a basic script that will send an email.  when run from a powershell console it works.  however, when i schedule the task using the tutorials I've found on the web, the script runs but the email is not sent!

Here's the script:

$smtp = New-Object system.Net.Mail.SMTPClient -ArgumentList xx.xx.xx.xx
$smtp.send('myemail@domain.com','destinationaddress@gmail.com','test message','this is a test message sent from powershell')

In the task scheduler I set up a task to run daily.  i choose "start a program". In the settings, under the Program/script section I've entered

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

in the arguments section i put

-Noninteractive -Noprofile -Command " &{C:\scripts\sendemail.ps1 }"

in the start in section i put

c:\scripts

under the General tab of the task, I selected it to run with the highest privileges and selected under the Configure for: section Windows 7

when i run the task manually.  a cmd window opens briefly and the disappears.  No error messages flash in the window before it closes.  So from everything I can tell it runs just fine.   However when I check the destination mail account, no email message is present. 

I know the script works when i run it in the powershell console, but it won't work any other way.  Can anyone tell me the step I missed. 

Open Powershell script and execute it via external script

$
0
0

Hello all,

I want to open a script a scipt with powershell ISE and then run it.

Ive created the following code but it doesn't work.

add-type -AssemblyName microsoft.VisualBasic
powershell_ise.exe -File "script2load"
Start-Sleep –Seconds 10
$p=get-process | where {$_.name -eq "powershell_ise"}
[Microsoft.VisualBasic.Interaction]::AppActivate($p.ID)
[System.Windows.Forms.SendKeys]::SendWait("{F5}{ENTER}")


But this doesn't work. Could really use some help with this.

Regards,



Powershell Remoting Help

$
0
0

Hello, 

I am having some trouble running a script.  I keep receiving the error:
"The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"

Alot of other forums said that this could be a firewall issue, but I don't think that is the case because I can run invoke-commands such as the following below with no errors:

Invoke-Command -ComputerName WS-IT-50 -ScriptBlock {Get-Process}

However, when I try to run the following script, which involves getting input from Active Directory, I get that error mentioned above.

Script:

import-module activedirectory

function Get-ComputerInfo {

    BEGIN {}
        PROCESS {

        $computername = $_

            $os = Get-WmiObject Win32_OperatingSystem -computer $computername


            $bios   = Get-WmiObject Win32_BIOS -computerName $computername;
            $system = Get-WmiObject Win32_ComputerSystem -computerName $computername;



            $obj = New-Object -TypeName PSObject
            $obj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $computername


            $obj | Add-Member -MemberType NoteProperty -Name osVersion -Value ($os.Version);
            $obj | Add-Member -MemberType NoteProperty -Name OsSerialNumber -Value ($os.SerialNumber);

            $obj | Add-Member -MemberType NoteProperty -Name BiosVersionNumber -Value ($bios.SMBIOSBIOSVersion);
            $obj | Add-Member -MemberType NoteProperty -Name BiosManufacturer -Value ($bios.Manufacturer);

            $obj | Add-Member -MemberType NoteProperty -Name SystemModel -Value ($system.Model);
            $obj | Add-Member -MemberType NoteProperty -Name Owner -Value ($system.PrimaryOwnerName);
            $obj | Add-Member -MemberType NoteProperty -Name SystemMemory -Value ($system.TotalPhysicalMemory);
            $obj | Add-Member -MemberType NoteProperty -Name SystemThermal -Value ($system.ThermalState);


            Write-Output $obj

        }
    END {}
}

Get-ADComputer -filter * | Select -expand Name | Get-ComputerInfo


Just so you know, I am not running Windows Firewall in my environment, I am running Symantec Endpoint Protection. All I have done is run a logon script for all computers in the domain with the following code which allowed me to run invoke-commands but not that script: 

Enable-PSRemoting -Force

Thank you all for your time and I look forward to your replies!

format output into a table

$
0
0

get-content "C:\users\jmateo\Desktop\LiquidNetGlobalUS\test1.txt"|
ForEach-Object{($_).split("\\")[0], ($_).split("\\")[2] ,($_).split("\\")[5]} 

I have the following code, which splits my string into three different parts the output looks like this 

Connections found on 
tri-vtsf05-sc
Solutions_LiquidnetTSF_waratah1t

how can I format this so that it puts each string here into it's own column ? 

status                    server thing 

Connected                         tri-vtsf05-sc                                      Solutions_LiquidnetTSF_waratah1t


Auto login with PowerShell problem

$
0
0

Hi,

I have a problem auto logging in into my company website.  I am trying to make the ID, Password, and login to auto click. It does not work. But I have done some research it might be because of an extra window that is opened within the login page, so I need to write up another code for it. Other than that I looked into HTML and wrote the correct ID.  Please help me. The message board won't allow me to add a url anywhere on this message. I need the administrator to allow me to post the url.

$var="410043"
$username = "username"
$password = "password"

$ie = New-Object -com InternetExplorer.Application
$ie.visible=$true
$ie.navigate("American Tower?url not allowed until I have approval ")
while($ie.ReadyState -ne 4) {start-sleep -m 100}
$ie.document.getElementById("input#tb_login").value= "$username"
$ie.document.getElementById("input#tb_password").value = "$password"
$ie.document.getElementById("login-signin").click()
while($ie.ReadyState -ne 4) {start-sleep -m 100}

Exclude a Update ID from my update script

$
0
0

Hello so i have learned that there are certain windows updates i need to not apply since i have .net 4.6 on my windows 2012 server. I have the below script already in place to run biweekly. 

#Define update criteria.

$Criteria = "IsInstalled=0 and Type='Software'"


#Search for relevant updates.

$Searcher = New-Object -ComObject Microsoft.Update.Searcher

$SearchResult = $Searcher.Search($Criteria).Updates


#Download updates.

$Session = New-Object -ComObject Microsoft.Update.Session

$Downloader = $Session.CreateUpdateDownloader()

$Downloader.Updates = $SearchResult

$Downloader.Download()


#Install updates.

$Installer = New-Object -ComObject Microsoft.Update.Installer

$Installer.Updates = $SearchResult

$Result = $Installer.Install()


#Reboot if required by updates.

If ($Result.rebootRequired) { shutdown.exe /t 0 /r }

My Question is if i added to the $criteria (UpdateID != 'xxxx') would it exclude that specific updateID, how would i find the updateID for the specific KB, i tried 

$upids=  @{}$Searcher= New-Object -ComObject Microsoft.Update.Searcher$results=$searcher.search("Type='software' AND IsInstalled = 0")$Results.Updates |
     ForEach-Object { $upids.Add($_.Title, $_.Identity.UpdateID) }

$upids

to create a hash table of available updates and there UID but it did not work. PLease help

Search registry for UninstallString, sort results in a particular order, then run sorted UninstallString list

$
0
0

I am looking for a way to search the registry for the UninstallString for a named piece of software. I have been able to use the info in this post to find the UninstallStrings. But my problem is, I need to uninstall the patches first, in a particular order, then the base software. I have not found a way to properly order these strings.

For the most part each workstation has the same software version and patches. But from time to time we come across a workstation that may have an old version, or the old and new versions installed and we need to remove all instances. Is this possible without having to specifically search for each instance by name?

Programs and Features screenshot:



With this Calabrio 9.2.1 installation, I must uninstall SR3 ES1 first before I can uninstall SR3 then finally the base. The Screen Player Plug-in does not have any dependencies and can be uninstalled in any order.

Here is my script:

$computername=hostname
$osarch = (Get-WmiObject Win32_OperatingSystem -computername $computername).OSArchitecture

If ($osarch = 64) {

$AppVer = Get-ChildItem -Path HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall  |
    Get-ItemProperty |
        Where-Object {$_.DisplayName -match "calabrio" } |
            Select-Object -Property DisplayName, QuietUninstallString, UninstallString

ForEach ($ver in $AppVer) {

    If ($ver.UninstallString) {

        $uninst = $ver.UninstallString
        $app = $ver.DisplayName
        If ($app -like "Calabrio Screen Player Plug-in*") {& Write-Host $app $uninst "/SILENT"
            } Else {& Write-Host $app $uninst
            }
        }
    }
} Else {
    $AppVer = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall  |
    Get-ItemProperty |
        Where-Object {$_.DisplayName -match "calabrio" } |
            Select-Object -Property DisplayName, QuietUninstallString, UninstallString

ForEach ($ver in $AppVer) {

    If ($ver.UninstallString) {

        $uninst = $ver.UninstallString
        $app = $ver.DisplayName
        If ($app -like "Calabrio Screen Player Plug-in*") {& Write-Host $app $uninst "/SILENT"
            } Else {& Write-Host $app $uninst
            }
        }
    }
}

(I added the DisplayName to the output for reference only)

Output:

Calabrio Screen Player Plug-in 9.2(1) "C:\windows\unins000.exe" /SILENT
Calabrio Monitoring and Recording Recording MsiExec.exe /X{5144778B-D71E-4FE5-8AEB-D5A2DAE6DABA}
Calabrio Monitoring and Recording Services Service Release 3 Engineering Special 1 MsiExec.exe /X{CA7F8FC9-1CDD-4AA4-80FB-B07F6A3D7DE5}
Calabrio Monitoring and Recording Services Service Release 3 MsiExec.exe /X{F8DC184C-9851-4476-998B-1FD876270C7A}

Output needs to be sorted as similar:

Calabrio Monitoring and Recording Services Service Release 3 Engineering Special 1 MsiExec.exe /X{CA7F8FC9-1CDD-4AA4-80FB-B07F6A3D7DE5}
Calabrio Monitoring and Recording Services Service Release 3 MsiExec.exe /X{F8DC184C-9851-4476-998B-1FD876270C7A}
Calabrio Monitoring and Recording Recording MsiExec.exe /X{5144778B-D71E-4FE5-8AEB-D5A2DAE6DABA}
Calabrio Screen Player Plug-in 9.2(1) "C:\windows\unins000.exe" /SILENT

I would also like for the script to not have to be edited in case newer versions are installed in the future. That is why I prefer to not use named instances, but if I must, I must.

Any help is appreciated.


I need to get last 7 days .bak files from a 2 node windows cluster

$
0
0

Hi All 

Get-ClusterNode|ForEach-Object { 
$name=$_.name
$time=$_.lastwritetime
$Daysback = "-7"
#$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
$date=$DatetoDelete.ToString('yyyyMMddhhmmss')

#Get-ChildItem -path $fullpath -Recurse -include  *.bak| Where-Object { $_.CreationTime  -le $DatetoDelete }|remove-item
Invoke-Command -ComputerName $name  -ScriptBlock {Get-ChildItem -path $args[0] -Recurse -include  *.bak|sort-object} -ArgumentList $fullpath
}

i have writtern this script to get files of last 7 days am not sure  why its not working for  2 node cluster 



PowerShell exit code from function.

$
0
0

Hi all,

I would like to make and get the exit code and "$?" status from function in PowerShell manually. Can I do it? For example:

function A { Param( $Arg01 ) If (-Not $( $Arg01) )) { exit 101
}

Write-Host All arguments available. } A Write-Host ("`"" + $? + "`", `"" + $LASTEXITCODE + "`""


But the "exit" will exit the whole ps1 script. If change to "return", it will return a "Value", not the exit code, the "$?" also return the "True".

I know it can be solved by separate all the function to individual ps1 script, but I want to confirm is it possible in PowerShell because it may take a script look like easier.

Thank you so mush.

Qho

Powershel Script PSEXEC Problem GUI

$
0
0

Hi all,

I have a problem with one of my scripts to launch psexec on a distant PC.

the command line is :

psexec -u domain\user -p password \\computer cmd.exe

And I have modified it in powershell like this :

Param ([switch]$NoWarning,[switch]$Debug)

If ($Debug) {
    #enable debug messages if -debug is specified
    $debugPreference="Continue"
}

If ($NoWarning) {
    #turn off warning messages
    $WarningPreference="SilentlyContinue"
}
Function Get-MACAddress {
param(
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$Computername = $env:computername
)

$colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration" -computername $Computer | Where{$_.IpEnabled -Match "True"}

foreach ($objItem in $colItems) {

write $objItem.MACAddress

}
}
function Read-InputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText)
{
    Add-Type -AssemblyName Microsoft.VisualBasic
    return [Microsoft.VisualBasic.Interaction]::InputBox($Message, $WindowTitle, $DefaultText)
	Read-InputBoxDialog -WindowTitle "Enter ComputerName" -Message "Please enter the name of the PC to be added to the list" | Out-File $txtComputerList
}
function Ping-Host {
  Param([string]$computername=$(Throw "You must specify a computername."))

  Write-Debug "In Ping-Host function"

  $query="Select * from Win32_PingStatus where address='$computername'"

  $wmi=Get-WmiObject -query $query
  write $wmi
}
Function Get-AllDomains
{
$Root = [ADSI]"LDAP://RootDSE"
$oForestConfig = $Root.Get("configurationNamingContext")
$oSearchRoot = [ADSI]("LDAP://CN=Partitions," + $oForestConfig)
$AdSearcher = [adsisearcher]"(&(objectcategory=crossref)(netbiosname=*))"
$AdSearcher.SearchRoot = $oSearchRoot
$domains = $AdSearcher.FindAll()
return $domains
}

Function Get-MP ($SiteCode)
{
    $domains = Get-AllDomains
    Foreach ($domain in $domains)
    {
        Try {
            $ADSysMgmtContainer = [ADSI]("LDAP://CN=System Management,CN=System," + "$($Domain.Properties.ncname[0])")
            $AdSearcher = [adsisearcher]"(&(Name=SMS-MP-$SiteCode-*)(objectClass=mSSMSManagementPoint))"
            $AdSearcher.SearchRoot = $ADSysMgmtContainer
            $ADManagementPoint = $AdSearcher.FindONE()
            $MP = $ADManagementPoint.Properties.mssmsmpname[0]
        } Catch {}
    }

    Return $MP
}
Function Get-SiteCode {
    param(
        [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [string[]]$Computername = $env:computername
        )

    $CCMClientClass = [wmiclass]"\\$ComputerName\root\ccm:sms_client"
    $CCMSiteCode = $CCMClientClass.GetAssignedSite().sSiteCode

    write $CCMSiteCode
}
function Get-OS {
  Param([string]$computername=$(Throw "You must specify a computername."))
  Write-Debug "In Get-OS Function"
  $wmi=Get-WmiObject Win32_OperatingSystem -computername $computername -ea stop
   write $wmi

}

function Get-Architecture {
[cmdletbinding()]
param(
    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
    [string[]]$Computername = $env:computername
)
Write-Debug "In Get-Architecture Function"
$version  = (Get-WmiObject -computername $computer -class Win32_OperatingSystem ).OSArchitecture
write $version
 }
 function Get-SCCMVersion {
#[cmdletbinding()]
#param(
#    [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
#    [string[]]$Computername = $env:computername
#)
Write-Debug "In Get-SCCMVersion Function"
$SCCMVersion  =  (Get-WMIObject -ComputerName $computer -namespace root\ccm -class sms_client).ClientVersion
write $SCCMVersion
 }
 function Get-OU {

[CmdletBinding()]
#requires -version 3
param(
    [parameter(ParameterSetName = "ComputerName", Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
    $ComputerName,
    [switch]$ValueOnly
)

begin
{
    $rootDse = New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
    $Domain = $rootDse.DefaultNamingContext
    $root = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$Domain")
}

process
{
    if ($PSCmdlet.ParameterSetName -ne "ComputerName")
    {
        $ComputerName = $env:COMPUTERNAME
    }

    $searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
    $searcher.Filter = "(&(objectClass=computer)(name=$ComputerName))"
    [System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
    if (!$?)
    {
        return
    }
    $dn = $result.Properties["distinguishedName"]
    $ouResult = $dn.Substring($ComputerName.Length + 4)
    if ($ValueOnly)
    {
        $ouResult
    } else {
        New-Object PSObject -Property @{"Name" = $ComputerName; "OU" = $ouResult}
    }
}

}


#Generated Form Function
function GenerateForm {

#region Import the Assemblies
Write-Debug "Loading Assemblies"
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion

#region Generated Form Objects
Write-Debug "Creating form objects"
$form1 = New-Object System.Windows.Forms.Form
$lblRefreshInterval = New-Object System.Windows.Forms.Label
$numInterval = New-Object System.Windows.Forms.NumericUpDown
$btnQuit = New-Object System.Windows.Forms.Button
$btnGo = New-Object System.Windows.Forms.Button
$dataGridView = New-Object System.Windows.Forms.DataGridView
$label2 = New-Object System.Windows.Forms.Label
$statusBar = New-Object System.Windows.Forms.StatusBar
$txtComputerList = New-Object System.Windows.Forms.TextBox
$timer1 = New-Object System.Windows.Forms.Timer
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
$LaunchPSexec =
{
    #only launch PSexec if a cell in the Computername
    #column was selected
	$c=$dataGridView.CurrentCell.columnindex
    $colHeader=$dataGridView.columns[$c].name
    if ($colHeader -eq "Computername") {
        $computer=$dataGridView.CurrentCell.Value
        Write-Debug ("Launch PSEXEC for {0}" -f $computer.toUpper())
		Set-Service -Name LanmanServer -ComputerName $computer -StartupType Automatic -Status Running
		Set-Service -Name RemoteRegistry -ComputerName $computer -StartupType Automatic -Status Running

		[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
		$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

		$response = Read-host "What's your password?" -AsSecureString
		$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($response))

		psexec -u $user -p $password "\\$computer" cmd.exe
		}

} #end Launch PSexec script block

$GetStatus=
{

 Trap {
    	Write-Debug "Error trapped in GetStatus script block"
    	Write-Warning $_.Exception.message
        Continue
    }

    #stop the timer while data is refreshed
    Write-Debug "Stop the timer"
    $timer1.stop()

    Write-Debug ("Getting content from {0}" -f $txtComputerlist.Text)
    if ($computers) {Clear-Variable computers}

    #clear the table
    $dataGridView.DataSource=$Null

    $computers=Get-Content $txtComputerList.Text -ea stop

    if ($computers) {

        $statusBar.Text = ("Querying computers from {0}" -f $txtComputerList.Text)
        $form1.Refresh

        #create an array for griddata
        Write-Debug "Create `$griddata"
        $griddata=@()
        #create a custom object

        foreach ($computer in $computers) {
          Write-Debug "Pinging $computer"
          $statusBar.Text=("Pinging {0}" -f $computer.toUpper())
          Write-Debug "Creating `$obj"
          $obj=New-Object PSobject
          Write-Debug "Adding Computername property"
          $obj | Add-Member Noteproperty Computername $computer.ToUpper()

          #ping the computer
          if ($pingResult) {
            #clear PingResult if it has a left over value
            Clear-Variable pingResult
            }
          $pingResult=Ping-Host $computer
          Write-Debug "Pinged status code is $($pingResult.Statuscode)"

          if ($pingResult.StatusCode -eq 0) {

               $obj | Add-Member Noteproperty Pinged "Yes"
               Write-Debug "Adding $($pingresult.ProtocolAddress)"
               $obj | Add-Member Noteproperty IP $pingResult.ProtocolAddress

               #get remaining information via WMI
               Trap {
                #define a trap to handle any WMI errors
                Write-Warning ("There was a problem with {0}" -f $computer.toUpper())
                Write-Warning $_.Exception.GetType().FullName
                Write-Warning $_.Exception.message
                Continue
                }

                if ($os) {
                    #clear OS if it has a left over value
                    Clear-Variable os
                }
                if ($versions) {
                    #clear OS if it has a left over value
                    Clear-Variable Architecture
                }
				$OUComputer = Get-OU -ComputerName $computer -ValueOnly
				write $OUComputer
         $OSversion = Get-Architecture $versions
   if ((Get-WmiObject -Class Win32_OperatingSystem -ComputerName $Computer -ea 0).OSArchitecture -eq '64-bit') {
    $architecture = "64-Bit"
   } else  {
    $architecture = "32-Bit"
   }
   $SCCMClient = Get-SCCMVersion $SCCMVersion
   write $SCCMClient
  	 if ($SCCMClient -like '4.00.*') {
    $SCCMClient = "SCCM 2007"
   }

   else {
    $SCCMClient = "SCCM 2012"
   }
   if ($ManagementPoint=Get-MP -SiteCode (Get-SiteCode -Computername $Computer)) {
   write $ManagementPoint
   }
   $MACAddress = Get-MACAddress -Computername $computer
      if ($OSVersion){
                   $architectures = $OSversion.OSArchitecture
                   Write-Debug "Adding $architecture"}
                   $os=Get-OS $computer
			       $SCCMClient
				   Write-Debug "Adding $SCCMClient"

               if ($os) {
                   $lastboot=$os.ConvertToDateTime($os.lastbootuptime)
                   Write-Debug "Adding $lastboot"
                   #$uptime=((get-date) - ($os.ConvertToDateTime($os.lastbootuptime))).tostring()
                   #Write-Debug "Adding $uptime"
                   $osname=$os.Caption
                   Write-Debug "Adding $osname"
                   $MACAddress
                   Write-Debug "Adding $MACAddress"
                   $ManagementPoint
                   Write-Debug "Adding $ManagementPoint"
				   $OUComputer
                   Write-Debug "Adding $OUComputer"

                   $obj | Add-Member Noteproperty MAC_Address $MACAddress
                   $obj | Add-Member Noteproperty OU_Computer $OUComputer
                   $obj | Add-Member Noteproperty Management_Point $ManagementPoint
                   $obj | Add-Member Noteproperty OS $osname
				   $obj | Add-Member Noteproperty Architecture $architecture
                   $obj | Add-Member Noteproperty SCCM_Version $SCCMClient
                   $obj | Add-Member Noteproperty LastBoot $lastboot

               }
               else {
               Write-Debug "Setting properties to N/A"

				   $obj | Add-Member Noteproperty MAC_Address "N/A"
                   $obj | Add-Member Noteproperty OU_Computer "N/A"
                   $obj | Add-Member Noteproperty Management_Point "N/A"
                   $obj | Add-Member Noteproperty OS "N/A"
				   $obj | Add-Member Noteproperty Architecture "N/A"
                   $obj | Add-Member Noteproperty SCCM_Version "N/A"
                   $obj | Add-Member Noteproperty LastBoot "N/A"

				    }
          }
          else {
                Write-Debug "Ping failed"
                Write-Debug "Setting properties to N/A"


               $obj | Add-Member Noteproperty Pinged "No"
               $obj | Add-Member Noteproperty IP "N/A"
			   $obj | Add-Member Noteproperty MAC_Address "N/A"
               $obj | Add-Member Noteproperty OU_Computer "N/A"
               $obj | Add-Member Noteproperty Management_Point "N/A"
               $obj | Add-Member Noteproperty OS "N/A"
			   $obj | Add-Member Noteproperty Architecture "N/A"
               $obj | Add-Member Noteproperty SCCM_Version "N/A"
               $obj | Add-Member Noteproperty LastBoot "N/A"

          }

        	#Add the object to griddata
            	Write-Debug "Adding `$obj to `$griddata"
            	$griddata+=$obj


        } #end foreach

        Write-Debug "Creating ArrayList"
        $array= New-Object System.Collections.ArrayList

        Write-Debug "Adding `$griddata to `$arry"
        $array.AddRange($griddata)
        $DataGridView.DataSource = $array
        #find unpingable computer rows
        Write-Debug "Searching for non-pingable computers"
        $c=$dataGridView.RowCount
        for ($x=0;$x -lt $c;$x++) {
            for ($y=0;$y -lt $dataGridView.Rows[$x].Cells.Count;$y++) {
                $value = $dataGridView.Rows[$x].Cells[$y].Value
                if ($value -eq "No") {
                #if Pinged cell = No change the row font color
                Write-Debug "Changing color on row $x"
                $dataGridView.rows[$x].DefaultCellStyle.Forecolor=[System.Drawing.Color]::FromArgb(255,255,0,0)
                }
            }
        }
        Write-Debug "Setting status bar text"
        $statusBar.Text=("Ready. Last updated {0}" -f (Get-Date))

    }
    else {
        Write-Debug "Setting status bar text"
        $statusBar.Text=("Failed to find {0}" -f $txtComputerList.text)
    }

   #set the timer interval
    $interval=$numInterval.value -as [int]
    Write-Debug "Interval is $interval"
    #interval must be in milliseconds
    $timer1.Interval = ($interval * 60000) #1 minute time interval
    Write-Debug ("Timer interval calculated at {0} milliseconds" -f $timer1.Interval )
    #start the timer
    Write-Debug "Starting timer"
    $timer1.Start()

    Write-Debug "Refresh form"
    $form1.Refresh()

} #End GetStatus scriptblock

$Quit=
{
    Write-Debug "closing the form"
    $form1.Close()
} #End Quit scriptblock

#----------------------------------------------
#region Generated Form Code
$form1.Name = 'form1'
$form1.Text = 'Display Computer Status'
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 890
$System_Drawing_Size.Height = 359
$form1.ClientSize = $System_Drawing_Size
$form1.StartPosition = 1
$form1.BackColor = [System.Drawing.Color]::FromArgb(255,185,209,234)

$lblRefreshInterval.Text = 'Refresh Interval (min)'

$lblRefreshInterval.DataBindings.DefaultDataSourceUpdateMode = 0
$lblRefreshInterval.TabIndex = 10
$lblRefreshInterval.TextAlign = 64
#$lblRefreshInterval.Anchor = 9
$lblRefreshInterval.Name = 'lblRefreshInterval'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 128
$System_Drawing_Size.Height = 23
$lblRefreshInterval.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 440
$System_Drawing_Point.Y = 28
$lblRefreshInterval.Location = $System_Drawing_Point

$form1.Controls.Add($lblRefreshInterval)

#$numInterval.Anchor = 9
$numInterval.DataBindings.DefaultDataSourceUpdateMode = 0
$numInterval.Name = 'numInterval'
$numInterval.Value = 10
$numInterval.TabIndex = 9
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 51
$System_Drawing_Size.Height = 20
$numInterval.Size = $System_Drawing_Size
$numInterval.Maximum = 60
$numInterval.Minimum = 1
$numInterval.Increment = 2
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 575
$System_Drawing_Point.Y = 30
$numInterval.Location = $System_Drawing_Point
# $numInterval.add_ValueChanged($GetStatus)

$form1.Controls.Add($numInterval)


$btnQuit.UseVisualStyleBackColor = $True
$btnQuit.Text = 'Close'

$btnQuit.DataBindings.DefaultDataSourceUpdateMode = 0
$btnQuit.TabIndex = 2
$btnQuit.Name = 'btnQuit'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$btnQuit.Size = $System_Drawing_Size
#$btnQuit.Anchor = 9
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 341
$System_Drawing_Point.Y = 30
$btnQuit.Location = $System_Drawing_Point
$btnQuit.add_Click($Quit)

$form1.Controls.Add($btnQuit)


$btnGo.UseVisualStyleBackColor = $True
$btnGo.Text = 'Get Status'

$btnGo.DataBindings.DefaultDataSourceUpdateMode = 0
$btnGo.TabIndex = 1
$btnGo.Name = 'btnGo'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$btnGo.Size = $System_Drawing_Size
#$btnGo.Anchor = 9
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 233
$System_Drawing_Point.Y = 31
$btnGo.Location = $System_Drawing_Point
$btnGo.add_Click($GetStatus)

$form1.Controls.Add($btnGo)

$dataGridView.RowTemplate.DefaultCellStyle.ForeColor = [System.Drawing.Color]::FromArgb(255,0,128,0)
$dataGridView.Name = 'dataGridView'
$dataGridView.DataBindings.DefaultDataSourceUpdateMode = 0
$dataGridView.ReadOnly = $True
$dataGridView.AllowUserToDeleteRows = $False
$dataGridView.RowHeadersVisible = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 870
$System_Drawing_Size.Height = 260
$dataGridView.Size = $System_Drawing_Size
$dataGridView.TabIndex = 8
$dataGridView.Anchor = 15
$dataGridView.AutoSizeColumnsMode = 16



$dataGridView.AllowUserToAddRows = $False
$dataGridView.ColumnHeadersHeightSizeMode = 2
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 70
$dataGridView.Location = $System_Drawing_Point
$dataGridView.AllowUserToOrderColumns = $True
$dataGridView.add_CellContentDoubleClick($LaunchPsexec)
#$dataGridView.AutoResizeColumns([System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells]::AllCells)
$DataGridViewAutoSizeColumnsMode.AllCells

$form1.Controls.Add($dataGridView)

$label2.Text = 'Enter the name and path of a text file with your list of computer names: (One name per line)'

$label2.DataBindings.DefaultDataSourceUpdateMode = 0
$label2.TabIndex = 7
$label2.Name = 'label2'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 490
$System_Drawing_Size.Height = 23
$label2.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 7
$label2.Location = $System_Drawing_Point

$form1.Controls.Add($label2)

$statusBar.Name = 'statusBar'
$statusBar.DataBindings.DefaultDataSourceUpdateMode = 0
$statusBar.TabIndex = 4
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 428
$System_Drawing_Size.Height = 22
$statusBar.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 337
$statusBar.Location = $System_Drawing_Point
$statusBar.Text = 'Ready'

$form1.Controls.Add($statusBar)

$txtComputerList.Text = "$env:userprofile\Desktop\computers.txt"
$txtComputerList.Name = 'txtComputerList'
$txtComputerList.TabIndex = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 198
$System_Drawing_Size.Height = 20
$txtComputerList.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 33
$txtComputerList.Location = $System_Drawing_Point
$txtComputerList.DataBindings.DefaultDataSourceUpdateMode = 0

$form1.Controls.Add($txtComputerList)


#endregion Generated Form Code

Write-Debug "Adding script block to timer"
#add the script block to execute when the timer interval expires
$timer1.add_Tick($GetStatus)

#Show the Form
Write-Debug "ShowDialog()"
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
Write-Debug "Call GenerateForm"
GenerateForm

But the problem is that when i doubleclick on the computername the Psexec is not launching and its blocking my GUI.

Can you help me please?

Thank you in advance.


Tiger666


Command Window Stuck In Insert Mode

$
0
0

Hi All,

On my PS command window, it is always in "Insert" mode. Drives me nuts.

Just a personal preference, but I much prefer "Overstrike".

Possible remedies:

  • Change window "Defaults"
  • Change window "Properties"
  • Hit the "Insert" key

None of this has any effect. What could possibly be the problem?


Stopping A service and getting confirmation and then proceed to next service

$
0
0

Hi ,

 we have inhouse services, i would like to stop this one by one in an order, i want to stop the first service and then wait for the confirmation and stop t he 2nd and also the 3rd. how can i achieve this.. i dint start the script yet.. is there way with stop-service to achieve this?

My hard drives were encrypted by Cryptowall virus

$
0
0
My hard drives were encrypted by Cryptowall virus, I bought the key but its giving me a errors, found a person who started to help me, he even decrypted one of my files, but its not completely working, I'm new at PowerShell so any help would be appreciated. Here is the code (text only) sent by the hackers, http://hastebin.com/raw/yanotavovo and here is the code sent by the guy who helped mehttp://hastebin.com/raw/xagowawumi also I had 3 files in every folder that was encrypted which is located here also jus Texthttp://hastebin.com/raw/siceyavezi. Any help would be great, I am willing to pay for your time. Thank You my email isteebee101@gmail.com

Mouse Click

$
0
0

I'm looking for mouse click function in powershell script  since last night and i can't find no one that work.

I have been tried the script from link but don't work. Does anybody some powershell script to simulate mouse left and right click?

Thanks!

Remove or Replace pipe character from the string variable

$
0
0
Remove or Replace pipe character from the string variable I have string which have pipe character and I want to remove it. Kindly somebody tell me how can we do that.

Check if PasswordNeverExpire is True or False and store and store it in variable

$
0
0

Hello All,

Sorry if my english is not very well.

I need to store the status of user properties "PasswordNeverExpires" in variable to use it later in another command of a script.

for exemple:

$status = get-aduser -identity user1  -properties PasswordNeverExpires | select PasswordNeverExpires

new-aduser -Name  test -PasswordNeverExpires $status

Thank you very muhc for your help


Orwell

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>