LoginSignup
3
8

More than 5 years have passed since last update.

powershell備忘録

Last updated at Posted at 2017-10-17

個人用備忘録

リモートサーバーでmsuファイルをインストール

invoke-commandとかps-remotingでサーバーにmsuをインストールしようとするとうまく行かなかったのでその対処法

普通ならば

wusa $X:\XXX\XXXXX.msu /quit

ですが、、、

wusa $X:\XXX\XXXXX.msu /extract:D:\XXXX
dism /online /add-package /PackagePath:D:\wfm51\XXXXXX.cab /Quiet

これでいけました

Path型とString型を + でつなごうとすると出るエラー

 [System.Management.Automation.PathInfo] に 'op_Addition' という名前のメソッドが含まれないため、メソッドの呼び出しに失敗しました。
発生場所 行:1 文字:1

とりあえずString型同士で結合することで回避

ホスト名から連番部分を取り出す

クラウド上の仮想マシンを複数台立てた際に連番でサーバー名を命名しましたが、カスタムドメインをそれぞれに振ったときにも同じく連番を振っているのですが、サーバー内部で自分のカスタムドメインが必要なときに自分のサーバー名からカスタムドメイン名を取得する際に使用したスクリプト

#PC名取得
$MyHostName = [Net.Dns]::GetHostName()
#共通ホスト名部分だけを端折り数字だけを取り出す
$StringHostNumber = $MyHostName.Replace($HostNameChar, '') 
#Intに型変換して頭の00を取る※物によって頭の0の数違うので
$IntHostNumber = [int]$StringHostNumber
#最後に必要な桁数(001とか01とか)に置換する

HashTableの使い方

これから使いそうなのでメモ

function Show-HasnTableValue
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [HashTable] $TableValue
    )

    foreach($KeyVal in $TableValue.Keys ) 
    {
        $outputVal = $KeyVal + ":" + $TableValue[$KeyVal]
        Write-Output $outputVal
    }

}

$sampleHashTable = @{
"a"="1";
"b"="2";
"c"="3";
}
Show-HasnTableValue -TableValue $sampleHashTable

Azureサービスプリンシパルでの認証

    $clientId = "x-x-x-x-x"
    $clientSecret = "x="
    $tenantId = "x-x-x-x-x"

    $secpasswd = ConvertTo-SecureString $clientSecret -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential ($clientId, $secpasswd)
    Login-AzureRmAccount -ServicePrincipal -Tenant $tenantId -Credential $mycreds
    Set-AzureRMContext -Subscription $SubscriptionName -Name $SubscriptionName -Force
    Select-AzureRmSubscription -Context (Get-AzureRmContext -Name $SubscriptionName) -Name $SubscriptionName -Force

PSDSCの構築時にリモートホスト側で実行するスクリプト

Enable-PSRemoting -Force
Set-Item wsman:\localhost\Client\TrustedHosts -Value * -Force
Set-ExecutionPolicy RemoteSigned

ストップウォッチ


$sw = New-Object System.Diagnostics.StopWatch
# Start Stopwatch
$sw.Start()
#DO SOMETHING
# Stop Stopwatch
$sw.Stop() 
#Show Result
Write-Output ("経過時間は{0}です。" -f $sw.Elapsed)
Write-Output ("経過時間は{0}日です" -f $sw.Elapsed.TotalDays)
Write-Output ("経過時間は{0}時間です" -f $sw.Elapsed.TotalHours)
Write-Output ("経過時間は{0}分です" -f $sw.Elapsed.TotalMinutes)
Write-Output ("経過時間は{0}秒です" -f $sw.Elapsed.TotalSeconds)
Write-Output ("経過時間は{0}ミリ秒です" -f $sw.Elapsed.TotalMilliseconds) 
#Reset Result
$sw.Reset()

ループの抜け方

知らなかった。。
image.png

参考リンク:
http://ufcpp.net/study/powershell/flow.html

3
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8