Powershell

How to redirect the output of a PowerShell to a file during its execution

.\MyScript.ps1 > output.txt

Set an Environment Variable from an expression and check the result

the env is important
set

$env:giuseppe=Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/instance-id

check the content
PS C:\Users\Administrator> Get-ChildItem env:giuseppe

Name                           Value
----                           -----
giuseppe                       i-xxxx1111222233333

update the path environment variable for that shell

$env:path = "C:\Program Files\Amazon\AWSCLI\;$env:path"

which for windows

PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe

Verify if a command return a good result

> echo helloworld
> $?
True

Write from the console inside a file

Add-Content test.json "[{`"DeviceName`": `"/dev/sda1`",`"Ebs`" :{`"Encrypted`" : true,`"DeleteOnTermination`": true} } ]"

in this example i did the escape of the " charater see the microsoft link https://technet.microsoft.com/en-us/library/ee156791.aspx for all the escapes available

Check if a registry key exist or no

reg.exe query HKEY_LOCAL_MACHINE\SOFTWARE\IBM\CurrentVersion\ /s /v MyKeyName",
  • with /s it check recursive
  • with /v you specify the keyname

Script for remote desktop with default user and password

from http://stackoverflow.com/questions/11296819/run-mstsc-exe-with-specified-username-and-password

content of remotedesk.ps1

$ip=$args[0]
cmdkey /generic:TERMSRV/$ip /user:"adminuser" /pass:"secretpassword"
mstsc /v:$ip

and call in this way
.\remotedesk.ps1 192.168.10.55

PowerShell funzioni

Basic Function , how to pass the parameters
http://www.powershellpro.com/powershell-tutorial-introduction/powershell-functions-filters/

Windows PowerShell: Build a Better Function
https://technet.microsoft.com/en-us/magazine/hh360993.aspx

Determine if localhost is a domain controller

https://vernanderson.wordpress.com/2013/09/18/determine-if-localhost-is-a-domain-controller/

Join Computer to Domain With Powershell (One-Click Method)

https://community.spiceworks.com/scripts/show/1540-join-computer-to-domain-with-powershell-one-click-method

Check if an user is inside a group

http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_28424711.html

$user = "user1"

if ((Get-ADUser $User -Properties memberof).memberof -like "CN=Domain Admins*")
{
  echo $true
}
Else
{
  echo $false
}

wget on powershell

http://www.powershellatoms.com/basic/download-file-website-powershell/

$source = "http://yoursite.com/file.xml"
$destination = "c:\application\data\newdata.xml"
Invoke-WebRequest $source -OutFile $destination

from

ignore ssl not valid
http://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

Test the port , telnet is outdate

connection working

Test-NetConnection -ComputerName bsrpremngprd019.intra.corp.bosslab.com -Port 5723

ComputerName           : myhostname19.mycompany.com
RemoteAddress          : 10.25.32.1
RemotePort             : 5723
InterfaceAlias         : Ethernet
SourceAddress          : 10.225.44.11
PingSucceeded          : True
PingReplyDetails (RTT) : 1 ms
TcpTestSucceeded       : True

connection not working

Test-NetConnection -ComputerName myhostname19.mycompany.com -Port 5724
WARNING: TCP connect to myhostname19.mycompany.com:5724 failed

ComputerName           : myhostname19.mycompany.com
RemoteAddress          : 10.25.32.1
RemotePort             : 5724
InterfaceAlias         : Ethernet
SourceAddress          : 10.225.44.11
PingSucceeded          : True
PingReplyDetails (RTT) : 1 ms
TcpTestSucceeded       : False

Udemy course powershellbeginner

Power shell course for begenner on Udemy

Extract the name of the ethernet card

from http://blogs.technet.com/b/heyscriptingguy/archive/2014/01/15/using-powershell-to-find-connected-network-adapters.aspx

PS C:\Users\Administrator> get-wmiobject win32_networkadapter -filter "netconnectionstatus = 2" | select netconnectionid

netconnectionid
---------------
Ethernet0

if you want only the value of the column for example to put inside a puppet facter

PS C:\Users\Administrator> (get-wmiobject win32_networkadapter -filter "netconnectionstatus = 2" | select netconnectionid).netconnectionid
Ethernet0

tail and head in poweshell

Get-Content ".\file_test.txt" | select -Last 10
Get-Content ".\file_test.txt" | select -First 10

to complete

add to wiki powershell
http://www.computerperformance.co.uk/powershell/powershell_variables.htm


http://windowsitpro.com/windows-server/initialize-volume-using-windows-powershell
http://www.thomasmaurer.ch/2012/04/replace-diskpart-with-windows-powershell-basic-storage-cmdlets/

################
$disknum = 5
$driveletter = 'E'

Initialize-Disk -Number $disknum -PartitionStyle MBR
New-Partition -DiskNumber $disknum -AssignDriveLetter -UseMaximumSize
Format-Volume -DriveLetter $driveletter -FileSystem NTFS -Confirm:$false
###########

##### working control
if ((Get-Disk | Where-Object {$_. OperationalStatus -eq 'Offline'}) -ne $null) {
Write-Host 'there is a disk to format'
}else {
Write-Host 'nothing to format'
}

######### the parameter for the function ######
$num=(Get-Disk | Where-Object {$_. OperationalStatus -eq 'Offline'}) | select Number
$toanalyze = $null
$num | ForEach-Object {
$toanalyze = ($_).Number
#call a funtion to inizialize the disk
Write-Host $toanalyze
}
####################

##### extract the first available letter
#http://www.powershellmagazine.com/2012/01/12/find-an-unused-drive-letter/
for($j=67;gdr($d=[char]++$j)2>0){}$d

if((Get-Disk | Where-Object {$_. OperationalStatus -eq 'Offline'}) -ne $null){write-host then}else{write-host else}

DNS commands

  • list the search values using the registry command
reg.exe query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\ /s /v SearchList
  • list using the powershell
(Get-DnsClientGlobalSetting | select SuffixSearchList).SuffixSearchList
  • overwrite the search parameter, this will replace the original dhcp value
Invoke-WmiMethod -class win32_networkadapterconfiguration -name setdnssuffixsearchorder -argumentlist @("hello.com", "word.com"), $null
Salvo diversa indicazione, il contenuto di questa pagina è sotto licenza Creative Commons Attribution-ShareAlike 3.0 License