function DeleteOldFile { param ( [string] $Path, [int] $LastWriteDay = -7, [string[]] $Extension = ("*.tmp","*.temp") ) try { Write-Verbose "DeleteOldFile::Path: $Path, LastWriteDay: $LastWriteDay" Get-ChildItem $Path -Include $Extension -Recurse | Where-Object { ($_.LastWriteTime -lt (Get-Date).AddDays($LastWriteDay)) } | Remove-Item -recurse -force } catch { $e = $_.Exception $line = $_.InvocationInfo.ScriptLineNumber Write-Host -ForegroundColor Red "caught exception: $e at $line" } } DeleteOldFile -Path ".\tmp" -LastWriteDay -40
Test-NetConnection www.example.com -Port 443 ComputerName : www.example.com RemoteAddress : 93.184.216.34 RemotePort : 443 InterfaceAlias : イーサネット 2 SourceAddress : ***.***.***.*** TcpTestSucceeded : True Test-NetConnection www.example.com -Port 443 -InformationLevel Quiet True
$PSVersionTable.BuildVersion Major Minor Build Revision ----- ----- ----- -------- 10 0 19041 1
Get-WmiObject Win32_OperatingSystem | ft BuildNumber,Version # Win10 1909の場合 BuildNumber Version ----------- ------- 18363 10.0.18363
.\script.ps1 *> script.log
- name: Create task to run a PS script as NETWORK service on boot win_scheduled_task: name: TaskName2 description: Run a PowerShell script actions: - path: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe arguments: -Command "c:\tmp\script.ps1 *> c:\tmp\script.log" triggers: - type: daily start_boundary: '2017-10-09T09:00:00' username: SYSTEM state: present enabled: yes
return "func1" # は以下と同じ "func1" return
function func1 { return "func1" } function func2 { func1 return "func2" } func2
func1 func2
function func1 { return "func1" } function func2 { $ret = func1 return "func2" } func2
func2
$var1 | ConvertTo-Json
try{ } catch { $e = $_.Exception $line = $_.InvocationInfo.ScriptLineNumber Write-Host -ForegroundColor Red "caught exception: $e at $line" }
echo (Convert-Path ".\example.log") C:\tmp\example.log
$config_var1="hoge"
# Include config . (Join-Path $PSScriptRoot "example-conf.ps1") echo $config_var1
# localtime Get-Date 2020年4月2日 16:45:32 # UTC (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz") 2020-04-02T08:03:27+09:00 # iso-8601 Get-Date -Format "o" 2020-04-02T16:56:30.9156570+09:00 # 文字列へ (Get-Date).ToString() 2020/04/02 16:50:00 # 任意の書式へ (Get-Date).ToString("yyyy-MM-ddTHH:mm:sszzz") 2020-04-02T17:01:17+09:00
Get-Command -Module Microsoft.PowerShell.Utility -Verb Write CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Write-Debug 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Error 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Host 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Information 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Output 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Progress 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Verbose 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Write-Warning 3.1.0.0 Microsoft.PowerShell.Utility
# 出力On $VerbosePreference = 'Continue' # 出力Off $VerbosePreference = 'SilentlyContinue'
# ファイルの場合は、ファイルサイズ (Get-ChildItem .\example.ps1).Length 987 # ディレクトリの場合は、ファイル数 (Get-ChildItem c:\tmp).Length 6
Remove-UTF8BOM -FilePath (Join-Path $PWD "utf8bom.txt")
function Utf8NoBom { param ( [string] $InPath, [string] $OutPath ) Get-Content -Path $InPath -Raw -Encoding Default ` | % { [Text.Encoding]::UTF8.GetBytes($_) } ` | Set-Content -Path $OutPath -Encoding Byte if (! (Test-Path -Path $OutPath)) { New-Item -Type File $OutPath } } Utf8NoBom ".\in.csv" ".\out.csv"
$ErrorActionPreference = "silentlycontinue" # エラーを無視したいコマンド $ErrorActionPreference = "continue"
function myfunc{ try{ # エラーが出る処理 $ErrorActionPreference = "silentlycontinue" }catch{ } }
- Touch-File $GZipPath + New-Item -Type File $GZipPath
Powershellだと安定しなかったので、NXLog等のツールで外部に送信するのが良さそう
記事:
似たような関数があるが、使えるオプションが違う
$LogName="Application" $AfterDate="2020-04-02" $CSVpath=$LogName + ".csv" Get-WinEvent -FilterHashtable @{LogName=$LogName;level=1,2;starttime=((Get-Date).AddDays(-1))} | Select timeCreated,levelDisplayName,providerName,id,@{name="message";expression={$_.message.Replace("`n",";")}} | Export-CSV $CSVpath -Encoding UTF8 -NoTypeInformation $AfterDate="2020-04-02" $CSVpath=$LogName + "." + $AfterDate + ".csv" Get-EventLog -LogName $LogName -After $AfterDate | Select timeCreated,levelDisplayName,providerName,id,@{name="message";expression={$_.message.Replace("`n",";")}}| Export-CSV $CSVpath -Encoding UTF8 -NoTypeInformation
#!powershell $PSVersionTable.PSVersion
$PSVersionTable.PSVersion
powershell -Command ".\ver.ps1" Major Minor Build Revision ----- ----- ----- -------- 5 1 18362 628
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -Command ".\ver.ps1" Major Minor Build Revision ----- ----- ----- -------- 5 1 18362 628
wsl.exe経由で呼び出せる。
Get-Process | Out-GridView
Get-ChildItem env: Name Value ---- ----- ALLUSERSPROFILE C:\ProgramData APPDATA C:\Users\user01\AppData\Roaming ChocolateyPath C:\Chocolatey CommonProgramFiles C:\Program Files\Common Files ...
echo $env:LOCALAPPDATA C:\Users\user01\AppData\Local echo $env:APPDATA C:\Users\user01\AppData\Roaming
$env:MYENV1 = "Hello" $env:MYENV1 Hello
Get-Help
gci -r
powershell Get-Service | where StartType -eq Manual | where Status -eq Running Status Name DisplayName ------ ---- ----------- Running Appinfo Application Information Running AppMgmt Application Management ...
powershell > get-childitem . -include *.zip -recurse | foreach ($_) { .\7z.exe l $_.name | Select-String "hoge.jpg" }
powershell ./get-smart.ps1 ######## Active: True InstanceName: IDE\DiskWDC_WD10EALX-759BA1_____________________19.01H19\4&1d873d54&0&0.0.0_0 Length: 512 bAttrID wStatusFlags bAttrValue bWorstValue bRawValue[6] 1 47 0 200 200 0 0 0 0 0 0 3 39 0 177 174 54 16 0 0 0 0 4 50 0 100 100 239 1 0 0 0 0 5 51 0 200 200 0 0 0 0 0 0 7 46 0 200 200 0 0 0 0 0 0 9 50 0 95 95 154 16 0 0 0 0 10 50 0 100 100 0 0 0 0 0 0 11 50 0 100 100 0 0 0 0 0 0 12 50 0 100 100 237 1 0 0 0 0 192 50 0 200 200 19 0 0 0 0 0 193 50 0 200 200 219 1 0 0 0 0 194 34 0 108 103 39 0 0 0 0 0 196 50 0 200 200 0 0 0 0 0 0 197 50 0 200 200 0 0 0 0 0 0 198 48 0 100 253 0 0 0 0 0 0 199 50 0 200 200 0 0 0 0 0 0 200 8 0 100 253 0 0 0 0 0 0 240 50 0 95 95 13 16 0 0 0 0 241 50 0 200 200 92 134 168 41 2 0 242 50 0 200 200 4 174 82 249 1 0
PowerShell内で「exit 2」としても、「echo %ERRORLEVEL%」は全て"1"になる。
以下のようにすれば取得できるようだ
powershell -NoProfile -command ".\test.ps1;exit $LASTEXITCODE" echo %ERRORLEVEL%
デフォルトでは実行不可になっている。
powershell Set-ExecutionPolicy RemoteSigned