顯示具有 PowerShell 標籤的文章。 顯示所有文章
顯示具有 PowerShell 標籤的文章。 顯示所有文章

2026-11-24

用 PowerShell 將連線到 Git Repo 用的 Access Token 存入 Windows 認證管理員

 # 手動輸入
$u = Read-Host '請輸入帳號 (Username)'
$s = Read-Host '請貼上新的 Access Token / 密碼(畫面不會顯示)' -AsSecureString
$repoUrl = Read-Host '請輸入 Repo URL (例如 https://git.test.com/test/test.git)'

# 自動輸入
$u = 'Test_on_TestVM'
$s = ConvertTo-SecureString "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -AsPlainText -Force
$repoUrl = 'https://git.test.com/test/test.git'

2026-11-20

PowerShell 設定台灣的 NTP Server

PowerShell 設定台灣的 NTP Server

$NTPServers = 'tick.stdtime.gov.tw,0x9 tock.stdtime.gov.tw,0x9 time.stdtime.gov.tw,0x9 clock.stdtime.gov.tw,0x9 watch.stdtime.gov.tw,0x9'
Write-Host "Setting NTP Servers..." -ForegroundColor Green
w32tm /config /syncfromflags:manual /manualpeerlist:"$NTPServers" /reliable:no /update | Out-Null
Restart-Service w32time -Force
Start-Sleep 5
w32tm /resync /force
Write-Host "`nCurrent Source:" -ForegroundColor Yellow
w32tm /query /source
Write-Host "`nCurrent Status:" -ForegroundColor Yellow
w32tm /query /status

2026-08-18

Windows 11 上安裝 SSH Server

Run PowerShell as an Administrator.

Check if OpenSSH is available by running:

Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'

If OpenSSH Server is not installed, run:

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

To start the OpenSSH Server, run the following command:

Start-Service sshd

Optionally, set it to start automatically with Windows:

Set-Service -Name sshd -StartupType 'Automatic'

Once these steps are completed, the OpenSSH Server should be running on your Windows 11 Pro computer.

Reference: https://learn.microsoft.com/en-us/answers/questions/5757124/how-to-turn-on-openssh-sever-on-windows-11-pro-com


2026-05-11

Powershell 取得運作中的程序,Kill 掉

取得 Process,Kill 掉:

Powershell 指令:

Get-Process | Select-Object `
Name,
Id,
@{N="ExeName";E={
if ($_.Path) { Split-Path $_.Path -Leaf } else { "N/A" }
}},
@{N="FullPath";E={$_.Path}},
@{N="CPU(s)";E={$_.CPU}},
@{N="Memory(MB)";E={[Math]::Round($_.WorkingSet64/1MB,2)}},
@{N="Owner";E={
try {
(Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)") |
Invoke-CimMethod -MethodName GetOwner |
ForEach-Object { "$($_.Domain)\$($_.User)" }
} catch {
"N/A"
}
}}

2026-04-30

OneDrive 復原資源回收桶內超量檔案的方法

使用者「不小心」在 OneDrive 桌面應用程式同步的情況下刪除了含有大量檔案的資料夾
並因為 OneDrive 桌面應用程式同步的關係將 OneDrive 雲端伺服器中的檔案也刪除
此時透過 OneDrive 網頁的資源回收桶進行復原將產生錯誤,因為復原檔案有限制數量







此時必須動用 PowerShell 指令搭配 Microsoft Entra App 來處理
先安裝好 PowerShell Module: PnP.PowerShell (需要 PowerShell 7 版本)
Install-Module -Name "PnP.PowerShell" -Scope AllUsers -Force (我都裝 AllUsers)
接著到 Microsoft Entra admin center 註冊一個 App
給予 API Permession 的時候「不是」選 Microsoft Graph,而是選 SharePoint

2026-03-06

Get VM's Virtual Hard Disk Size with Keyword

$keyword = 'Off'

$vms = Get-VM | Where-Object { $_.Name -like "*$keyword*" }

if (-not $vms) {
   Write-Host "找不到 VM 名稱包含 '$keyword' 的虛擬機。" -ForegroundColor Yellow
   return
}

$vmResults = @()
$grandTotalBytes = 0

foreach ($vm in $vms) {
   $hdds = Get-VMHardDiskDrive -VMName $vm.Name -ErrorAction SilentlyContinue

   if (-not $hdds) {
       $vmResults += [pscustomobject]@{
           VMName     = $vm.Name
           VhdCount    = 0
           TotalSizeGB = 0.0
           Detail     = "<無掛載虛擬硬碟>"
       }
       continue
   }

2025-12-05

批次建立 win-acme 用 DNS Record 取得憑證的任務

批次建立 win-acme 用 DNS Record 取得憑證的任務

$RecordNames = @();
$RecordNames += "www";

$Domain = "contoso.com";

foreach ($RecordName in $RecordNames) {
    
    $FQDN = ($RecordName + '.' + $Domain);
    write-host ('Request Certificate for ' + $FQDN);

在 Azure DNS Zone 用 DNS Record 來驗證 Let's Encrypt 的 PowerShell Script

前情提要: 在 Microsoft DNS Server 上用 DNS Record 來驗證 Let's Encrypt 的 PowerShell Script

AzureDNSZoneVerification.ps1


# -Step "create" -Identifier "{Identifier}" -RecordName "{RecordName}" -Token "{Token}"
# -Step "delete" -Identifier "{Identifier}" -RecordName "{RecordName}" -Token "{Token}"

param (
[string]$Step,
[string]$Identifier,
[string]$RecordName,
[string]$Token
);

[string]$AzureResourceGroupName = "Infra_Network"
[string]$ZoneName = "contoso.com"
[int]$TTL = 3600

write-host ('Step: ' + $Step);
write-host ('Identifier: ' + $Identifier);
write-host ('RecordName: ' + $RecordName);
write-host ('Token: ' + $Token);

2025-11-20

在 Exchange Online 如果寄給某個外部網域的信件無法送達,不要退信給原寄件者

在 Exchange Online 如果寄給某個外部網域的信件無法送達,不要退信給原寄件者
方法是透過 Remote Domain 設定停用 NDR(Non-Delivery Report)

首先要建立 Remote Domain (在 EAC Mail flow -> Accepted domains)
New-RemoteDomain -Name "DomainNameOne" -DomainName "Domain.Name.One"
New-RemoteDomain -Name "DomainNameTwo" -DomainName "Domain.Name.Two"

停用 NDR必須用 PowerShell 指令,EAC 不支援 (這裡的 -Identity 是上面的 -Name)

Set-RemoteDomain -Identity "DomainNameOne" -NDREnabled $false
Set-RemoteDomain -Identity "DomainNameTwo" -NDREnabled $false

2025-10-24

Fix: SMTP Service MMC has detected an error in a snap-in

When right-click on [SMTP Virtual Server #1] in IIS 6.0 Manager and SMTP Server, you may get this error:

"MMC has detected an error in a snap-in. It is recommended that you shut down and restart MMC."

Here's the fix:

  1. Stop SMTPSVC service [Display Name: Simple Mail Transfer Protocol (SMTP)]
  2. Stop IISADMIN service [Display name: IIS Admin Service]
  3. Edit "C:\Windows\System32\inetsrv\MetaBase.xml"
  4. Find: <IIsSmtpServer Location ="/LM/SmtpSvc/1"
  5. Add (Settings are alphabetical): RelayIpList=""
  6. Save file
  7. Start IISAdmin Service
  8. Start SMTPSVC service

以下提供 PowerShell 程式,直接執行完成上述步驟

2025-10-23

Replace Ceritificate on IIS SMTP Virtual Server


$PFXPath = "C:\Cert\"
$PFXPW  = ''
$PublishedURL = "smtp.contoso.com"

Import-Module WebAdministration
$MicrosoftIISv2WMI = Get-CimInstance -Namespace root/MicrosoftIISv2 -Class __Namespace -ErrorAction SilentlyContinue
if ($MicrosoftIISv2WMI -eq $Null) {
Install-WindowsFeature Web-Mgmt-Compat, Web-WMI;
};
$SMTPServer = Get-CimInstance -Namespace root/MicrosoftIISv2 -Class IIsSmtpServerSetting -Filter ("FullyQualifiedDomainName='".$PublishedURL."'")
if ($SMTPServer.AccessSSL -ne $True) {
write-host 'TLS not enabled';
exit;
};

2025-10-15

取出 MSSQL DB 中 ZIP 壓縮過的二進位 .eml 檔並取出 Subject 等資訊

Mail eml 格式檔案 ZIP 後存在 DB 裡,但某日發現資料庫中有許多 Record 的 Subject 都錯誤
推測是歸檔程式有 Bug 的關係。
因為會影響搜尋結果,所以必須從資料庫中取出 ZIP 過的 eml 檔案
解壓後分析,再修正資料庫中的資料

以下程式包含上述功能但有更多其他功能,就不多說,有需要自取

需要 
SharpZipLib
這是用來忽略解壓過程中發生錯誤,強制解壓的工具
不知道為什麼 DB 中的 ZIP 二進位資料取出後解壓會有問題,但忽略錯誤就可以

只用 Powershell 實在沒辦法對 Email 做良好的 Parser,必須丟到 Python 去處理
所以需要用 Powershell 處理到一半,用 Python 讀檔,再回 Powershell 處理
因為我實在不熟 Python,不然應該要用 Python 從頭寫到瑋才對

以下程式有許多部份都是用 Copilot 協助產生的,再加上自己修改而成

2025-09-16

為 Powershell Script (*.ps1) 或自行編譯的執行檔 (*.exe) 建立自我信任的數位簽章

以下使用的環境為以 Windows Server 建立的Standalone CA,Enterprise CA 大同小異
首先建立一個憑證範本,用以提交 Code Signing Request 給 CA
其中藍字部分改為自己需要的內容
將其存檔為 CodeSigning.inf (純文字檔)
[Version]
Signature="$Windows NT$"

[NewRequest]
Subject = "CN=Dino9021 Code Signing, OU=IT, O=DinoClub, L=Hsinchu, S=Taiwan, C=TW"
KeySpec = 1
KeyLength = 2048
Exportable = TRUE
MachineKeySet = FALSE
SMIME = FALSE
PrivateKeyArchive = FALSE
UserProtected = FALSE
UseExistingKeySet = FALSE
RequestType = PKCS10
ProviderName = "Microsoft RSA SChannel Cryptographic Provider"

[Extensions]
2.5.29.37 = "{text}"
_continue_ = "1.3.6.1.5.5.7.3.3" ; Code Signing EKU

2025-07-30

Block Auth Failed IPs for Exchange

$UnBlockIPURL 是一個給 User 自行解鎖 IP 的清單,要另外處理
此處不提供與介紹

# in Hours
$BlockTime = 720;
$RuleGroupName = "ExchangeAuthFailBlockIPs"
$RuleSubnetsGroupName = "ExchangeAuthFailBlockSubnets"
$SMTPLookBackHours = 1;
$SMTPLogFullPath = "C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\FrontEnd\ProtocolLog\SmtpReceive\"
$SMTPLogSearchTailLines = 10000;
$UnBlockIPURL = 'https://www.contoso.com/BlockIPs/History/AllUnblock.Json';

$ClassBSubnetBlockCount = 3;

#-------------------------------------------------------------------------------------------------------------------------------------------

Export SharePoint Files with Path hierarchy with PowerShell

利用 Invoke-RestMethod 透過網址下載
需要具有 Site 管理權限

搭配 Junction 避免路徑過長的問題
如果還是過長,要再另外處理

注意非黑色文字的變數與執行細節

ExportSharePointSiteTriggler.ps1

$Finalize = $False;

$ConcurrentLimit = 5; 

Add-PSSnapin Microsoft.SharePoint.PowerShell
$Sites = (Get-SPSite -Limit ALL) 

$ExceptSites = @();
$ExceptSites += 'DefaultSite';

$TargetSites = @();
foreach ($SiteURL in ($Sites | where {(($_.Url -Split '/').count -eq 5) -and ($ExceptSites -notcontains ($_.Url -Split '/')[-1])})) {
$TargetSites += ($SiteURL.Url -Split '/')[-1];
};

$Location = 'S:\Command';
Set-Location -LiteralPath $Location;

foreach ($TargetSite in $TargetSites) {
write-host ('Processing ' + $TargetSite);
Start-Process "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ($Location + '\ExportSharePointSiteMain.ps1'), "-TargetSite", $TargetSite

while ((Get-Process -Name 'PowerShell').Count -ge $ConcurrentLimit) {
Start-Sleep -Seconds 1;
};
};

2025-04-28

URL Parsing by PowerShell

URL Parsing by PowerShell

$URL = "https://api.contoso.com/level1/level2/Script.php?index=1&page=2&content=3";
$URI = [System.Uri]$URL;

Add-Type -AssemblyName System.Web;
$ParsedQueryString = [System.Web.HttpUtility]::ParseQueryString($URI.Query);
$QueryParams = New-Object -TypeName PSObject;
$i=0;
foreach($QueryStringObject in $ParsedQueryString){
    $QueryParams | Add-Member -MemberType NoteProperty -Name $QueryStringObject -Value $ParsedQueryString[$i];
    $i++;
};

$URI | fl;
$QueryParams.PSObject.Properties.Name;
$QueryParams;


2025-04-23

Link User to Existed Exchange Online Mailbox

Powershell Exchange Online

Get-Mailbox UserName | fl ExchangeGuid    #取得 ExchangeGuid

PowerShell On-Premises

Enable-RemoteMailbox UserName -RemoteRoutingAddress  UserName@YourDomain.mail.onmicrosoft.com
Set-RemoteMailbox UserName -ExchangeGuid <ExchangeGuid from above>

如果是 Shared Mailbox, Enable-RemoteMailbox 指令加上 -Shared 參數

參考資料:
https://www.itpromentor.com/link-aduser-365/


2025-04-18

以 ffmpeg 批次降低影片 bitrate

運動攝影機錄影擋預設流量 (bitrate) 很高,但其實我覺得看不太出來高低流量畫質的差異
所以根據網路查的一些建議用 ffmpeg 批次處理降低流量
先用 
ffprobe.exe 取得影片屬性,再根據影片屬性進行處理

以下 Powershell 中,VideoRotation 是影片方向的資訊,在降低流量的處理中實際上不需要
這裡只是當作筆記用,未來有需要的時候才找得到
 (找很久才找到這個語法)

#設定要降低的 bitrate 值 Start
$ProcessMethod = @();
$ProcessMethod += New-Object -TypeName PSObject -Property @{
     Width = 2688;
     FrameRate = 30;
     BitRate = 16;
};
$ProcessMethod += New-Object -TypeName PSObject -Property @{
     Width = 2688;
     FrameRate = 60;
     BitRate = 24;
};
$ProcessMethod += New-Object -TypeName PSObject -Property @{
     Width = 3840;
     FrameRate = 30;
     BitRate = 45;
};
$ProcessMethod += New-Object -TypeName PSObject -Property @{
     Width = 3840;
     FrameRate = 60;
     BitRate = 55;
};
$ProcessMethod += New-Object -TypeName PSObject -Property @{
     Width = 3840;
     FrameRate = 120;
     BitRate = 65;
};
#設定要降低的 bitrate 值End

360 全景影片加入 Metadata Tag

全景影片用 VLC 等媒體播放軟體播放時若預設不以全景模式播放代表缺少 Metadata Tag
解決辦法如下,如果檔案量少,可以直接用 GUI 程式處理,檔案多的話跑批次比較省事

GUI & Source: google spatial-media
https://github.com/google/spatial-media/releases

Command 需要 python 2.7 (新版不行)
根據影片類型可能要加入 StereoMode 參數,請自行參考程式說明
先轉轉看確認參數再跑批次

Set-Location -Path "D:\Software\spatial-media-2.1\";
$Files = (Get-ChildItem -Path 'D:\Video' -File)
foreach ($File in $Files) {
& D:\Python27\python.exe spatialmedia -i $File.FullName ($File.FullName -Replace $File.BaseName,($File.BaseName + '_360 Tag Added'));
#if (($File.FullName -Replace $File.BaseName,($File.BaseName + '_360 Tag Added')) -eq $True) {
# remove-item -path $File.FullName -force;
#};

};

技術細節可 Google 關鍵字: Inject 360 Metadata