簡體   English   中英

腳本運行時如何引用當前登錄用戶?

[英]How do I reference the current logged in user when a script is running?

因此,我正在使用 Desktop Central 在一堆機器上運行一些腳本。 該腳本應該在 c:\users%USERNAME%\ 文件夾中打開一個 zip 文件,並將其解壓縮到我選擇的文件夾中。 這個想法是為多台機器使用一個腳本,可以利用 c:\users\LOGGEDONUSER\downloads 文件夾(默認 TEAMS 下載目錄)。 這個想法是每個用戶將從團隊下載存檔,腳本將從每個用戶的 DOWNLOADS 文件夾解壓縮和安裝。

問題是我似乎不知道如何編寫腳本使用一個變量來表示登錄用戶的用戶名作為我參數中的 -path。

例如;

Extract file
Expand-archive -path $home\Downloads\SWANDPDM_SP5.1.zip -DestinationPath C:\temp\swpdminstaller\extracted\ -Force

#Define registry values to modify to allow for no UAC
$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
$Name         = 'ConsentPromptBehaviorAdmin'
$Value        = '0'

#Run reg change
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force

#Run installer
Invoke-Item C:\temp\swpdminstaller\extracted\SOLIDWORKS_AND_PDM_2021_SP5.1\startswinstall.exe

#Define reg values to change back to default
$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
$Name         = 'ConsentPromptBehaviorAdmin'
$Value        = '5'

#Run reg change
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force

如果我手動將腳本復制到機器並以用戶身份啟動腳本,這會非常有效。 它查看 $home 並根據登錄的人找出正確的目錄。

但是,當它作為 Desktop Central 運行時,$home 並不意味着相同的位置。 它回來了;

Expand-archive : The path 'C:\Windows\system32\config\systemprofile\Downloads\SWANDPDM_SP5.1.zip' either does not
exist or is not a valid file system path.
At C:\Program Files (x86)\DesktopCentral_Agent\Computer\startup\76507\SWandPDMdecomInstall.ps1:2 char:1
+ Expand-archive -path $home\Downloads\SWANDPDM_SP5.1.zip -DestinationP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Windows\syst...NDPDM_SP5.1.zip:String) [Expand-Archive], InvalidOpe
rationException
+ FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Expand-Archive

我嘗試使用各種環境變量,但沒有成功。 似乎因為它是一個遠程運行腳本的“桌面中心”帳戶,所以我無法讓它指向 c:\users\NAMEOFLOGGEDINUSER\ 中的正確文件夾

因此,它認為 $home = 'C:\Windows\system32\config\systemprofile\ 而不是 c:\users\NAMEOFLOGGEDINUSER\

有沒有辦法獲取當前登錄用戶的用戶名,將其分配給一個變量,然后使用該變量而不是 $home? 請記住,它需要在以 Desktop Central 服務帳戶運行腳本時找到登錄用戶。 我試過以各種域管理員\系統帳戶的身份運行腳本,但沒有成功。

我想過做一個 whoami,寫入一個文本文件,然后省略 output 的域部分並將其分配給一個變量,但必須有更好的方法。

任何幫助是極大的贊賞!

編輯:以為我在做某事,但沒有用。 我試過;

Expand-archive -path $env:HOMEPATH\Downloads\SWANDPDM_SP5.1.zip -DestinationPath C:\temp\swpdminstaller\extracted\ -Force

我從評論中看到您找到了解決方法。 但是要回答您最初的問題,當您在不同的安全上下文下運行腳本時,您無法通過通常的 Powershell 技術( $env:USERNAMEwhoami等)獲取登錄用戶名。

但是您可以檢查誰擁有Explorer.exe進程:

$User = (Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'" | 
 Invoke-CimMethod -MethodName GetOwner).User

“Desktop central”用戶可能不會運行 Explorer。 但是,如果有多個用戶通過 RDP 會話登錄,這將返回一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM