Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Can this script trigger a reboot on Windows 7?

$
0
0

Hello,

I have a very simple script to install a plugin for Outlook. Would someone be so kind and tell me if it is possible that this script triggers a reboot?

$installer = "$PSScriptRoot\Outlook Add-In Setup 13.0.19204.1650.exe"
$args = @("/s"
)

start-process $installer $args -wait

$wshell = New-Object -ComObject Wscript.Shell
$return = $wshell.Popup("Das NoSpamProxy Outlook-Plugin wurde auf die neueste Version aktualisiert. Starten Sie bitte Outlook neu, damit die Aenderungen wirksam werden..",0,"OK")

For some reason, after deploying it to around 500 Windows 7 workstations using SCCM , we have received complaints that the workstations got rebooted about 3 seconds after the popup appeared, without giving the User any warnings or anything. But it did not happen on all workstations, it was less than 10. I'm trying to identify if the method to call the popup could, in any way, send a message to the OS to reboot.

Kind regards,

Wojciech


Enable OK Button when more Form Boxes are populated

$
0
0

Hi Scripting Guys,

I would like to ask you how can I enable OK button only when both boxes (textBox and ListBox) are populated (or more boxes like ListBoxes and ComboBoxes), not just One box populated..

I have found a peace of script:

$textBox.add_TextChanged({$OKButton.Enabled = $textBox.Text})
$listBox.add_SelectedIndexChanged({$OKButton.enabled = $listBox.Text})

which can do it just for one box, but I need to enable OK button only when multiple boxes are populated.

Here is the script:

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

# Form setup

$form = New-Object System.Windows.Forms.Form
$form.Text = 'Custom Form'
$form.Size = New-Object System.Drawing.Size(400,350)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = 'Fixed3D'
$form.MaximizeBox = $false

# Buttons

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(100,270)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$OKButton.Enabled = $false
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(200,270)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)

# Labels

$label1 = New-Object System.Windows.Forms.Label
$label1.Location = New-Object System.Drawing.Point(10,10)
$label1.Size = New-Object System.Drawing.Size(230,20)
$label1.Text = 'Name:'
$form.Controls.Add($label1)

$label2 = New-Object System.Windows.Forms.Label
$label2.Location = New-Object System.Drawing.Point(10,80)
$label2.Size = New-Object System.Drawing.Size(280,20)
$label2.Text = 'Select Item:'
$form.Controls.Add($label2)

# TextBox

$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,30)
$textBox.Size = New-Object System.Drawing.Size(260,40)
$textBox.Height = 40
$form.Controls.Add($textBox)


# Listbox Items


$listBox = New-Object System.Windows.Forms.listBox
$listBox.Location = New-Object System.Drawing.Point(10,100)
$listBox.Size = New-Object System.Drawing.Size(260,40)
$listBox.Height = 80
[void] $listBox.Items.Add('Item1')
[void] $listBox.Items.Add('Item2')
[void] $listBox.Items.Add('Item3')
[void] $listBox.Items.Add('')
$listBox.SelectionMode = 'MultiExtended'
$form.Controls.Add($listBox)


# Enable OK Button when boxes are populated


$textBox.add_TextChanged({$OKButton.Enabled = $textBox.Text})
$listBox.add_SelectedIndexChanged({$OKButton.enabled = $listBox.Text})


$form.Topmost = $true

$result = $form.ShowDialog()

if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
    $x = $textBox.Text
    $x

    $y = $listBox.SelectedItem
    $y
}

Thank you very much.

Martin


How do I create xlsx files in Powershell without using Excel.Application?

$
0
0

How do I convert files between CSV, XLS, XLSM, and XLSX to CSV, XLS, XLSX, and XML in Powershell without using Excel.Application? I would like to just use MICROSOFT.ACE.OLEDB.12.0.

Create incremented variables from objects in another variable.

$
0
0

I have a variable $running_vms that has all of the VM names on that host.

$running_vms = Get-VM | Where-Object State -ne Off | ForEach-Object Name

I want to create an incremented variable with each VM name in it so that I can run Measure-VM against it.

I know that i will need a ForEach-Object loop and a way to increment the variable number, and I'm not sure how to get the names in their own variable. 

$running_vms | ForEach-Object `
{
    $n++
    New-Variable -Name $vm + $n
}

If you could point me to the correct documentation, or provide any assistance I would greatly appreciate it!

Powershell Script to Choose PC to Run Command on

$
0
0

Hello, 

Working to get a powershell script running where I can run it through a normal powershell window and select the PC in the script itself. 

 param
    (       
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$computer
    )


$destpath = "\\$computer\C$\installs\.exe"
$sourcepath = "\Source Path"

{
        #Add Ports
       Add-PrinterPort -Name "PrinterPort" -PrinterHostAddress 127.0.0.1 -ComputerName $Computer
       #Add Print Driver
       Add-PrinterDriver -Name "Generic / Text Only" -ComputerName $Computer    
      #Add Printer
      Add-Printer -ComputerName $Computer -Name "PRINTER" -PortName "Printer" -DriverName "Generic / Text Only"

      New-Item -Path \\$computer\C$\installs\Folder -ItemType directory
      Copy-Item $sourcepath -Destination $destpath -Recurse -Verbose 
     
     }
     

When i run this it gives me the option to choose PC but script doesnt run

Any tips would be helpful, still gaining powershell knowledge as I go. 

Winfows Form PowerShell

$
0
0
Hello,

I am creating an interface in the power shell with forms, and I need to click on the button it runs the command I set and return the result in a text field that I put in forms too.

Example:

Path field:

Command: Get-acl <value dictated in path field>

Button

Result Field: Returns Get-acl Path Command Value

how do i make it work?

Auto Sync in Source control not working due to errors in Process-SourceControlWebhook

$
0
0
I hope someone can help me with this issue. I've set up a devops repo where my account is a project administrator. I've set up the source controll sync between my automation account in Azure and my DevOps repo. When I do a manual sync the runbooks are synced to my automation account without a problem. But when I push to the repo I see the Process-SourceControlWebhook job being made and run and it shows completed, but with the following output (I've replaced the project and company name):
Getting Azure Connection information

Getting the source control information

SourceControl Properties : [RepoUrl = https://NAME.visualstudio.com/NAME/_git/Azure-Automation] ,[Branch = Azure-PROD] , [FolderPath = /RunBooks]

UrlConnectionInformation: [AccountName = NAME.visualstudio.com] [RepoName = Azure-Automation] [ProjectName = NAME]

No need to start syncjob for following reason : 
So it suggest there is nothing to sync, but when I do a manual sync it will sync stuff. When I look at the error stream for this job it shows the following errors:
The property 'refUpdates' cannot be found on this object. Verify that the property exists. At line:911 char:5 + $actualBranch = $WebhookDataObject.resource.refUpdates.name + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException + FullyQualifiedErrorId : PropertyNotFoundStrict
Compare-Branch : Cannot validate argument on parameter 'ActualBranch'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At line:912 char:62 + ... (Compare-Branch -ExpectedBranch $Branch -ActualBranch $actualBranch) + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Compare-Branch], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Compare-Branch
I've updated the azurerm modules to the latest version alraedy. We are having this problem is different tenants with different repo's. But some repo's we set up earlier to sync do seem to work so it looks like something changed which blocks this from working. Does anyone has an idea where to look or how to fix this?

inventory

$
0
0

Hi Experts

i want to pull the aws inventory for all my ec2 instances, i am using the below ps1 but i am not getting any output, experts help me correct the script

<#
This script creates AWS Inventory
#>

Remove-Item -LiteralPath "C:\AWSInven" -Force -Recurse

Write-Host "----- Pre Requisites -----`n" -ForegroundColor Yellow
Write-Host "1. Make sure you have AWS tools for Powershell installed. You can download the same at: https://aws.amazon.com/powershell/ `n" -ForegroundColor Yellow
Write-Host "2. Set up AWSpowershell modules. Getting started link: http://docs.aws.amazon.com/powershell/latest/userguide/ `n" -ForegroundColor Yellow
Write-Host "3. Enable execution policy accordingly. Set it to either RemoteSigned OR Unrestricted `n`n" -ForegroundColor Yellow

# Declaring variables
$AWS_AccessKey = (Read-Host "Enter AWS Access Key")
$AWS_SecretKey = (Read-Host "Enter AWS Secret Key")

# Create a Workbook
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add()

# creating a variable to contain the AWS Regions
$Global:AWS_Locations = (Read-Host "Enter Region Name to fetch the inventory")

# Creating a directory, overrides if any directory exists with the same name
Write-Host "Creating a directory: C:\AWSInven. This operation will override if you have a directory with the same name. `n" -ForegroundColor Yellow
New-Item C:\AWSInven -Type Directory -Force

# We will encounter exceptions while running methods on a null-valued expression. This is expected. So it is safe to ignore them.
$ErrorActionPreference = "SilentlyContinue"


# Setting the AWS credentials
Set-AWSCredentials -AccessKey $AWS_AccessKey -SecretKey $AWS_SecretKey -StoreAs myawsprofile

# Setting the profile, so we can execute the cmdlets
Set-AWSCredentials -ProfileName myawsprofile 

# Creating EXCEL object
#$excel = New-Object -ComObject excel.application



# Function to creat the EC2 Instance worksheet 
function Create-EC2InstanceWorksheet { 
 
        Write-Host "Creating EC2 Instances Worksheet..`n`n" -ForegroundColor Green 
        # Adding worksheet 
        $workbook.Worksheets.Add() 
        # Creating the worksheet for Virtual Machine 
        $VirtualMachineWorksheet = $workbook.Worksheets.Item(1) 
        $VirtualMachineWorksheet.Name = 'VirtualMachine' 
        # Headers for the worksheet 
        $VirtualMachineWorksheet.Cells.Item(1,1) = 'Region'  
        $VirtualMachineWorksheet.Cells.Item(1,2) = 'VM Image ID' 
        $VirtualMachineWorksheet.Cells.Item(1,3) = 'VM Instance ID' 
        $VirtualMachineWorksheet.Cells.Item(1,4) = 'VM Instance Type' 
        $VirtualMachineWorksheet.Cells.Item(1,5) = 'VM Private IP' 
        $VirtualMachineWorksheet.Cells.Item(1,6) = 'VM Public IP' 
        $VirtualMachineWorksheet.Cells.Item(1,7) = 'VM VPC ID' 
        $VirtualMachineWorksheet.Cells.Item(1,8) = 'VM Subnet ID' 
        $VirtualMachineWorksheet.Cells.Item(1,9) = 'VM State' 
        $VirtualMachineWorksheet.Cells.Item(1,10) = 'VM Security Group Id'
        $VirtualMachineWorksheet.Cells.Item(1,11) = 'TagName'
        $VirtualMachineWorksheet.Cells.Item(1,12) = 'TagValue'
        $VirtualMachineWorksheet.Cells.Item(1,13) = 'StartTimeinUTC'
        $VirtualMachineWorksheet.Cells.Item(1,14) = 'StopTimeinUTC'
		$VirtualMachineWorksheet.Cells.Item(1,15) = 'Platform' 
        # Excel Cell Counter 
        $row_counter = 3 
        $column_counter = 1 
    # Get the Ec2 instances for each region 
    foreach($AWS_Locations_Iterator in $AWS_Locations){ 
        $EC2Instances = Get-EC2Instance -Region $AWS_Locations_Iterator
        # Iterating over each instance 
        foreach($EC2Instances_Iterator in $EC2Instances){ 
            # Ignore if a region does not have any instances 
            if($EC2Instances_Iterator.count -eq $null) { 
            continue 
            }
            #USing regex t split date for Stop Operation.

            # Populating the cells 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $AWS_Locations_Iterator  
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.imageid 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.Instanceid 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.Instancetype.Value 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.PrivateIpAddress 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.PublicIpAddress 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.vpcid 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.SubnetId 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.state.name.value 
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.securitygroups.GroupId
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.Tag.Key
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.Tag.Value
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.LaunchTime.ToUniversalTime()
            $VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.StateTransitionReason
			$VirtualMachineWorksheet.Cells.Item($row_counter,$column_counter++) = $EC2Instances_Iterator.Instances.Platform.Value
            # Seting the row and column counter for next EC2 instance entry 
            $row_counter = $row_counter + 1 
            $column_counter = 1 
        } 
        # Iterating to the next region 
        $row_counter = $row_counter + 3 
    } 
}


function Create-EC2VolumeWorksheet {

        Write-Host "Creating EC2 Volume Worksheet..`n`n" -ForegroundColor Green
        # Adding worksheet
        $workbook.Worksheets.Add()

        # Creating the worksheet for Volume
        $Ec2_Volume_Worksheet = $workbook.Worksheets.Item(1)
        $Ec2_Volume_Worksheet.Name = 'Volumes'

        # Headers for the worksheet
        $Ec2_Volume_Worksheet.Cells.Item(1,1) = 'Region'
        $Ec2_Volume_Worksheet.Cells.Item(1,2) = 'Device'
        $Ec2_Volume_Worksheet.Cells.Item(1,3) = 'InstanceID'
        $Ec2_Volume_Worksheet.Cells.Item(1,4) = 'VolumeID'
        $Ec2_Volume_Worksheet.Cells.Item(1,5) = 'State'
        $Ec2_Volume_Worksheet.Cells.Item(1,6) = 'Availability Zone'
        $Ec2_Volume_Worksheet.Cells.Item(1,7) = 'VolumeType'
        $Ec2_Volume_Worksheet.Cells.Item(1,8) = 'Size'


        # Cell Counter
        $row_counter = 3
        $column_counter = 1

        # Get the AWS VPC for each region

        foreach($AWS_Locations_Iterator in $AWS_Locations){
        $EC2_Volumes = Get-EC2volume -Region $AWS_Locations_Iterator



        foreach($EC2_Volume_Iterator in $EC2_Volumes){
        # Populating the cells
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $AWS_Locations_Iterator
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.Attachments.Device
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.Attachments.InstanceID
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.Attachments.VolumeID
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.Attachments.State.Value
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.AvailabilityZone
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.VolumeType.Value
            $Ec2_Volume_Worksheet.Cells.Item($row_counter,$column_counter++) = $EC2_Volume_Iterator.size
            # Seting the row and column counter for next EC2 Volume entry
            $row_counter = $row_counter + 1
            $column_counter = 1
        }

        # Iterating to the next region
        $row_counter = $row_counter + 3
    }
}

# Calling functions

Create-EC2InstanceWorksheet
Create-EC2VolumeWorksheet


# Checking if the AWSInven.xlsx already exists
if(Test-Path C:\AWSInven\Inventory.xlsx){
    Write-Host "C:\AWSInven\AWSInven.xlsx already exitst. Deleting the current file and creating a new one. `n" -ForegroundColor Yellow
    Remove-Item C:\AWSInven\AWSInven.xlsx
    # Saving the workbook/excel file
    $workbook.SaveAs("C:\AWSInven\AWSInven.xlsx")
}else {
    # Saving the workbook/excel file
    $workbook.SaveAs("C:\AWSInven\AWSInven.xlsx")
}

Write-Host "File is saved as - C:\AWSInven\AWSInven.xlsx `n" -ForegroundColor Green

# Prompting the user if he/she wants to open the Inventory sheet.
$openExcelFlag = Read-Host "Type YES to open the Inventory sheet. Type NO to quit."
if($openExcelFlag -eq 'YES' -or $openExcelFlag -eq 'yes' -or $openExcelFlag -eq 'y') {
    Invoke-Item C:\AWSInven\AWSInven.xlsx
        # Removing the lock on the file
        $workbook.close()
        $excel.Quit()
}else {
    # Removing the lock on the file
    $workbook.close()
    $excel.Quit()
}


PowerShell - Run Command with Windows Form

$
0
0

Hello,

What is wrong with my code?

In the first textbox, the command work

but in the second textbox, the command not work.

but if I put the group name instead of a variable, the command works

Below is the complete code:

function Show-mainform2_psf {

    Add-Type -AssemblyName System.Windows.Forms
    import-module activedirectory


    #region Generated Form Objects
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $textboxResultado = New-Object 'System.Windows.Forms.TextBox'
    $textboxCheckPath = New-Object 'System.Windows.Forms.TextBox'
    $textboxCheckGroup = New-Object 'System.Windows.Forms.TextBox'
    $buttonCheckOwnerGroup = New-Object 'System.Windows.Forms.Button'
    $buttonClickMe = New-Object 'System.Windows.Forms.Button'
    $buttonOK = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    #endregion Generated Form Objects

    
    $form1_Load={
        
    }
    
    
    $buttonClickMe_Click={
        $textboxResultado.Lines = (Get-Acl $textboxCheckPath.Lines).Access | ft IdentityReference,FileSystemRights -auto | Out-String
    }



    $buttonCheckOwnerGroup_Click={
        $textboxResultado.Lines = Get-ADGroup -Identity $textboxCheckGroup.Lines -Properties Name,Description,info | select Name,Description,Info | Out-String
    }
    
    #region Generated Events
    $Form_StateCorrection_Load=
    {
        #Correct the initial state of the form to prevent the .Net maximized form issue
        $form1.WindowState = $InitialFormWindowState
    }
    
    $Form_Cleanup_FormClosed=
    {
        #Remove all event handlers from the controls
        try
        {
            $buttonClickMe.remove_Click($buttonClickMe_Click)
            $form1.remove_Load($form1_Load)
            $form1.remove_Load($Form_StateCorrection_Load)
            $form1.remove_FormClosed($Form_Cleanup_FormClosed)
        }
        catch { Out-Null <# Prevent PSScriptAnalyzer warning #> }
    }
    #endregion Generated Events

    #region Generated Form Code
    # form1
    #
    $form1.Controls.Add($textboxResultado)
    $form1.Controls.Add($textboxCheckPath)
    $form1.Controls.Add($textboxCheckGroup)
    $form1.Controls.Add($buttonClickMe)
    $form1.Controls.Add($buttonCheckOwnerGroup)
    $form1.Controls.Add($buttonOK)
    $form1.AcceptButton = $buttonOK
    $form1.AutoScaleDimensions = '6, 13'
    $form1.AutoScaleMode = 'Font'
    $form1.ClientSize = '711, 483'
    $form1.FormBorderStyle = 'FixedDialog'
    $form1.MaximizeBox = $False
    $form1.MinimizeBox = $False
    $form1.Name = 'Check Folder'
    $form1.StartPosition = 'CenterScreen'
    $form1.Text = 'Check Folder'
    $form1.add_Load($form1_Load)
    #
    # textboxCheckGroup
    #
      $textboxCheckGroup.Location = '23, 45'
    $textboxCheckGroup.Multiline = $True
    $textboxCheckGroup.Name = 'textboxCheckGroup'
    $textboxCheckGroup.Size = '300, 20'
    $textboxCheckGroup.TabIndex = 4
    #
    # textboxCheckPath
    #
      $textboxCheckPath.Location = '23, 15'
    $textboxCheckPath.Multiline = $True
    $textboxCheckPath.Name = 'textboxCheckPath'
    $textboxCheckPath.Size = '300, 20'
    $textboxCheckPath.TabIndex = 3
    #
    # textboxResultado
    #
    $textboxResultado.Location = '23, 150'
    $textboxResultado.Multiline = $True
    $textboxResultado.Name = 'textboxResultado'
    $textboxResultado.Size = '476, 178'
    $textboxResultado.TabIndex = 2
    #
    # buttonCheckOwnerGroup
    #
    $buttonCheckOwnerGroup.Location = '330, 44'
    $buttonCheckOwnerGroup.Name = 'CheckOwnerGroup'
    $buttonCheckOwnerGroup.Size = '120, 23'
    $buttonCheckOwnerGroup.TabIndex = 5
    $buttonCheckOwnerGroup.Text = 'Check Owner Group'
    $buttonCheckOwnerGroup.UseCompatibleTextRendering = $True
    $buttonCheckOwnerGroup.UseVisualStyleBackColor = $True
    $buttonCheckOwnerGroup.add_Click($buttonCheckOwnerGroup_Click)
    #
    # buttonClickMe
    #
    $buttonClickMe.Location = '330, 13'
    $buttonClickMe.Name = 'buttonClickMe'
    $buttonClickMe.Size = '75, 23'
    $buttonClickMe.TabIndex = 1
    $buttonClickMe.Text = 'Check Path'
    $buttonClickMe.UseCompatibleTextRendering = $True
    $buttonClickMe.UseVisualStyleBackColor = $True
    $buttonClickMe.add_Click($buttonClickMe_Click)
    #
    # buttonOK
    #
    $buttonOK.Anchor = 'Bottom, Right'
    $buttonOK.DialogResult = 'OK'
    $buttonOK.Location = '624, 448'
    $buttonOK.Name = 'buttonOK'
    $buttonOK.Size = '75, 23'
    $buttonOK.TabIndex = 0
    $buttonOK.Text = '&OK'
    $buttonOK.UseCompatibleTextRendering = $True
    $buttonOK.UseVisualStyleBackColor = $True
    $form1.ResumeLayout()
    #endregion Generated Form Code

    #----------------------------------------------

    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    #Show the Form
    return $form1.ShowDialog()

}
Show-mainform2_psf

Power Shell - Windows Forms

PowerShell - Expirate the Program

$
0
0

Hello

I developed an application in PowerShell with windows Forms.
I would like to make a condition for the executable to expire on the date I determine.
I made this condition in another application that I developed in VB.NET, but I didn't find how to do it in power shell

in VB it looked like this:

Dim dt1 = DateTime.Now
        Dim dt2 = DateTime.Parse("30/09/2019")

        If dt1 >= dt2 Then
            MsgBox("Expired Date - Please Contact Administrator")
            Application.Exit()
       
        End If

Does anyone know how I do this in powerShell?no need to have msgbox, just want the program not to run, not open, do nothing when it arrives on the set date

Thank you very much in advance.

Convert cURL to powershell (again)

$
0
0

Sorry All,

I've checked previous posts on this kind of question to no avail.  We need to regularly upload a .csv file to a company that maintains a sign-in system for our offices (so staff list is kept current).  The company recommends using cURL but our security guy doesn't like the installation of non-Microsoft software so I'd like to convert the following to powershell:

curl -F "file=@HostsFile.csv" "https://company.com.co/v1/host/csv-upload/api-key?remove-hosts=true&send-emails=false" -H "X-Sine-Api-Key: (api key)"

Any assistance gratefully received.

Cheers

Powershell script - VPN (working from home) / Office

$
0
0

Hi, does anyone have any powershell code snippets or advice to detect whether an end users machine is connecting to the company network from an off-site location, or connected to the network within an office. eg. detecting VPN is in use (fortinet) or not. 

This code will be embedded into a powershell scripted software deployment to determine whether to run an install when the machine is in the office, or to postpone it if the machine is off site.

thanks in advance.

Key not valid for use in specified state

$
0
0

Hi Experts,

Below is the code which is running fine in PS manually in my session but when I schedule the same in SQL Agent as job it’s failing with ‘key not valid for use in specified state’ error.

# Prompting & saving credentials, delete the XML file created to reset

# Setting credential file

$SNOWCredentialsFile = "N:\CMDB\SNOWCredentials.xml"

 

# Testing if file exists

$SNOWCredentialsFileTest =  Test-Path $SNOWCredentialsFile

 

# IF doesn't exist, prompting and saving credentials

IF ($SNOWCredentialsFileTest -eq $False)

{

$SNOWCredentials = Get-Credential -Message "Enter SNOW login credentials"

$SNOWCredentials | EXPORT-CLIXML $SNOWCredentialsFile -Force

}

 

# Importing credentials

$SNOWCredentials = IMPORT-CLIXML $SNOWCredentialsFile

 

$SNOWUsername = $SNOWCredentials.UserName

$SNOWPassword = $SNOWCredentials.GetNetworkCredential().Password

 

$SNOWPassword = ConvertTo-SecureString $SNOWPassword -AsplainText -Force

 

$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($SNOWUsername, $SNOWPassword)


 

# Build auth header

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $SNOWUsername, $SNOWPassword)))

The script saving the credentials in xml file and from there we are retrieving in the above script. But the same is not working in job as it runs in service account

When I googled, I got suggestion that to use KEY/SecureKey instead of AsplainText if we need to resue irrespective of user/systems. I have tried out but failed and I am not sure where I was missing and unable to fix it.

So please help me to get the complete correct query accordingly with the following requirements

  1. Only once security team come and enter the password when it prompts for user – due to security in prod
  2. It should be encrypted and written in xml or txt file in some path
  3. And when we schedule the ps script to run via sql agent it has to pick it from there and runs without an issues

Thanks

Dave

 


Recurse does not work in Remove-Item command

$
0
0

Hi,

I try to delete Windows Update registry key and alls subkeys using powershell.

Unfortunaley the following command does not work:

Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\" -recurse -force -confirm:$false
Remove-Item : Cannot delete a subkey tree because the subkey does not exist.
At line:1 char:1
+ Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Wi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (HKEY_LOCAL_MACH...\WindowsUpdate\:String) [Remove-Item], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.RemoveItemCommand

If I use the same command without -recurse parameter, then the output wants that I should confirm it. But the command should not ask to confirm it:

Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\" -force -confirm:$false
Confirm
The item at HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\ has children and the Recurse parameter was
not specified. If you continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

How can I solve -recurse issue? 

Best regards

Birdal


Statement taking an inordinate amount of time to execute

$
0
0

I have this routine that queries the WMI system to find the location of an executable file in Windows …

	CALL	subLog( 1, "" )
CALL subLog( 1, "#################################################################################################" ) CALL subLog( 1, "fnFindExecutable(): finding '" & strFilename & "' executable.") CALL subLog( 1, "#################################################################################################" ) CALL subLog( 1, "" ) strQuery = "WinMgmts:\\" & strLocalPC & "\Root\CIMV2" CALL subLog( 5, "About to open WinMgmts, query is '" & strQuery & "'." ) SET objWMI = GetObject( strQuery ) strQuery = "SELECT * FROM CIM_DataFile WHERE fileName = '" & strFilename & "' AND Extension = 'exe'" CALL subLog( 5, "About to query WinMgmts, query is '" & strQuery & "'." ) SET colFiles = objWMI.ExecQuery( strQuery ) CALL subLog( 5, "returned from query." ) intNumFiles = colFiles.Count CALL subLog( 5, CStr( intNumFiles ) & " returned in collection." )
As you can see, I have logging statements both before and after the intNumFiles = colFiles.Count statement. when I run the script
# 10/9/2019 10:24:23 AM: #################################################################################################
# 10/9/2019 10:24:23 AM: fnFindExecutable(): finding 'WinSCP' executable.
# 10/9/2019 10:24:23 AM: #################################################################################################
# 10/9/2019 10:24:23 AM:
# 10/9/2019 10:24:23 AM: About to open WinMgmts, query is 'WinMgmts:\\HPS20778\Root\CIMV2'.
# 10/9/2019 10:24:23 AM: About to query WinMgmts, query is 'SELECT * FROM CIM_DataFile WHERE fileName = 'WinSCP' AND Extension = 'exe''.
# 10/9/2019 10:24:23 AM: returned from query.
# 10/9/2019 10:35:56 AM: 1 returned in collection.
# 10/9/2019 10:35:56 AM: strPath is 'c:\program files (x86)\winscp\winscp.exe'.
# 10/9/2019 10:35:56 AM: 'WinSCP' found at 'c:\program files (x86)\winscp\winscp.exe'.
# 10/9/2019 10:35:56 AM: End of file collection processing.
# 10/9/2019 10:35:56 AM: WinSCP found at 'c:\program files (x86)\winscp\winscp.exe'.
# 10/9/2019 10:35:56 AM:
# 10/9/2019 10:35:56 AM: #################################################################################################
# 10/9/2019 10:35:56 AM: fnFindExecutable(): finding 'AcroDist' executable.
# 10/9/2019 10:35:56 AM: #################################################################################################
# 10/9/2019 10:35:56 AM:
# 10/9/2019 10:35:56 AM: About to open WinMgmts, query is 'WinMgmts:\\HPS20778\Root\CIMV2'.
# 10/9/2019 10:35:56 AM: About to query WinMgmts, query is 'SELECT * FROM CIM_DataFile WHERE fileName = 'AcroDist' AND Extension = 'exe''.
# 10/9/2019 10:35:56 AM: returned from query.
# 10/9/2019 10:36:24 AM: 1 returned in collection.
# 10/9/2019 10:36:24 AM: strPath is 'c:\program files (x86)\adobe\acrobat 2017\acrobat\acrodist.exe'.
# 10/9/2019 10:36:24 AM: 'AcroDist' found at 'c:\program files (x86)\adobe\acrobat 2017\acrobat\acrodist.exe'.
# 10/9/2019 10:36:24 AM: End of file collection processing.
# 10/9/2019 10:36:24 AM: Distiller found at 'c:\program files (x86)\adobe\acrobat 2017\acrobat\acrodist.exe'.
As you can see from the logging, the first time that this procedure is called, that one statement takes 11 minutes to execute.    Is there a more optimal way to do this?




Disabling the "Energy-Efficient Ethernet" property using PowerShell

$
0
0

My goal is to disable two values ("Selective suspend" and "Energy-Efficient Ethernet") via PowerShell, which pertain to the Surface Ethernet Adapter.

In reference to "Selective suspend", the following command works: Disable-NetAdapterPowerManagement -SelectiveSuspend "Ethernet" -NoRestart

In reference to "Energy-Efficient Ethernet", I've searched the internet for the correlating keyword/object, to no avail.  The keyword/object "EEELinkAdvertisement" doesn't succeed with the 'Disable-NetAdapterPowerManagement' command.

I have over 750 Surface Pro's that I need to deploy these settings to.

Any feedback would be greatly appreciated.

Open program from HTA

$
0
0

Hello

Im trying to create a HTA application, that can open programs(exe, bat etc..) locally on the computer.

This will be used on a Kiosk PC, where the users don't have access to the desktop etc.

But have some problems with finding a script that works with my existing code..

Right now I'm using this script to open the programs:

<script type="text/javascript">
    function runApp(which) {
    WshShell = new ActiveXObject("WScript.Shell");
    WshShell.Run (which,1,true);
    }</script>

And this is how my links looks:

<a 
href="javascript:window.location.href=window.location.href" 
onclick="runApp('file://C:/Tools/program.exe');parent.playSound('assets/sounds/startsound.mp3');"
onmouseover="playSound('assets/sounds/hover.wav');"
unselectable="on"
style="cursor: hand; display: block;">Start Program</a>

The problem with this script, is that some of the programs I open from the launcher HTA, are placed below the HTA app that runs in fullscreen.. So the users need to ALT+TAB to switch to them.. This not is not good, since most of the users don't know what to do..

I have then been searching for another script, and found this HTA sample, which looks like a better way to do it:

<!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=9"><HTA:APPLICATION
APPLICATIONNAME="Open link with chrome browser"
BORDER="THIN"
BORDERSTYLE="NORMAL"
ICON="Explorer.exe"
INNERBORDER="NO"
MAXIMIZEBUTTON="NO"
MINIMIZEBUTTON="NO"
SCROLL="NO"
SELECTION="NO"
SINGLEINSTANCE="YES"/><META HTTP-EQUIV="MSThemeCompatible" CONTENT="YES"><title>Test HTA</title><SCRIPT LANGUAGE="VBScript">
'************************************************************************************
Option Explicit
 Function Executer(StrCmd)
 Dim ws,MyCmd,Resultat
 Set ws = CreateObject("wscript.Shell")
 MyCmd = "CMD /C " & StrCmd & " "
 Resultat = ws.run(MyCmd,0,True)
 Executer = Resultat
End Function
'************************************************************************************
Sub window_onload()
 CenterWindow 400,320
End Sub
'************************************************************************************
Sub CenterWindow(x,y)
 Dim iLeft,itop
 window.resizeTo x,y
 iLeft = window.screen.availWidth/2 - x/2
 itop = window.screen.availHeight/2 - y/2
 window.moveTo ileft,itop
End Sub
'************************************************************************************</script></head><p>Links :</p><ol><li><a href="#" onClick="Call Executer('Start C:\ScriptExe.exe')">EXE test</a></li><li><a href="#" onClick="Call Executer('Start C:\Tools\Bats\menu.bat')">Bat test</a></li><li><a href="#" onClick="Call Executer('Start chrome.exe www.google.com chrome --app=https://www.google.com/')">Chrome App Test</a></li></ol><BODY></body></html>

The problem with the script, is that I need to use:

<meta http-equiv="X-UA-Compatible" content="IE=9">

My existing code only works with IE=9 and breaks alot of things like jquery, if i dont have that tag..

And If I add the tag to the sample above, it breaks and show me this error when I run the HTA:

An error has occured in the script on this page. Line: 46 Char: 31 Error: Expected ";" Code: 0

So looks like something breaks, with this linie and char 31 is: Call Executer

<li><a href="#" onClick="Call Executer('Start C:\ScriptExe.exe')">EXE test</a></li>

I have no prior experience with hta, vbs and only a little java.. So I have been using whatever scripts I'm able to find to build this.

Can anyone tell me, why this don't work with IE=9 content tag? Or perhaps know a better way of doing this?



List all computers with remote WMI not enabled

$
0
0

Hi,

I want to check if remote WMI is enabled or not on other computers. If not, then these servers should be listed with state.

If I run following, I get all OK.

$Computers = Get-Content "C:\ComputerList.txt"

Get-WmiObject -Query "select * from win32_service where name='WinRM'" -Computer $Computers |ft -Property PSComputerName,StartMode, State, Status

PSComputerName StartMode State   Status
-------------- --------- -----   ------
MITAPO13       Auto      Running OK
MITHCHDB       Auto      Running OK
MITIXOS8       Auto      Running OK
MITSHP06       Auto      Running OK
MITSHP07       Auto      Running OK

But if the CoputerList.txt has any computer with remote WMI not enabled, I get the error

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:1 char:1
+ Get-WmiObject -Query "select * from win32_service where name='WinRM'" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

My question:

how can I get the list all computers on which the WinRM does not enabled or and/or "RPC server is unavailable"?

Best regards

Birdal

PS command to display username and group name.

$
0
0

Hello,

What is the PS command to display an AD group and its members?

For example:  the display should show username and group name.

Name:                        GroupName

User01                        Domain Admins

User02                        Domain Admins.

I used this command and it only display the name, and no group name (Get-ADGroupMember -Identity "domain admins" | select Name).

Thanks for your help.

Viewing all 15028 articles
Browse latest View live


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