Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Convert JSON data into usable variables

$
0
0

Hello,

I am writing a Power shell script to query AWS DynamoDB and retrieve some data (uses the AWS CLI). The two pieces of data I am interested in are "foldername" and "quota" size.

I would like to place those two pieces of information into two separate variables, $folder and $quota. From there I will use those variables in a update user quota information for a Windows FSRM implementation.

Below is the script that I have so far, the problem I've got is that I don't know how to turn the JSON output which I get from the AWS CLI dynamoDB into the variables. I've made a start by conventing the JSON data into a PowerShell object, but as you can see from the script below, it's full of symbols I don't want, "@= {}". Any help would be much appreciated.

 

### Connect to DynamoDB to extract the new Quota Data

$json = aws dynamodb scan --table-name quotapending --region ap-southeast-2

### Output the results to a JSON file

$json | Out-File -FilePath F:\MyJson.json

### Set the $file variable to the output JSON file

$file ="F:\MyJson.json"

### Create a Powershell object called $Data from the JSON strings

$data = Get-content $file| out-string | ConvertFrom-Json

### Print out the contents of the new PowerShell Object

$data.Items | Format-table

 

createdate                                                 quota                                                foldername

----------                                                     -----                                                ----------

@{S=2014-04-08 03:41:32}                      @{N=100}                                      @{S=001070-112233-1236386}

@{S=2014-04-08 03:38:31}                      @{N=100}                                      @{S=1309506-1}

@{S=2014-04-08 05:01:04}                      @{N=100}                                      @{S=1309506-1}

@{S=2014-04-07 17:09:58}                      @{N=100}                                      @{S=0112233-1}

@{S=2014-04-08 03:34:20}                      @{N=200}                                     @{S=1309506-1.backup}

 

@{S=2014-04-08 05:01:04}                      @{N=100}                                      @{S=1309506-1.backup}


Oracle ODBC connection using DSN with powershell

$
0
0

 

Hi All,

I want to establish a Oracle database connection using ODBC DSN. I have written the below code but i am getting error "Data source name not found and no default driver
specified
". Let me know what needs to be modified or added to establish this connection successfully.

I have created a system DSN : test_odbc in ODBC administrator

Script:

[System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient")
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.connectionstring = "Provider=System.Data.OracleClient;(Oracle in v112030b64;DSN=test_odbc)"
$conn.open()
$sql = "select * from products"
$cmd = New-Object system.Data.Odbc.OdbcCommand($sql,$conn)
$da = New-Object system.Data.Odbc.OdbcDataAdapter($cmd)
$dt = New-Object system.Data.datatable
$null = $da.fill($dt)
$conn.close()
$dt

 

Error:  Exception calling "Open" with "0" argument(s): "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver
specified"
At line:4 char:1
+ $conn.open()
+ ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : OdbcException

Shortcut Properties

$
0
0

I found this code on this site and it works.

 

$shell = New-Object -ComObject WScript.Shell

$Location = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs"

$shortcut = $shell.CreateShortcut("$Location\clickme.lnk")

$shortcut.TargetPath = "notepad.exe"

$shortcut.IconLocation = "shell32.dll,2"

$shortcut.Save()

 

But I need to add a value for the START IN property.  I've tired

$shortcut.Start = "C:\Windows"

$shortcut.StartIn = "C:\Windows"

 

And the shortcut does get created but the START IN is left blank.

 

 

Adding PowerShell Script to Primalform

$
0
0

I am trying to add a PowerShell script into a PrimalForm GUI and seem to be having difficulty getting it work. The script allows you to update Active Directory description on multiple machines listed on a .CSV file. Below is the script I am trying to add:

 <#Update computer description
Open notepad and create a .CSV file. Add ComputerName,Description as the headers.
Below the headers type each computer name and description separated by a comma.
EXAMPLE:
ComputerName,Description
HORMEDTKWK40797,Test_Description
HORMEDTKTB47144,Test_Description
#>
Import-Csv "C:\scripts\computerdescription.csv" | % {
$computer = $_.computername
$Desc = $_.Description
set-ADComputer $computer -Description $Desc
}

Below is the Primalform GUI format. The GUI gives you three options: Update a localhost AD Description, type a computer name on the form or browse to a .CSV file. Thanks!

#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 4/6/2014 4:01 PM
# Generated By:
########################################################################

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

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$Install = New-Object System.Windows.Forms.Button
$label3 = New-Object System.Windows.Forms.Label
$Browse = New-Object System.Windows.Forms.Button
$label2 = New-Object System.Windows.Forms.Label
$txtComputername = New-Object System.Windows.Forms.TextBox
$radioButton3 = New-Object System.Windows.Forms.RadioButton
$radioButton2 = New-Object System.Windows.Forms.RadioButton
$radioButton1 = New-Object System.Windows.Forms.RadioButton
$txtDescription = New-Object System.Windows.Forms.TextBox
$label1 = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events.
$Browse_OnClick=
{
#When Browse button is clicked
$FileName = Select-FileDialog
$Computer = Get-Content $FileName
$Install.enabled = $true
}

$Install_OnClick=
{
#Update AD Description of computer
Foreach ($pc in $Computer) {
$Desc = $txtDescription
set-ADComputer $pc -Description $Desc
}
}

$handler_radioButton1_CheckedChanged=
{
#Localhost radio button
$txtComputername.enabled = $false
$Browse.enabled = $false
$Computer = $env:computername
$Install.enabled = $true

}

$handler_radioButton2_CheckedChanged=
{
#Enter Hostname radiobutton
$txtComputername.enabled = $true
$Browse.enabled = $false
}

$handler_radioButton3_CheckedChanged=
{
#Load list of computers radiobutton
$Browse.enabled = $true
$txtComputername.enabled = $false

}

$handler_textBox1_TextChanged=
{
#Hostname textbox
$Computer = $txtComputername.Text.ToString()
$Install.enabled = $true


}
$OnLoadForm_StateCorrection={
#Correct the initial state of the form to prevent the .Net maximized form issue
 $form1.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 288
$System_Drawing_Size.Width = 517
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "Computer Description"


$Install.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 333
$System_Drawing_Point.Y = 207
$Install.Location = $System_Drawing_Point
$Install.Name = "Install"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 93
$Install.Size = $System_Drawing_Size
$Install.TabIndex = 9
$Install.Text = "Install"
$Install.UseVisualStyleBackColor = $True
$Install.add_Click($Install_OnClick)

$form1.Controls.Add($Install)

$label3.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 116
$System_Drawing_Point.Y = 208
$label3.Location = $System_Drawing_Point
$label3.Name = "label3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label3.Size = $System_Drawing_Size
$label3.TabIndex = 8
$label3.Text = "Load Computer List"
$label3.TextAlign = 16

$form1.Controls.Add($label3)


$Browse.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 208
$Browse.Location = $System_Drawing_Point
$Browse.Name = "Browse"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 93
$Browse.Size = $System_Drawing_Size
$Browse.TabIndex = 2
$Browse.Text = "Browse"
$Browse.UseVisualStyleBackColor = $True
$Browse.add_Click($Browse_OnClick)

$form1.Controls.Add($Browse)

$label2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 230
$System_Drawing_Point.Y = 156
$label2.Location = $System_Drawing_Point
$label2.Name = "label2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 100
$label2.Size = $System_Drawing_Size
$label2.TabIndex = 6
$label2.Text = "Enter Hostname"
$label2.TextAlign = 16
$label2.add_Click($handler_label2_Click)

$form1.Controls.Add($label2)

$txtComputername.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 159
$txtComputername.Location = $System_Drawing_Point
$txtComputername.Name = "txtComputername"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 188
$txtComputername.Size = $System_Drawing_Size
$txtComputername.TabIndex = 5
$txtComputername.add_Leave($handler_txtComputername_TextChanged)

$form1.Controls.Add($txtComputername)


$radioButton3.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 271
$System_Drawing_Point.Y = 97
$radioButton3.Location = $System_Drawing_Point
$radioButton3.Name = "radioButton3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 41
$System_Drawing_Size.Width = 104
$radioButton3.Size = $System_Drawing_Size
$radioButton3.TabIndex = 4
$radioButton3.TabStop = $True
$radioButton3.Text = "Load List of Computers"
$radioButton3.UseVisualStyleBackColor = $True
$radioButton3.add_CheckedChanged($handler_radioButton3_CheckedChanged)

$form1.Controls.Add($radioButton3)


$radioButton2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 167
$System_Drawing_Point.Y = 98
$radioButton2.Location = $System_Drawing_Point
$radioButton2.Name = "radioButton2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 40
$System_Drawing_Size.Width = 75
$radioButton2.Size = $System_Drawing_Size
$radioButton2.TabIndex = 3
$radioButton2.TabStop = $True
$radioButton2.Text = "Enter Hostname"
$radioButton2.UseVisualStyleBackColor = $True
$radioButton2.add_CheckedChanged($handler_radioButton2_CheckedChanged)

$form1.Controls.Add($radioButton2)


$radioButton1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 106
$radioButton1.Location = $System_Drawing_Point
$radioButton1.Name = "radioButton1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 24
$System_Drawing_Size.Width = 104
$radioButton1.Size = $System_Drawing_Size
$radioButton1.TabIndex = 2
$radioButton1.TabStop = $True
$radioButton1.Text = "LocalHost"
$radioButton1.UseVisualStyleBackColor = $True
$radioButton1.add_CheckedChanged($handler_radioButton1_CheckedChanged)

$form1.Controls.Add($radioButton1)

$txtDescription.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 51
$txtDescription.Location = $System_Drawing_Point
$txtDescription.Name = "txtDescription"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 473
$txtDescription.Size = $System_Drawing_Size
$txtDescription.TabIndex = 1

$form1.Controls.Add($txtDescription)

$label1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 24
$label1.Location = $System_Drawing_Point
$label1.Name = "label1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 470
$label1.Size = $System_Drawing_Size
$label1.TabIndex = 0
$label1.Text = "Enter Description"

$form1.Controls.Add($label1)

#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($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

 

#Select File Explorer Function
function Select-FileDialog {

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ofd = New-Object System.Windows.Forms.OpenFileDialog
$ofd.InitialDirectory = "c:\Description"
$ofd.ShowHelp=$true
if($ofd.ShowDialog() -eq "OK") { $ofd.FileName }

}

#Call the Function
GenerateForm

 

 

 

show pop up message during script running

$
0
0

Is possible to show pop up message during script running without buttons?

For example:

1. scheduler run script
2. current logged user get pop up information: "backup in progress do not turn off your computer..."
3. User can't close window, no buttons ok / no / cancel, user only can minimize pop up window
4. when the scripthas finishedclose thewindowautomatically.

HOSTS update

$
0
0

I want to share this code to update the HOSTS file with a windows task at regular times.

Note.- Hosts addresses can change or need password in the future, so take care. This code needs a help file cabeza.txt or a string with similar code and the corresponding modification

Text for cabeza.txt at the end of code. Text and comments in Spanish Language but you can googeling translate.

Code

"

 

# Script para Automatizar la actualización del archivo HOSTS de Windows por medio de una tarea y

# fusionando los tres archivos de las direcciones siguientes:

 

# http://www.malwaredomainlist.com/hostslist/hosts.txt

# http://someonewhocares.org/hosts/zero/hosts"

# http://www.winhelp2002.mvps.org/hosts.txt

 

#Inicio

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

 

 

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

 

# Comprobamos que el archivo HOSTS existe en el directorio de windows

 

$path = "c:\windows\system32\drivers\etc\HOSTS"

 

# Si no existe, creamos uno de la nada y si existe seguimos el programa

 

If(-not(Test-Path -path $path))

  {

   $h="127.0.0.1 localhost"

    New-Item -Path $path -ItemType file -Value $h -force

 

  }

Else

 { 

 }

 

# Ahora comprobamos si existe el hosts.bak y si no hay hacemos uno

# Podiamos si existe el HOSTS hacer un .bak del HOSTS pero hacemos este de fortuna

# porque después el programa ya pone los valores verdaderos.

 

$path = "c:\windows\system32\drivers\etc\hosts.bak"

 

If(-not(Test-Path -path $path))

  {

   $h="127.0.0.1 localhost"

    New-Item -Path $path -ItemType file -Value $h -force

  }

Else

 { 

 }

# como queremos que tambien en la carpeta auxiliar estén los dos, tanto el HOSTS como el hosts.bak

# miramos si existen y si no existen copiamos los archivos del directorio de windows y los ponemos en este

 

$path = "c:\HOSTSUPDATE\HOSTS"

 

# Si no existe, copiamos el de windows y si existe seguimos el programa

 

If(-not(Test-Path -path $path))

  {

   Copy-Item c:\windows\system32\drivers\etc\HOSTS C:\HOSTSUPDATE

 

  }

Else

 { 

 }

 

$path = "C:\HOSTSUPDATE\hosts.bak"

 

# Si no existe, copiamos el de windows y si existe seguimos el programa

 

If(-not(Test-Path -path $path))

  {

   Copy-Item c:\windows\system32\drivers\etc\hosts.bak C:\HOSTSUPDATE

 

  }

Else

 { 

 }

 

cd C:\HOSTSUPDATE

 

#Si no hay backup de hosts actual, hacer uno

 

$MirarSiHostsbak = "c:\HOSTSUPDATE\hosts.bak"

$FileExists = (Test-Path $MirarSiHostsbak -PathType Leaf)

 

 

# Comprobamos que el Hosts es el del dia porque hayamos encendido el ordenador mas de una vez

# ya que el Hosts se genera nada mas encender el ordenador. Para ello cogemos la fecha que 

# hay en el HOSTS actual. Si el ordenador permanece encendido mas de un dia entonces la tarea

# ha de programarse para una hora concreta en que sepamos que va a estar encendido.

 

$fileNames = "C:\HOSTSUPDATE\HOSTS"

$fecha=Get-Date -format "dd-MM-yyyy"

 

# Ahora cogemos la fecha de hoy del ordenador

 

$result = Get-Content $fileNames | Select-String $fecha -quiet -casesensitive 

 

 # Comparamos ambas fechas para ver si son iguales

 

      If ($result -eq $fecha)  

      { 

        # Si las fechas coinciden,SALIR sin hacer nada. Ya existe el archivo con esa fecha

        # El programa sale aquí y no realiza ninguna operación

 

      } 

Else{   # En caso contrario, realizar todo el proceso. Primero descargamos los archivos al ordenador 

 

 

 

#Descargar el hosts de 'malwaredomainlist.com' a la carpeta HOSTSUPDATE

#una manera de hacerlo es con Invoke y la otra con Start. Start es más rápido

$error.clear()

$fileURL = "http://www.malwaredomainlist.com/hostslist/hosts.txt"

$destination = "C:\HOSTSUPDATE\file1.log"

#Invoke-WebRequest $fileURL -OutFile $destination

Start-BitsTransfer $fileURL $destination

 

#Descargar el hosts de 'someonewhocares.org' a la carpeta HOSTSUPDATE

#otra manera de hacerlo pero puede que sea mas lento porque es linea a linea

$error.clear()

#$urls = "http://someonewhocares.org/hosts/zero/hosts"

#$fileNames = "C:\HOSTSUPDATE\file2.log"

#$webclients = New-Object System.Net.WebClient

#$webclients.DownloadFile($urls,$fileNames)

 

#nos quedamos con esta

$urls = "http://someonewhocares.org/hosts/zero/hosts"

$fileNames = "C:\HOSTSUPDATE\file2.log"

#Invoke-WebRequest $urls -OutFile $filenames

Start-BitsTransfer $urls $filenames

 

 

# Fusionar los dos archivos en el primero

$error.clear()

$file2 = Get-Content "file2.log"

Add-Content "file1.log" $file2

 

# obtenemos el día de hoy y si es un 7 ,14,21 o un 28 entonces descargamos

# el hosts de 'www.winhelp2002.mvps.org'

 

$data=$a = (Get-Date).Day

if ($data -eq 7 -or $data -eq 14 -or $data -eq 21 -or $data -eq 28) {

#Descargar el hosts de MVPS to HOSTSUPDATE folder

$error.clear()

$fileURL = "http://www.winhelp2002.mvps.org/hosts.txt"

$fileName = "C:\HOSTSUPDATE\file3.log"

#$webclient = New-Object System.Net.WebClient

#$webclient.DownloadFile($fileURL,$fileName)

#Invoke-WebRequest $fileURL -OutFile $filename

Start-BitsTransfer $fileURL $filename

 

# Fusionar el file1.log con el de MVPS

$error.clear()

$file3 = Get-Content "file1.log"

Add-Content "file3.log" $file3

}

else {   # en caso de que no sea dia 7 ,14,21 o 28 seguir con la operacion sin bajar el MVPS Hosts

$error.clear()

$file3 = Get-Content "file1.log"

Add-Content "file3.log" $file3

}

 

#Eliminar las lineas de comentarios para poder añadir las mias propias con el archivo cabeza.txt

New-Item -ItemType file "file4.log" -force

Select-String '#' .\file3.log -notmatch | % {$_.Line} | set-content file4.log

 

#Reemplazar un string 127.0.0.1 por 0.0.0.0

$new = (Get-Content "file4.log") -replace "127.0.0.1", "0.0.0.0"

Set-Content file4.log $new

 

#Reemplazar un string 0.0.0.0 por 255.255.255.0

$new = (Get-Content "file4.log") -replace "0.0.0.0", "255.255.255.0"

Set-Content file4.log $new

 

#elimina las líneas que contienen localhost,local y broadcasthost porque todos los ficheros las repiten

# y así ponemos solo las que vienen en el archivo cabeza.txt

 

New-Item -ItemType file "file6.log" -force

Select-string -path .\file4.log -pattern localhost, local,broadcasthost -notmatch | % {$_.Line} | set-content file6.log

 

# convertir dos espacios o mas en solo uno, para poder ordenar bien ya que algun hosts tiene dos espacios

# entre el 255.255.255.0 y el hostsname

 

$new2 = (Get-Content "C:\HOSTSUPDATE\file6.log") -replace '\s+', ' ' 

 Set-Content "C:\HOSTSUPDATE\file6.log" $new2

 

# Aqui ordenamos las lineas de menor a mayor por numeros y letras a la vez que elimina duplicados

 

New-Item -ItemType file "HOSTS1" -force

$ins1 = Get-Content "file6.log"

$ins2 = $ins1  | sort -Unique 

Add-Content "C:\HOSTSUPDATE\HOSTS1" $ins2

 

 

#Fusiona el archivo cabeza.txt (que es la cabecera) con el HOSTS1

$error.clear()

New-Item -ItemType file "HOSTS2.log" -force

$HOSTS2 = Get-Content "C:\HOSTSUPDATE\cabeza.txt"

$HOSTS3 = Get-Content "C:\HOSTSUPDATE\HOSTS1"

 

 

Add-Content "C:\HOSTSUPDATE\HOSTS2.log" $HOSTS2

Add-Content "C:\HOSTSUPDATE\HOSTS2.log" $HOSTS3

 

#Cambiar la fecha1 de cabeza a la fecha de recogida de datos. Es decir la fecha actual cuando

# se inicia el ordenador por primera vez en el día o si no se inicia porque ha estado encendido

# todo el tiempo

 

$fecha=Get-Date -format "dd-MM-yyyy"

$fecha2=Get-Date

$fecha2=[DateTime]::Parse($fecha2)

$filelist = Get-ChildItem "C:\HOSTSUPDATE\HOSTS2.log"

foreach ($file in $filelist){

    $new = (Get-Content $file.fullname) -replace "fecha1", $fecha

    Set-Content $file.fullname $new

    $new2 = (Get-Content $file.fullname) -replace "fecha2", $fecha2

 Set-Content $file.fullname $new2

}

# Aqui ya construimos el HOSTS renombrando el HOSTS2. log y eliminamos los archivos auxiliares.

 

if (!($error[0])) {

 

        if(!($FileExists)) {

 

 

 

                Remove-Item c:\HOSTSUPDATE\HOSTS

                Rename-Item C:\HOSTSUPDATE\HOSTS2.log HOSTS

               Remove-Item C:\HOSTSUPDATE\file1.log

                Remove-Item C:\HOSTSUPDATE\file2.log

                Remove-Item C:\HOSTSUPDATE\file3.log

               Remove-Item C:\HOSTSUPDATE\file4.log

 

               Remove-Item C:\HOSTSUPDATE\file6.log

 

                Remove-Item C:\HOSTSUPDATE\HOSTS1

 

 

 

        }

        else {

 

                Remove-Item C:\HOSTSUPDATE\hosts.bak 

                Rename-Item C:\HOSTSUPDATE\HOSTS hosts.bak

                Rename-Item C:\HOSTSUPDATE\HOSTS2.log HOSTS

                Remove-Item C:\HOSTSUPDATE\file1.log

                Remove-Item C:\HOSTSUPDATE\file2.log

               Remove-Item C:\HOSTSUPDATE\file3.log

                Remove-Item C:\HOSTSUPDATE\file4.log

 

                Remove-Item C:\HOSTSUPDATE\file6.log

 

                Remove-Item C:\HOSTSUPDATE\HOSTS1

 

 

 

        }

# Aqui borramos los archivos antiguos y copiamos los nuevos de la carpeta auxiliar a la de Windows

 

Set-ItemProperty C:\Windows\System32\Drivers\etc\hosts.bak -name IsReadOnly -value $false

Set-ItemProperty C:\Windows\System32\Drivers\etc\HOSTS -name IsReadOnly -value $false

Remove-Item C:\Windows\System32\Drivers\etc\hosts.bak  #esto funciona

Rename-Item C:\Windows\System32\Drivers\etc\HOSTS hosts.bak

#hasta aquí funciona. Ahora tenemos que poner el HOST de AdZHost en Windows

Copy-Item -Path C:\HOSTSUPDATE\HOSTS -Destination C:\Windows\System32\Drivers\etc\HOSTS

Set-ItemProperty C:\Windows\System32\Drivers\etc\HOSTS -name IsReadOnly -value $true

Set-ItemProperty C:\Windows\System32\Drivers\etc\hosts.bak -name IsReadOnly -value $true

}

else {

#$error[0]

}

 

# Aqui enviamos los emails cuando corresponda. En el caso de uno solo, lo hacemos todos los días

# En el caso de envio a varios lo hacemos cada 7 dias.

 

#Esto es para uno solo

 

#$EmailTo = "a friend@orange.es"

#$EmailFrom = "myemail@gmail.com"

#$Subject = "Archivo HOSTS" 

#$Body = "Hay que ponerlo en C:\windows\system32\Drivers\etc y substituir el que hay.Cada semana recibirás la actualización" 

#$SMTPServer = "smtp.gmail.com" 

#$filenameAndPath = "C:\HOSTSUPDATE\HOSTS"

#$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)

#$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)

#$SMTPMessage.Attachments.Add($attachment)

#$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 

#$SMTPClient.EnableSsl = $true 

#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("miemail", "miclave"); 

#$SMTPClient.Send($SMTPMessage)

 

#esto es para varios

 

$date=$a = (Get-Date).Day

if ($date -eq 7 -or $date -eq 14 -or $date -eq 21 -or $date -eq 28) {

 

 

 

 

$recipients="a friend@hotmail.com" , "anotherfriend@hotmail.com" , "my@orange.es"

 

 

$filenameAndPath = "C:\HOSTSUPDATE\HOSTS"

 

$storage = "C:\HOSTSUPDATE\tdata.txt"

$secureString = Get-Content -Path $storage | ConvertTo-SecureString

 

$ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($secureString)

$pasw = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr) 

 

 

$secpasswd = ConvertTo-SecureString $pasw -AsPlainText -Force

$mycreds = New-Object System.Management.Automation.PSCredential ("myemail", $secpasswd)

 

Send-MailMessage -from myemail@gmail.com -To $recipients -Subject "Archivo HOSTS" -Body  "Hay que ponerlo en C:\windows\system32\Drivers\etc y substituir el que hay.Cada semana recibirás la actualización" -SMTPServer "smtp.gmail.com" -Attachments $filenameAndPath -Credential $mycreds -Usessl

 

 

 

}

else {

}

 

}  # para cerrar el else de comprobación de fecha

 

# Puesto aquí para no olvidar, la rutina de como se genera el

#archivo tdata.txt que almacena la clave codificada del email

#figura en el archivo storecredential.ps1

#$storage = "C:\HOSTSUPDATE\tdata.txt"

#$mysecret = 'miclavedelemail'

 

#$mysecret | 

#  ConvertTo-SecureString -AsPlainText -Force |

#  ConvertFrom-SecureString |

#  Out-File -FilePath $storage

 

------------------------

cabeza.txt

"

# Este Archivo HOSTS es el resultado de la fusion de los tres archivos

# descargados de las paginas siguientes:

 

# http://someonewhocares.org/hosts/zero/

# http://www.malwaredomainlist.com/hostslist/hosts.txt

# http://www.winhelp2002.mvps.org/hosts.txt

 

# Los dos primeros se actualizan casi cada dia. El tercero lo hace con mucho

# mas espacio de tiempo. Lo he puesto aqui por su popularidad y lo buscamos

# solo los dias 7 ,14,21 y 28 de cada mes. 

 

# Este archivo no redirige a 127.0.0.1 ni a 0.0.0.0 si no a 255.255.255.0. Ver Wikipedia española para entenderlo.

# Actualización automática programada todos los días a las 12:00 horas

 

# Nota.- No hay acentos en las palabras porque las escribe mal.

 

# Por Emilio Mari en Fecha:fecha1

# Fecha Larga: fecha2

#<localhost>

127.0.0.1 localhost  loopback

::1 localhost    #[IPv6]

#</localhost>

 

#Llamadas cortas

192.168.1.1    livebox  # entrada al modem livebox para trabajar en el

193.41.234.22  ing      # www.ingdirect.es

#Final llamadas Cortas

 

#Inicio de paginas bloqueadas

"

No "" but the code inside

 

Restart server & then email

$
0
0

I am trying to write a script to restart a server and then email when the restart is done.

I started with this basic command:  Restart-Computer -ComputerName <string[ ]>,

But I can't get it into a script and I need it as a scheduled task, and then the email when the server is back up?

 

 

returning and referencing remote powershell variable results

$
0
0

Hi,  I'm very new to powershell so looking some assistance.  I am trying to run remote powershell script to check health of or VDI enviroment using Citrix Commandlets.  (I am implementing the script on Microsoft orchestrator .Net Activity).  So I have the following code:
#2012 VDI Desktop check

$vdims = "MyCitrixPowershellSDKServer"
function vdidesktopcheck
{

                asnp Citrix*
                $result = Get-BrokerDesktop -InMaintenanceMode $True -DesktopGroupName Unidesk
 $result
}


$output = invoke-command -computer $vdims -scriptblock ${function:vdidesktopcheck}
$machinename = $output.machinename
$machinename
$state = $output.RegistrationState
$state

So when I use orchestrator to expose the variables $machinename, $state - I get the 'last' result from the involked Get-BrokerDesktop query.  However Get-Brokerdesktop query may have multiple machines returned so I am hoping to be able to reference each of the machines that match the query output.  Thats the basic requirement - what I am hoping to be able to do is further refine the basic Get-BrokerDesktop query to be able to count the number on machines output to say > 3 (ie more than 3 machines in MaintMode is unacceptable) and also check that the MachineName property is not equal to a particular value, ie the 3 test machine names in the environment which may be expected to be in MaintenanceMode.

Hope this makes sense, if not I'll try and elaborate.  Any help much appreciated!!


how to copy new and updated files to more than one location

$
0
0

My case is as below

 

I had

 SourceFoler  = d:\temp\SourceFolder

TargetFoler = d:\temp\TargetFolder

OtherFolder = d:\DiffernceFolder

 

I want to copy new and updated files from source folder to target folder

AND

Capture ONLY these updated and new files and copy them to "Other folder"

 

 How I can do that in powrshell?

thanks in advance

Pass variable into Invoke-Command for remote execution

$
0
0

I am trying to copy a file on a remote computer by executing a script on my local computer.  The -Path and -Destination  need to be variables.

This work:

Invoke-Command -ComputerName $server -ScriptBlock{
   $fromPath = "C:\MyFolder\MyFile.dat"
   $toPath = $fromPath.Replace("MyFolder", "YourFolder")
   Copy-Item -Path $fromPath -Destination $toPath

}

This does not:
$fromPath = "C:\MyFolder\MyFile.dat"
$toPath = $fromPath.Replace("MyFolder", "YourFolder")
Invoke-Command -ComputerName $server -ScriptBlock{
    Copy-Item -Path $fromPath -Destination $toPath
}
The error:  Cannot bind argument to parameter 'Path' because it is null.
is returned.
This makes sense to me, because i guess the variable needs to be assigned inside of the -ScriptBlock?
However, what I need is to be able to assign the variable outside of the script block - i.e., before the "Invoke-Command" is issued, like in the first example.
Is this possible?
Thanks

Split Lines in a variable and compare function

$
0
0

I have a variable called $a which has multiple lines as follows:

 

Source

------

saturday:activity1

saturday:activity2

saturday:activity3

 

 

i have another variables called $b which also has multiple lines as follows

 

Files

------

[string1] text and strings

[string2] text and strings

[string3] text and strings

[string4] text and strings

 

I need a function that only takes what is in the [ ] from each line in $b, something like this:

 

Split(']')[0].TrimStart('[') # this needs to apply to each line in $b

 

and compares that to every activity in $ (which comes after the colon in each line in $a)

 

so all lines in $a need to be split, something like this: $_.Split(':') #applies to each line in $a

 

if there is at least one match across all lines, i want the outcome to say "yes", if there was no match at all, the outcome to be "No",

 

Please note that the word Saturday does exist in each line in $a.

 

cant get expected output.. any suggestions?

$
0
0
$computers=get-content"C:\scripts\class-lists\Test-Lab-Computers.txt"
foreach ($computerin$computers){
invoke-command-computer$pc-scriptblock {get-item c:\drc882c.log |
format-table-property @{ label="computername"; expression={$computer}}, name, length -autosize
}
}

I have a list of computers with about 30 computers in it. im trying to query each computer ,
and provide output that finds a file on each of those computers and returns the file name
and size and the computer it came from. I cant seem to get the "computername" field to
populate.. its blank.
been trying numerous ways and cant seem to get it the way I want... any suggestions?

Powershell PSObjects does not save data in excel sheet.

$
0
0

Hi,

I am trying to save Powershell script with PSObjects to capture Registry data which is not able to save in excel sheet.

Earlier i have captured registry data using Microsoft.Win32.RegistryKey, & was able to capture it in excel sheet, but not with PSObjects this time.

Here is my code:

$date = Get-Date
$ComputerName = "localhost"
$a = New-Object -comobject Excel.Application
$a.visible = $True

$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)

$c.Cells.Item(1,1) = "Type"
$c.Cells.Item(1,2) = "Name"
$c.Cells.Item(1,3) = "PathFind"
$c.Cells.Item(1,4) = "Value"

$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True

function Get-InstalledAppReg ([string]$ComputerName)
{
$Path3 = "HKLM:\SOFTWARE\Microsoft\Internet Explorer"

$Keys = get-ChildItem -path $path3 -recurse
forEach($Key in $Keys)
{
    $i = 2
    forEach ($Value in $Key.GetValueNames())
    {
        New-Object PSObject -Property @{
       
        $c.Cells.Item($i,1) = $Key.GetValueKind($Value)
        $c.Cells.Item($i,2) = $Value
        $c.Cells.Item($i,3) = $Key.Name
        $c.Cells.Item($i,4) = $Key.GetValue($Value)
       
       
       
        }
        $i ++
    }
   
}

}
Get-InstalledAppReg ([string]$ComputerName)
$d.EntireColumn.AutoFit()
$a.Application.Displayalerts = $false


$b.SaveAs("c:\$date.xlsx")

 

here the script runs showing up the data in console, but does not save in excel sheet.

Any help is appreciated.

I am reachable at getarindam@gmail.com

 

Thanks

Arindam

Error: "Input string was not in a correct format."

$
0
0

I get this message when running my script, please could you advise how i can overcome the issue so that i should be able to quit the game at any point?

Cannot convert value "Q" to type "System.Int32". Error: "Input string was not in a correct format."

At C:\Users\F\Documents\Scripts\PowerShell\Test.ps1:58 char:7

+                         $guess = Read-Host " Enter a number between 1 and 1000 or Press Q to quit  ...

+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException

    + FullyQualifiedErrorId : RuntimeException

 

My Script is here

--------------------------------------------------------------------------------------------------------------------

# *************************************************************************

#

# Script Name: GuessMyNumber.ps1 (The Guess My Number Game)

# Version: 1.0

# Author: Captedgar

# Date: October 10, 2008

#

# Description: This PowerShell script challenges the player to attempt to guess a randomly generated number in the range of 1 to 100 in as few guesses as possible.

#

# *************************************************************************

 

Clear-Host

$number = 0 # Keeps track of the game's secret number

$noOfGuesses = 0 # Keeps track of the number of guesses made

$noOfLowGuesses = 0 # Keeps track of the number of Low guesses made

$noOfHighGuesses = 0 # Keeps track of the number of High guesses made

$playGame = "Yes" # Controls when to quit the game

$playGamesNumber = 1# Keeps track of number of games played

$randomNo = New-Object System.Random # This variable stores a random object

$status = "Play" # Controls the current round of play

$guess = "" # Stores the player's guess

$reply = "" # Stores the player's response when asked to play again

 

Write-Host "`n`n`n`n`t W E L C O M E T O T H E G U E S S M Y"

Write-Host "`n`n`n`t`t`tN U M B E R G A M E"

Write-Host "`n`n`n`t`t`tBy Capt Edgar"

Write-Host "`n`n`n`n`n`n`n`n`n`n Press Enter to continue."

 

Read-Host

 

Clear-Host

 

Write-Host "This game is to guess a number which is randomly generated by the Computer."

Write-Host "This number would be between 1 to 100."

Write-Host "Please Choose a number to guess. The Computer would then tell you whether"

Write-Host "your number is greater or lesser than the randomly generated number."

Write-Host "The Game terminates when you have guessed the correct number at which you"

Write-Host "would be presented by the correct number and the amount of guesses you have"

Write-Host "taken. Just before closing the game, you are presented with an option to play"

Write-Host "the game again. If you choose No then the game fully terminates"

Write-Host "`n`n`n"

 

Read-Host "Press continue"

 

Clear-Host

 

while ($playGame -ne "No") 

{

[int]$number = $randomNo.Next(1,101)

Write-Host $number

Clear-Host

while ($status -ne "Stop") 

{

while ($guess -eq "") 

{

Clear-Host 

Write-Host

$guess = Read-Host " Enter a number between 1 and 1000 or Press Q to quit the game"

}

if([str]$guess = [str]"Q")

{

$status = "Stop"

$playGame = "No"

}

$noOfGuesses++

if ([int]$guess -lt $number) 

Clear-Host 

Write-Host "`n Sorry. Your guess was too low. Press Enter to guess again."

$guess = "" 

$noOfLowGuesses++

Read-Host 

}

else{

     if ([int]$guess -gt $number) 

   { 

Clear-Host 

Write-Host "`n Sorry. Your guess was too high. Press Enter to guess again."

$guess = "" 

$noOfHighGuesses++

Read-Host 

  }

      else 

    { 

    Clear-Host 

   Write-Host "`n Congratulations. You guessed my number! Press Enter to continue."

   $status = "Stop" 

  Read-Host 

    }

        }

}

if([str]$guess = [str]"Q")

{

Clear-Host

Write-Host "`n Game Statistics"

Write-Host " -----------------------------------------------------------"

Write-Host "`n The secret number was: $number."

Write-Host "`n You guessed it in $noOfGuesses guesses.`n"

Write-Host "`n You have played this game" $playGamesNumber "times.`n"

Write-Host "`n Number of Low Guesses was " $noOfLowGuesses "times.`n"

Write-Host "`n Number of High Guesses was " $noOfHighGuesses "times.`n"

Write-Host " -----------------------------------------------------------"

Write-Host "`n`n`n`n`n`n`n`n`n`n`n`n`n`n Press Enter to continue."

 

Read-Host

Clear-Host

$reply = "" 

while ($reply -eq "") 

{

Clear-Host 

Write-Host

$reply = Read-Host " Would you like to play again? (Y/N) "

if (($reply -ne "Y") -and ($reply -ne "N")) 

{

$reply = "" 

}

}

if ($reply -eq "Y") 

{

$number = 0

$noOfGuesses = 0

$status = "Play"

$playGamesNumber++

$noOfLowGuesses = 0

$noOfHighGuesses = 0

$guess = 0

}

else 

$playGame = "No" 

}

}

}

Clear-Host

--------------------------------------------------------------------------------------------------------------------

 

 

 

 

Make `n to create a new line for redirected output

$
0
0

Hello

I have a string as below:

$String = "Test1`nTest2"

While printing to screen, I have 2 lines. But on redirection I get one line.

Code: $String >> Log.log

Output for Log.log: Test1Test2

How can I make`n to create a new line for logging mechanism. I tried to use Replace function  for 'n and [Environment]::NewLine but I didn't run it.

 


XML Code

$
0
0

So I downloaded the Powertips Monthly Vol 11, I wanted to try  the weather retrieval

$weather = New-WebServiceProxy -Uri http://www.webservicex.net/globalweather.asmx?WSDL

$data = $weather.GetCitiesByCountry('United States')

I Get

Exception calling "GetCitiesByCountry" with "1" argument(s): "The request failed with HTTP status 417: Expectation

Failed."

At line:1 char:1

+ $data = $weather.GetCitiesByCountry('United Kingdom')

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : WebException

 

 

I get this error in an elevated powershelll session also.

 

How do I fix this 

 

Invoke-RestMethod to upload a csv file with no contentType

$
0
0

Dealing with a special webservice I must upload a csv file.

The JavaScript code to do this using jQuery is:

var data = new FormData();

data.append('file', document.getElementById('file').files[0]);

 

$.ajax({

    url: 'https://xx',

    method: 'POST',

    data: data,

    contentType: false, 

    processData: false

});

I would like to do that with powershell:

$A = Invoke-RestMethod -Method Post -Uri $uri -InFile $filename

Doing this I get a Server error 500 back that this is not a multipart request

If I look into the jQuery documentation I find that contentType: false mean sending no contenttype at all.

How can I archive that with the invoke-restmethod?

I have tried it with -contentType "", but this doesn't work.

Any idea? 

 

Getting date and comparing

$
0
0

I want to compare the present date with the one in a file

$fecha1=Get-Date -format "dd/MM/yyyy"
$fecha2=((Get-Item C:\HOSTSUPDATE\HOSTS).LastWriteTime).Tostring().substring(0,10)

if $fecha1 -eq $fecha2) {

}

Is there a better way of doing things?

help with running batch file on remote computer

$
0
0

Hello guys,

i have the local computer called comp1 and the remote computer name comp2

i have a batch file on the local computer and i want to run it on the remote computer, I did in both of the computers: enable-psrremoting -force and when i used the invoke-command -computername comp2 { childlt c:\ } i saw all folders in comp2 c:

how do i run the batch file on the remote computer?  i dont need to get any information back from the remote computer to the local just want the batch file to run on the remote...

 

thanks for the help!

Get subset of data

$
0
0

If I run this command

get-wmiobject -class Win32_ComputerSystem 

 

I get this information.

Domain              : company.org

Manufacturer        : Dell Inc.

Model               : OptiPlex 7010

Name                : MG10011001

PrimaryOwnerName    : MyUserID

TotalPhysicalMemory : 4173807616

 

how do I get Just Manufacturer, Model and Name?    

 

Viewing all 10624 articles
Browse latest View live