Search This Blog

Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

PowerShell: create directories recursively

New-Item -Path “C:\AAA\BBB\CCC” -Type Directory -Force
similar to mkdir -p on Linux/Mac OS.

PowerShell: write text to file

Out-File -FilePath .\text.txt -InputObject 'Hello' -Encoding utf8



see also

PowerShell: single quote vs. double quote

  • Single quotes:
    $i = 5
    'The value of $i is $i.'
    
    Output:
    The value of $i is $i.
    
  • Double quotes:
    $i = 5
    "The value of $i is $i."
    
    Output:
    The value of 5 is 5.
    

Powershell: compare two directories including their descendants

  • create catalog for the source directory:
    New-FileCatalog -Path source -CatalogFilePath source.cat -CatalogVersion 2.0
    
  • test the destination directory against the source catalog:
    Test-FileCatalog -Path destination -CatalogFilePath source.cat
    


Both New-FileCatalog and Test-FileCatalog cmdlets only work in PowerShell 5.1 and later, if you are on Windows 7 or 8.1, follow the link to upgrade your PowerShell.

see also

PowerShell: execute a .msi installer

$MSI=AppInst.msi
$LOG=AppInst.log
$MSIArguments = @(
    "/i"
    $MSI
    "/qn"
    "/norestart"
    "/L*v"
    $LOG
)

Start-Process "msiexec.exe" -ArgumentList $MSIArguments -Wait -NoNewWindow



see also

PowerShell: show pop up dialog

Add-Type -AssemblyName PresentationCore,PresentationFramework
$ButtonType = [System.Windows.MessageBoxButton]::YesNo
$MessageIcon = [System.Windows.MessageBoxImage]::Question
$MessageBody = "Are you sure you want to proceed?"
$MessageTitle = "Confirm"

$Result = [System.Windows.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)

Write-Host "Your choice is $Result"

ByPass PowerShell execution policy

powershell -ExecutionPolicy ByPass ...


powershell -NoProfile ...



see also

powershell oneliner

Powershell statements can be separated with semicolons:
[xml]$doc = Get-Content "C:\1.xml"; $te = $doc.DocumentElement.SelectSingleNode("token"); if (-not $te) { Write-Host "token element not found" }


To execute a script block using powershell command:
powershell -NoProfile -Command "[xml]$doc = Get-Content C:\1.xml; $te = $doc.DocumentElement.SelectSingleNode(\"token\"); if (-not $te) { Write-Host "token element not found") }"

processing XML using powershell

# load XML document from file
$xmlfile = "C:\Users\user1\Documents\123.xml"
[xml]$doc = Get-Content $xmlfile

# find element by tag name
$te = $doc.DocumentElement.SelectSingleNode("token")

# check if element exists
if (-not $te) {
    # create the element if not exist
    $te = $doc.CreateElement("token")
    # append to DocumentELement
    $doc.DocumentElement.AppendChild($te) 
}

# set element value
$te.InnerText = "XXXXXXXX"

# save the document back to the file
$doc.Save($xmlfile)



see also

Call powershell script block from a batch script

You can use -Command option to execute a script block:
powershell -NoProfile -Command "[xml]$doc = Get-Content %DMCFG%; $te = $doc.DocumentElement.SelectSingleNode(\"token\"); if (-not $te) { $te = $doc.CreateElement(\"token\"); $doc.DocumentElement.AppendChild($te); }; $te.InnerText = \"%TOKEN%\";  $doc.Save(\"%DMCFG%\");"

Windows 10: change local group policy to allow executing PowerShell scripts

According to "3 Ways to Change PowerShell Execution Policy in Windows 10", I used Local Group Policy Editor:
  • press Windows Key and search Group Policy then select Edit group policy to start local group policy editor
  • Navigate to Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell. Double-click a setting called “Turn on Script Execution” on the right pane.
  • Select the Enabled option. Beneath it, you can click the drop-down list to set the execution policy to “Allow all scripts“ or "Allow local scripts and remote signed scripts". Click OK to save your changes.

Windows Batch Script: download file using bitsadmin without ssl certification validation

  • For the web server that does not support content range requests. You have to set priority to FOREGROUND to force the job to run synchronously. Otherwise, error: BG_E_INSUFFICIENT_RANGE_SUPPORT (0x80200013)
    bitsadmin /transfer MyJob /priority FOREGROUND  "http://your-site.org/file.zip" "C:\test\file.zip"
    
  • For the web server with self signed certificate or could not pass the ssl certificate validation, you cannot use a single bitsadmin /transfer command and the job has to be run asynchronously. You have to bitsadmin /create a job and bitsadmin /SetSecurityFlags to value 30
    bitsadmin /create MyJob1
    bitsadmin /addfile MyJob1 "https://your-site.org/file.zip" "C:\test\file.zip"
    bitsadmin /SetSecurityFlags MyJob1 30
    bitsadmin /SetPriority MyJob1 FOREGROUND
    bitsadmin /resume MyJob1
    bitsadmin /monitor || bitsadmin /cancel MyJob1
    







see also

Windows Batch Script: Download file using powershell

SET "url=https://your-site.org/a-file.zip"
SET "out=C:\Downloads"
POWERSHELL -COMMAND "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};(New-Object Net.WebClient).DownloadFile('%url%', '%out%')"
NOTE: [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} bypass the SSL certificate validation.










See also

Windows Batch Script: call multiple powershell commands in one line

Multiple powershell commands are separated by semicolons:
POWERSHELL -COMMAND "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};(New-Object Net.WebClient).DownloadFile('%url%', '%out%')"