Remote AD session error trapping woes - session

I am trying to catch exceptions in my remote PoSH script and I'm getting different behaviour depending on whether it is a local or remote PoSH session. The first code works as expected, the user cannot be enabled because it has no password and thus is caught by the ADPasswordComplexityException catch.
import-module activedirectory
try { Set-ADUser user123 -ErrorAction "stop" -Enabled $true }
catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException] { write-host "gotya" }
catch { write-host "err" }
..resulting in gotya being written. This happens whether I run the code locally on the DC or another PC. So all good there.
However when doing this via a remote session not only the initial catch does not work, neither does the second catch..
$ADS = New-PSSession -computername dc.domain -Authentication default -Credential $(get-credential)
Import-Module ActiveDirectory -PSSession $ADS
try { Set-ADUser user123 -ErrorAction "stop" -Enabled $true }
catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException] { write-host "gotya" }
catch { write-host "err" }
When run remotely it returns (presumably skipping all catches):
The password does not meet the length, complexity, or history requirement of the domain.
+ CategoryInfo : InvalidData: (user123:ADUser) [Set-ADUser], ADPasswordComplexityException
+ FullyQualifiedErrorId : The password does not meet the length, complexity, or history requirement of the etc..
Also when I run the remote script locally on the DC oddly I get a different error:
Unable to find type [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException]: make sure that the assembly
containing this type is loaded.
At line:1 char:7
+ try { Set-ADUser -ErrorAction "stop" user123 -Enabled $true }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Activ...lexityException:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
Any ideas why PoSH hates me? thanks in advance.

Related

problem in windows powershell while installing haskell

I try to install haskell in my windows machine, I followed the instructions given in the website of haskell.org, but when I execute in the powerShell as an administrator this commande:
Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing))) -ArgumentList $true } catch { Write-Error $_ }
It doesn't work and the terminal prints this message when the installation begins:
Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol =
[System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-Command -ScriptBlock
([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing)))
-ArgumentList $true } catch { Write-Error $_ } : Exec: Error executing command curl.exe with arguments '-o
C:\Users\MBI\AppData\Local\Temp\\msys2-base-x86_64-20221216.sfx.exe
https://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20221216.sfx.exe'
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
can you help me I don't know what is the problem

Powershell: Failing to resume bitlocker remotely with script

I am trying to resume BitLocker protection on remote devices. See the below code:
$computers = Get-Content "C:\Users\admin_jr\Documents\bitlockerlist.txt"
$credentials = Get-Credential
foreach($computer in $computers) {
Try {
$Session = New-PSSession $computer -Credential $credentials
if (-Not ($Session)) {
Write-Error "No session is made with the specified computer, please try again"
}
Invoke-Command -Session $Session -ScriptBlock {Get-BitLockerVolume | Resume-BitLocker -Verbose}
} Catch {
Write-Error "Something went wrong"
}
}
I get the following error message:
The TPM returned an unexpected result. (Exception from HRESULT: 0x8029010C)
+ CategoryInfo : NotSpecified: (:) [Write-Error], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Resume-BitLocker
+ PSComputerName : *pcname*
I am currently testing this on a laptop whereby I can manually resume and suspend the Bitlocker protection but essentially want to emulate and automate this via a script on multiple pcs.
Any advice on this?

Powershell: Find the currently logged on user and copy a unique file from a shared drive

Title says most of it. I have generated unique files for users who will be running their scripts remotely. The script is supposed to find the name of the currently logged on user and copy that unique file to C:\Users\Public. Currently however I am running into an issue where the system seems to default to my username. I have tried multiple methods sourced from here and stack overflow and cannot seem to get a good result, as everyone ends up with my unique file. I have tried the following:
$env:username
$env:userprofile
$currentuser=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
The script looks as such:
$currentuser=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
if ($currentuser = "Domain/username1") {
copy-item -Path "shared network location\username1file" -Destination "C:\Users\Public"
}
elseif ($currentuser = "Domain\username2") {
copy-item -Path "shared network location\username2file" -Destination "C:\Users\Public"
}
elseif ($currentuser = "domain\username3") {
copy-item -Path "shared network location\username3file" -Destination "C:\Users\Public"
}
Can anyone provide me any advice on how to fix this?
To get the currently logged on user and not the user currently running the script, you can use WMI Win32_ComputerSystem.
Also, I would recommend using switch instead of multiple elseif:
$currentuser = (Get-WmiObject -Class Win32_ComputerSystem).UserName
$file = switch ($currentuser) {
'Domain\username1' { "shared network location\username1file"; break }
'Domain\username2' { "shared network location\username2file"; break }
'Domain\username3' { "shared network location\username3file"; break }
default { $null }
}
if ($file) {
Copy-Item -Path $file -Destination "C:\Users\Public"
}
else {
Write-Host "No file to copy defined for user '$currentuser'"
}

Downloading certain files using powershell produce corrupt files

So I have a powershell script that I wrote which crawls through a particular website and downloads all of the software hosted on the site to my local machine. The website in question is nirsoft.net, and I will include the full script below. Anyway, so I have this script that downloads all of the application files hosted on the website, when I notice something odd: while most of the file downloads completed successfully, there are several files that were not downloaded successfully, resulting in a corrupt file of 4KB:
For those of you who are familiar with Nirsoft's software, the tools are very powerful, but also constantly misidentified as dangerous because of the password cracking tools, so my guess as to why this is happening is that, since powershell's If I were to guess as to why this was happening, I would guess that, due to the fact that powershell's "Invoke-webrequest cmdlet" uses Internet Explorer's engine for its core functionality, Internet Explorer is flagging the files as dangerous and refusing to download them, thus causing powershell to fail to download the file. I confirmed this by trying to manually download each of the corrupt files using internet explorer, which marked them all as malicious. However, this is where things get strange. In order to bypass this limitation, I attempted a variety of other methods to download the file within my script, like using a pure dotnet object ( (New-object System.Net.WebClient).DownloadFile("url","file") ) and even some third party command line tools (wget for windows, wget in cygwin, etc), but no matter what I tried, not a single alternative method I used was able to download a non-corrupt file. So what I want to know is if there is a way around this, and I want to know why even third party tools are affected by this. Is there some kind of rule that any scripting tool has to use Internet Explorer's engine in order to connect to the internet or something? Thanks in advance. Oh, and one last thing before I post the script. Below is the url to one of the files that I am having difficulty in downloading via powershell, which you can use to run individual tests rather than the whole script:
enter link description here
And without further ado, here is the script. Thank again:
$VerbosePreference = "Continue"
$DebugPreference = "Continue"
$present = $true
$subdomain = $null
$prods = (Invoke-WebRequest "https://www.nirsoft.net/utils/index.html").links
Foreach ($thing in $prods)
{
If ($thing.Innertext -match "([A-Za-z]|\s)+v\d{1,3}\.\d{1,3}(.)*")
{
If ($thing.href.Contains("/"))
{
}
$page = Invoke-WebRequest "https://www.nirsoft.net/utils/$($thing.href)"
If ($thing.href -like "*dot_net_tools*")
{
$prodname = $thing.innerText.Trim().Split(" ")
}
Else
{
$prodname = $thing.href.Trim().Split(".")
}
$newlinks = $page.links | Where-Object {$_.Innertext -like "*Download*" -and ($_.href.endswith("zip") -or $_.href.endswith("exe"))}
# $page.ParsedHtml.title
#$newlinks.href
Foreach ($item in $newlinks)
{
$split = $item.href.Split("/")
If ($item.href -like "*toolsdownload*")
{
Try
{
Write-host "https://www.nirsoft.net$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net$($item.href)" -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
elseif ($item.href.StartsWith("http") -and $item.href.Contains(":"))
{
Try
{
Write-host "$($item.href)"
Invoke-WebRequest $item.href -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host "$($item.href)" -ForegroundColor Red
}
}
Elseif ($thing.href -like "*/dot_net_tools*")
{
Try
{
Invoke-WebRequest "https://www.nirsoft.net/dot_net_tools/$($item.href)" -OutFile "$env:DOWNLOAD\test\$($split[-1])" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
Else
{
Try
{
Write-Host "https://www.nirsoft.net/utils/$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net/utils/$($item.href)" -OutFile "$env:DOWNLOAD\test\$($item.href)" -ErrorAction Stop
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
If ($item.href.Contains("/"))
{
If (!(Test-Path "$env:DOWNLOAD\test\$($split[-1])"))
{
$present = $false
}
}
Else
{
If (!(Test-Path "$env:DOWNLOAD\test\$($item.href)"))
{
$present = $false
}
}
}
}
}
If ($present)
{
Write-Host "All of the files were downloaded!!!" -ForegroundColor Green
}
Else
{
Write-Host "Not all of the files downloaded. Something went wrong." -ForegroundColor Red
}
You have two separate issues.
For anything Defender flags, it doesn't matter if you save it to disk with this or that. You could simply add an exclusion for the directory in Defender.
The other issue is pointed out by Guenther, you need to provide a referrer at least on some of the downloads. With the following changes I was able to download them all.
$VerbosePreference = "Continue"
$DebugPreference = "Continue"
$present = $true
$subdomain = $null
$path = c:\temp\downloadtest\
New-Item $path -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
Add-MpPreference -ExclusionPath $path
$prods = (Invoke-WebRequest "https://www.nirsoft.net/utils/index.html").links
Foreach ($thing in $prods)
{
If ($thing.Innertext -match "([A-Za-z]|\s)+v\d{1,3}\.\d{1,3}(.)*")
{
If ($thing.href.Contains("/"))
{
}
$page = Invoke-WebRequest "https://www.nirsoft.net/utils/$($thing.href)"
If ($thing.href -like "*dot_net_tools*")
{
$prodname = $thing.innerText.Trim().Split(" ")
}
Else
{
$prodname = $thing.href.Trim().Split(".")
}
$newlinks = $page.links | Where-Object {$_.Innertext -like "*Download*" -and ($_.href.endswith("zip") -or $_.href.endswith("exe"))}
# $page.ParsedHtml.title
#$newlinks.href
Foreach ($item in $newlinks)
{
$split = $item.href.Split("/")
If ($item.href -like "*toolsdownload*")
{
Try
{
Write-host "https://www.nirsoft.net$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net$($item.href)" -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
elseif ($item.href.StartsWith("http") -and $item.href.Contains(":"))
{
Try
{
Write-host "$($item.href)"
Invoke-WebRequest $item.href -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="$($item.href)"}
}
Catch
{
Write-Host "$($item.href)" -ForegroundColor Red
}
}
Elseif ($thing.href -like "*/dot_net_tools*")
{
Try
{
Invoke-WebRequest "https://www.nirsoft.net/dot_net_tools/$($item.href)" -OutFile "$path\$($split[-1])" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net/dot_net_tools/$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
Else
{
Try
{
Write-Host "https://www.nirsoft.net/utils/$($item.href)"
Invoke-WebRequest "https://www.nirsoft.net/utils/$($item.href)" -OutFile "$path\$($item.href)" -ErrorAction Stop -Headers #{Referer="https://www.nirsoft.net/utils/$($item.href)"}
}
Catch
{
Write-Host $thing.href -ForegroundColor Red
}
}
If ($item.href.Contains("/"))
{
If (!(Test-Path "$path\$($split[-1])"))
{
$present = $false
}
}
Else
{
If (!(Test-Path "$path\$($item.href)"))
{
$present = $false
}
}
}
}
}
If ($present)
{
Write-Host "All of the files were downloaded!!!" -ForegroundColor Green
}
Else
{
Write-Host "Not all of the files downloaded. Something went wrong." -ForegroundColor Red
}
I'd also recommend you turn the download routine into a function that you can pass the relative URL portion so you don't have to repeat code several times.

Trouble with Powershell functions in .ps1

I'm trying to modify a working script, to make it modular. The purpose of the script is to connect to a DPM server, get the attached libraries, and inventory them. Once the inventory is done, the script marks the appropriate tapes as 'free'. The script is below
I have two problems. The first one has come and gone, as I've edited the script. When I run the script: .\script.ps1, Powershell says:
C:\it\test.ps1 : Cannot validate argument on parameter 'DPMLibrary'. The argument is null. Supply a non-null argument and try the command again.
At line:1 char:11
+ .\test.ps1 <<<<
CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,test.ps1
The second problem comes when I've just copied the functions into the shell. The Get-Libraries function works fine and returns the properties of the connected library. When I pass the parameter to Inventory-DPMLibrary, the inventory completes. When I pass the library parameter into the Update-TapeStatus function, I get an error that says
Bad argument to operator '-notmatch': parsing "slot" - Quantifier {x,y} follo
wing nothing..
At line:6 char:77
$tapes = Get-DPMTape -DPMLibrary $lib | Where {$_.Location -notmatch
<<<< " *slot *"} | Sort Location
CategoryInfo : InvalidOperation: (:) [], RuntimeException
? + FullyQualifiedErrorId : BadOperatorArgument
It looks like the $liblist parameter is null, even though the variable isn't. What gives?
Here is the script:
[CmdletBinding()]
param(
[ValidateSet("Fast","Full")]
[string]$InventoryType = 'Fast',
[string]$DPMServerName = 'server1'
)
Function Import-DPMModule {
Try {
Import-Module DataProtectionManager -ErrorAction Stop
}
Catch [System.IO.FileNotFoundException] {
Throw ("The DPM Powershell module is not installed or is not importable. The specific error message is: {0}" -f $_.Exception.Message)
}
Catch {
Throw ("Unknown error importing DPM powershell module. The specific error message is: {0}" -f $_.Exception.Message)
}
}
Function Get-Libraries {
Write-Verbose ("Getting list of libraries connected to {0}." -f $DPMServerName)
Try {
$libraries = Get-DPMLibrary $DPMServerName -ErrorAction Stop | Where {$_.IsOffline -eq $False}
}
Catch [Microsoft.Internal.EnterpriseStorage.Dls.Utils.DlsException] {
Write-Error ("Cannot connect to the DPM library. It appears that the servername is not valid. The specific error message is: {0}" -f $_.Exception.Message)
Return
}
Catch {
Write-Error ("Unknown error getting library. The specific error message is: {0}" -f $_.Exception.Message)
Return
}
Return $libraries
}
Function Inventory-DPMLibraries ($liblist) {
Foreach ($lib in $liblist) {
If ($InventoryType -eq "Fast") {
Write-Verbose ("Starting fast inventory on {0}" -f $lib)
$inventoryStatus = Start-DPMLibraryInventory -DPMLibrary $lib -FastInventory -ErrorAction SilentlyContinue
}
Else {
Write-Verbose ("Starting detailed inventory on {0}" -f $lib)
$inventoryStatus = Start-DPMLibraryInventory -DPMLibrary $lib -DetailedInventory -ErrorAction SilentlyContinue
}
While ($inventoryStatus.HasCompleted -eq $False) {
Write-Output ("Running {0} inventory on library: {1}" -f $InventoryType.ToLower(),$lib.UserFriendlyName)
Start-Sleep 5
}
If ($inventoryStatus.Status -ne "Succeeded") {
Throw ("Unknown error in inventory process. The specific error message is: {0}" -f $_.Exception.Message)
Return
}
}
}
Function Update-TapeStatus ($liblist) {
Foreach ($lib in $liblist) {
write-host ("in tapestatus. the lib is: {0}" -f $lib)
Write-Verbose ("Beginning the process to determine which tapes to mark 'free' on {0}" -f $lib)
Write-Verbose ("Getting list of tapes in {0}." -f $lib)
$tapes = Get-DPMTape -DPMLibrary $lib | Where {$_.Location -notmatch "*slot*"} | Sort Location
Foreach ($tape in $tapes) {
If ($tape.DisplayString -eq "Suspect") {
Write-Verbose ("Remove suspect tapes from the DPM database.")
Invoke-Command -ScriptBlock {osql -E -S server2 -d DPMDB_server1 -Q "UPDATE tbl_MM_ArchiveMedia SET IsSuspect = 0"} -whatif
Start-DPMLibraryInventory -DPMLibrary $lib -FastInventory -Tape $tape -whatif
}
#Run a full inventory on "unknown" tapes
#Make recyclable tapes "free"
If (($tape.DisplayString -notlike "Free*" -and $tape.DataSetState -eq "Recyclable") -or ($tape.DisplayString -like "Unrecognized")) {
Write-Output ("Marking the tape in slot {0} as free." -f $tape.Location)
Set-DPMTape $tape -Free -whatif
}
If ($tape.OMIDState -eq "Unknown") {
Write-Warning ("Unknown tape found in slot {0}. Beginning detailed inventory." -f $tape.location)
$inventoryStatus = Start-DPMLibraryInventory -DPMLibrary $lib -DetailedInventory -Tape $tape -whatif
While ($inventoryStatus.HasCompleted -eq $False) {Write-Output ("Running full inventory on the tape in slot {0} (label {1})" -f $tape.Location,$tape.Label); Start-Sleep 10}
}
}
}
}
#Calling functions
Try {
Import-DPMModule
}
Catch {
Write-Error $_
Exit
}
Try {
$liblist = Get-Libraries
}
Catch {
Write-Error $_
Exit
}
Try {
Inventory-DPMLibraries
}
Catch {
Write-Error $_
Exit
}
Update-TapeStatus $liblist
Thanks.
Your function Inventory-DPMLibraries expects a parameter ($liblist):
Function Inventory-DPMLibraries ($liblist) {
...
}
However, you don't supply that parameter when you call the function:
Try {
Inventory-DPMLibraries
}
Catch {
Write-Error $_
Exit
}
Change the above into this:
Try {
Inventory-DPMLibraries $liblist
}
Catch {
Write-Error $_
Exit
}

Resources