g++ test.cpp -o test 2>&1 | Tee-Object -Filepath error.txt
invoke-command { 'txt1'; write-error 'err'; 'txt2' } -ErrorVariable e
#пример вызова внешней команды
invoke-command { python 1.py 2>&1 } -ErrorVariable e
$e | Out-File error.txt
$LastExitCode
Contains the exit code of the last Windows-based program that was run.
try {
Copy-Item -ErorAction Stop .......
}
catch {
exit 1
}
MyUtils/
MyUtils.psd1
MyUtils.psm1
functions/
Get-Something.ps1
Get-SomethingOther.ps1
@{
ModuleVersion = '1.0'
GUID = '72d739dd-bddf-4d7c-a358-1a40e2ff961d'
Description = 'MyUtils module'
NestedModules = @('MyUtils.psm1')
}
Try {
Get-ChildItem "$PSScriptRoot\functions\*.ps1" -Exclude *.tests.ps1, *profile.ps1 |
ForEach-Object {
$Function = $_.Name
. $_.FullName
}
} Catch {
Write-Warning ("{0}: {1}" -f $Function,$_.Exception.Message)
Continue
}
function Get-Something {
param(
$parameter
)
Write-Host "I'm Get-Something with $parameter"
}
... | Sort-Object -Property TimeCreated
$date = [datetime]'2020-04-13';
... |
Where-Object { $_.TimeCreated.Date -eq $date } |
Measure-Object -Sum -Property SessionDuration
[Console]::CursorVisible = $false
работает, но до первого нажатия. Потому что его модуль PSReadline по новой включает.if ((TestPath $pathToProjectFile) -eq $false) {
function TestPath($Path) {
Write-Host -fore Green "Args: $args"
return (Test-Path -Path $Path -PathType leaf)
}
Args: -eq False
$x1 = [xml]$xml1
$x2 = [xml]$xml2
$x2.FORM.Group.InnerXml = $x1.FORM.Group.InnerXml
? # Сразу используем массив, а не строку - можно обойтись без деления на части
$ComputerList = "PC1", "PC2", "PC3", "PC4", "PC5", "PC6", "PC7", "PC8", "PC9", "PC10"
Write-Host -ForegroundColor Magenta "Количество компьютеров:" $ComputerList.Length
# Get-Random Умеет сам выбирать нужное количество элементов, поданных на вход
# к тому же он выдаёт гарантированно неповторяющиеся элементы, ваш вариант потенциально может выдать, например, два пятых компа
$NewList = $ComputerList | Get-Random -Count 5
Write-Host -ForegroundColor Green "Количество новых компьютеров:" $newList.Length
Write-Host -ForegroundColor Red "Список новых компьютеров:" $newList
Windows 7, установлен Net Framework 4.7
$psversiontable.psversion показывает что у меня 2ая версия powershell
# Тут можно импортировать модуль напрямую, если не класть его по вышеуказанным путям
#Import-Module C:\Path\To\Module\WindowHelper.psm1
# Или просто импортировать, если есть в путях (необязательно)
#Import-Module WindowHelper
# Импортируем типы для использования SendKeys
Add-Type -AssemblyName System.Windows.Forms
# Ищем среди всех окон окно с нужным заголовком
$w = Get-ChildWindows | ? { $_.Text -eq 'Visual Studio Code' }
# Клавиши, которые нужно нажимать
# Брать отсюда - https://docs.microsoft.com/ru-ru/dotnet/api/system.windows.forms.sendkeys
$KeySequence = '{F1}'
# Активируем нужное окно
Set-ForegroundWindow $w.Handle
# Небольшая задержка
Start-Sleep -Milliseconds 100
# Посылаем клавиши
[System.Windows.Forms.SendKeys]::SendWait($KeySequence)
- name: Information about license for Windows
win_shell: |
# variant 1
Start-Process -Wait -RedirectStandardOutput C:\111 -FilePath cscript -ArgumentList 'slmgr.vbs','-dlv'
Get-Content C:\111 -Encoding OEM
# variant 2
[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding("cp866")
cscript slmgr.vbs -dlv > c:\222
Get-Content C:\222 -Encoding Unicode
register: infowin_out
args:
chdir: '{{ ansible_env.windir }}\System32\'
no_profile: yes
- debug: var=infowin_out