Active Directory Member Of Custom Pull Script - windows

I put together this script over 5 years ago now and since have forgotten what I did or how I did it...
For some context, the below script which runs from a .bat file was used to enter a user's display name and then using dsquery and dsget, along with Get-Content from PowerShell commands. About 6 months ago this script stopped working and just crashes and fails with a brief error that it getting stuck on this line to my understanding:
dsquery user forestroot -name "%lookforuser%">"%userprofile%\Desktop\usertemp.txt"
The %lookforuser% variable is set earlier in the script, see below for full source code:
#echo off
title Get AD Groups For User
set /p lookforuser=Enter Username (Surname, Firstname):
set lookforuser2=%lookforuser: =%
echo %lookforuser%
echo %lookforuser2%
dsquery user forestroot -name "%lookforuser%">"%userprofile%\Desktop\usertemp.txt"
set /p usercn=<"%userprofile%\Desktop\usertemp.txt"
dsget user %usercn% -memberof>"%userprofile%\Desktop\usertemp.txt"
Powershell -Command "(Get-Content %userprofile%\Desktop\usertemp.txt) -replace '\"CN=','' ^| Out-File -encoding ASCII %userprofile%\Desktop\usertemp.txt"
Powershell -Command "(Get-Content %userprofile%\Desktop\usertemp.txt) -replace ',OU=','*' | Out-File -encoding ASCII %userprofile%\Desktop\usertemp.txt"
for /f "delims=*, tokens=1" %%A IN (%userprofile%\Desktop\usertemp.txt) do echo %%A>>"%userprofile%\Desktop\%lookforuser2%.txt"
del "%userprofile%\Desktop\usertemp.txt"
Long story short, can anyone help me figure out what's gone on, has my parent company changed something to force this not to work, or has MS changed something that no longer allows this script to run, really stumped and not sure.
Any help would be greatly appreciated, even if you have something similar that works in Powershell
Please see error in command prompt below:
Get-Content : Cannot find path 'C:\Users\mcguirkd\Desktop\usertemp.txt' because it does not exist.
At line:1 char:2
+ (Get-Content C:\Users\mcguirkd\Desktop\usertemp.txt) -replace '"CN=', ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\mcguirkd\Desktop\usertemp.txt:String) [Get-Content], ItemNotFo
undException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Out-File : Could not find a part of the path 'C:\Users\mcguirkd\Desktop\usertemp.txt'.
At line:1 char:75
+ ... '"CN=','' | Out-File -encoding ASCII C:\Users\mcguirkd\Desktop\userte ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
Get-Content : Cannot find path 'C:\Users\mcguirkd\Desktop\usertemp.txt' because it does not exist.
At line:1 char:2
+ (Get-Content C:\Users\mcguirkd\Desktop\usertemp.txt) -replace ',OU=', ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\mcguirkd\Desktop\usertemp.txt:String) [Get-Content], ItemNotFo
undException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Out-File : Could not find a part of the path 'C:\Users\mcguirkd\Desktop\usertemp.txt'.
At line:1 char:76
+ ... ,OU=','*' | Out-File -encoding ASCII C:\Users\mcguirkd\Desktop\userte ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

Related

unpin apps from taskbar and start menu using powershell

In Windows 11, using PowerShell, I am trying to unpin Microsoft Store from the taskbar and ESPN & Spotify from the start menu.
function unpin_taskbar([string]$appname) {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() |
Where-Object{$_.Name -eq $appname}).Verbs() | Where-Object{$_.Name.replace('&','') -match 'Unpin from taskbar'} | ForEach-Object{$_.DoIt()}
}
function unpin_startmenu([string]$appname) {
((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').Items() |
Where-Object{$_.Name -eq $appname}).Verbs() | Where-Object{$_.Name.replace('&','') -match 'Unpin from Start'} | ForEach-Object{$_.DoIt()}
}
foreach ($taskbarapp in 'Microsoft Store') {
Write-Host unpinning $taskbarapp
unpin_taskbar("$taskbarapp")
}
foreach ($startmenuapp in 'ESPN', 'Spotify') {
Write-Host unpinning $startmenuapp
unpin_startmenu("$startmenuapp")
}
Microsoft Store is unpinned successfully, but the next two fail. This is the output.
unpinning Microsoft Store
unpinning ESPN
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\repo\general\rundeck\windows\unpin_windows_apps.ps1:7 char:5
+ ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
unpinning Spotify
You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\repo\general\rundeck\windows\unpin_windows_apps.ps1:7 char:5
+ ((New-Object -Com Shell.Application).NameSpace('shell:::{4234d49b ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
What I'm I doing wrong here?
are you looking at something like this by any change?
Install-Module -Name Microsoft.PowerShell.StartMenu
Import-Module Microsoft.PowerShell.StartMenu
Remove-StartAppsTaskbarPinned -AppName "Microsoft Store"
Remove-StartAppsStartMenuPinned -AppName "ESPN"
Remove-StartAppsStartMenuPinned -AppName "Spotify"
You will need to install the module "Microsoft.PowerShell.StartMenu", this is mandatory to run those commands.
You can look at the powershell gallery to find out more what this is about and how it works.

How do I download a file using windows command line without having to input a proxy password?

After looking at various stackoverflow questions, I found several ways to download a file from a command line without interaction from the user.
The only one that worked for me also works only on Windows 10 natively :
curl -sko %TEMP%\file.txt "https://some.hostname/file.txt"
But installing an external tool like wget/curl is what I want to avoid.
What didn't work for me because of proxy errors :
Command:
bitsadmin.exe /transfer "dljob" "https://some.hostname/file.txt" %TEMP%\file.txt
Error:
DISPLAY: 'dljob' TYPE: DOWNLOAD STATE: ERROR
PRIORITY: NORMAL FILES: 0 / 1 BYTES: 0 / UNKNOWN
Unable to complete transfer.
ERROR FILE: https://some.hostname/file.txt -> E:\Users\xxx\AppData\Local\Temp\file.txt
ERROR CODE: 0x80190197
ERROR CONTEXT: 0x00000005
Command:
powershell -Command "(New-Object Net.WebClient).DownloadFile('https://some.hostname/file.txt', '%TEMP%\file.txt')"
Error:
Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (407) Proxy Authentication Required."
At line:1 char:1
+ (New-Object Net.WebClient).DownloadFile('https://some.hostname/file.txt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Command:
powershell -Command "Invoke-WebRequest 'https://some.hostname/file.txt' -OutFile %TEMP%\file.txt
Error:
Invoke-WebRequest :
Authentication required
You must be authenticated to access this URL.
...
Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.1.17763.1007
At line:1 char:1
+ Invoke-WebRequest 'https://some.hostname/file.txt ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
This didn't work either :
powershell -Command "$client.Credentials = Get-Credential; $browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials; (New-Object Net.WebClient).DownloadFile('https://some.hostname/file.txt', 'file.txt')"
Error :
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
Get-Credential : Cannot process command because of one or more missing mandatory parameters: Credential.
At line:1 char:23
+ $client.Credentials = Get-Credential; $browser.Proxy.Credentials =[Sy ...
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Credential], ParameterBindingException
+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.GetCredentialCommand
The property 'Credentials' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:39
+ ... Credential; $browser.Proxy.Credentials =[System.Net.CredentialCache]: ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (407) Proxy
Authentication Required."
At line:1 char:124
+ ... redentials; (New-Object Net.WebClient).DownloadFile('https://some.hostname ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Refer to this question Access web using Powershell and Proxy
You can try something like that in Powershell and suppose that you have already created a folder named as C:\Test:
$url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
$file = "C:\Test\" + $url.Split("/")[-1]
$wb = New-Object System.Net.WebClient
$wb.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
$wb.DownloadFile($url,$file)
EDIT : 14/08/2020 #17:08
I tried this on Windows Powershell ISE and it works 5/5 :
cls
$start_time = Get-Date
$url = "https://cdn2.unrealengine.com/Fortnite%2FBoogieDown_GIF-1f2be97208316867da7d3cf5217c2486da3c2fe6.gif"
$Folder = "$Env:Temp\DownloadFolder"
# We create a SubFolder Named "DownloadFolder" in the temporary file %Temp% if it doesn't exists yet !
If ((Test-Path -Path $Folder) -eq 0) { New-Item -Path $Folder -ItemType Directory | Out-Null }
# We can get the name of the file to be downloaded from the variable $url
# $url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
# In our case the FileName will be = "googlelogo_color_272x92dp.png" or
# Fortnite%2FBoogieDown_GIF-1f2be97208316867da7d3cf5217c2486da3c2fe6.gif
$file = $Folder+ "\" + $url.Split("/")[-1]
Try
{
$wb = New-Object System.Net.WebClient
$wb.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
$wb.DownloadFile($url,$file)
# better use Invoke-Item $Folder instead of ii
Invoke-Item $Folder
Write-Output "Running Script Time taken is : $((Get-Date).Subtract($start_time).Milliseconds) millisecond(s)"
}
Catch
{
Write-Host "Error from $url" `n"Message: [$($_.Exception.Message)"] -ForegroundColor Red -BackgroundColor DarkBlue
}
This worked for me :
powershell -Command "[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebRequest]::GetSystemWebProxy(); [System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; (New-Object Net.WebClient).DownloadFile('https://some.hostname/file.txt', 'file.txt')"

Access denied on a script that should work

I have an assignment that says: "Find out how many .bat and .cmd files there are on the C drive".
I got help from a classmate, and together we came to this:
Get-Childitem -path c:\ -include *.bat,*.cmd -Recurse -ErrorAction SilentlyContinue|Measure-Object|select count
It works on his computer, but not on mine. And when I only check for .bat files it can work. And it doesn't work by putting *.bat and *.cmd in quotations
Error:
Get-Childitem : Adgang nægtet
At line:1 char:1
+ Get-Childitem -path c:\ -include *.bat,*.cmd -Recurse -ErrorAction Si ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand
And "Adgang nægtet" means Access denied :-)
Full error message:
Exception : System.UnauthorizedAccessException: Adgang nægtet ---> System.ComponentModel.Win32Exception:
Adgang nægtet
--- Slut på staksporing af indre undtagelser ---
ved System.Management.Automation.Utils.NativeDirectoryExists(String path)
ved System.Management.Automation.SessionStateInternal.IsItemContainer(CmdletProvider prov
iderInstance, String path, CmdletProviderContext context)
TargetObject :
CategoryInfo : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails :

Get file version from .exe URL-Source in PowerShell

I know how to get productversion of a file on my windows PC with powershell
(get-item -Path
'(get-item -Path 'C:\test.exe').VersionInfo.ProductVersion
but is it also possible to get the productversion from a exe file with it's URL?
(get-item -Path 'example.com/test.exe').VersionInfo.ProductVersion
No, it is not possible to get the product version from a URL.
When we use a URL it is not the direct path to access the storage server. Therefore we can not determine the version. By C path we can not access the URL Path.
I tried the shell command for Teamviewer setup URL Teamviewer version 9.X. It is not possible to get it through the URL.
PS C:\Users\israr ahmad> (get-item -Path 'download.teamviewer.com/full').VersionInfo.ProductVersion
get-item : Cannot find path 'C:\Users\israr ahmad\download.teamviewer.com\full' because it does not exist.
At line:1 char:2
+ (get-item -Path 'download.teamviewer.com/full').VersionInfo.ProductVe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\israr ...viewer.com\full:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
PS C:\Users\israr ahmad> ^C
PS C:\Users\israr ahmad> https://download.teamviewer.com/download/version_9x/TeamViewer_Setup.exe
+ (get-item -Path 'https://www.teamviewer.com/download/version_9x/Team ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (https:String) [Get-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetItemCommand
PS C:\Users\israr ahmad> (get-item -Path '../www.teamviewer.com/download/version_9x/TeamViewer_Setup.exe').VersionInfo.ProductVersion
get-item : Cannot find path 'C:\Users\www.teamviewer.com\download\version_9x\TeamViewer_Setup.exe' because it does not exist.

How to replace a path(c:\test\sqr.ini) in a .ini file using powershell

I need to replace a line in a .ini file.
Currently my script looks like this...
clear
$file= "D:\sqr.ini"
$path="c:\bin\TestPWProv_VC;"
$newpath="c:\myprod\sqlrs\test;"
get-content $file |
Foreach-Object { $_ -replace $path,$newpath } | Set-Content D:\result.ini
But this is giving me an error of
Invalid regular expression pattern: c:\bin\TestPWProv_VC;.
At line:7 char:38
+ Foreach-Object { $_ -replace <<<< $path,$newpath } | Set-Content D:\result.ini
+ CategoryInfo : InvalidOperation: (c:\bin\TestPWProv_VC;:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression
Invalid regular expression pattern: c:\bin\TestPWProv_VC;.
At line:7 char:38
+ Foreach-Object { $_ -replace <<<< $path,$newpath } | Set-Content D:\result.ini
+ CategoryInfo : InvalidOperation: (c:\bin\TestPWProv_VC;:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression
Could you offer some advice please as to why this isn't working, any help is greatly appreciated.
This is the .ini file
[INFO] PROVIDER=;
OUTPUT=c:\bin\TestPWProv_VC.ini;
TABLENAME=;
OUTPUT=c:\bin\TestPWProv_VC.ini;
DEFAULTQUERY=;
VERSION=1,50,3518,0;
TABLE=Privlib;
OUTPUT=c:\bin\TestPWProv_VC.ini;
PROVIDER=TestPWProv_VC;
TABLENAME=Privlib;
In Future please try researching before just simply asking a question, i'm sure others won't be as straightforward in the future.
$file= "D:\sqr.ini"
$newpath="c:\myprod\sqlrs\test;"
(Get-Content $path) -replace 'OUTPUT=.+', ("OUTPUT=$newpath") | Set-Content $path

Resources