Importing a variable from AD to map a drive - powershell-4.0

I'm trying to export the homepath information from AD into a powershell script and map that information. I can pull the information from AD but I cant turn that information into a variable to map the drive. The script looks at a users AD information and is supposed to map a drive with that information if the drive isn't already mapped, then it does a robocopy of data to that drive.
I tried setting the $homedrive variable but I dont think I'm doing it correctly
Get-ADUser -Identity $env:username -Properties HomeDirectory |
Select Homedirectory
$homeDirectory = (Get-AdUser -filter {name -eq "$env:username"} -properties *).HomeDirectory
$networkpath = "P:\"
$pathExists = Test-Path -Path $networkpath
If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("P:",$homeDirectory)
}
robocopy C:\Users\$env:Username\desktop P:\desktop /sec /E /R:3
robocopy C:\Users\$env:Username\favorites P:\favorites /sec /E /R:3
I want the $homedrive variable to be whats listed in AD for the user so I can map that drive. When I run the script it just tells me whats in AD but doesnt store the information in the variable.

so i ended up writing it to a csv file then pulling it from the same csv file and it worked
Get-ADUser -Identity $env:username -Properties HomeDirectory |
Select -Property HomeDirectory |
Export-CSV 'c:\temp\homedirectory.csv' -NoTypeInformation -encoding UTF8
Import-csv "C:\temp\homedirectory.csv" | foreach-object {
$homeDirectory = $_.homedirectory
}
$networkpath = "P:\"
$pathExists = Test-Path -Path $networkpath
If (-not ($pathExists)) {
(new-object -com WScript.Network).MapNetworkDrive("P:",$homeDirectory)
}
robocopy C:\Users\$env:Username\desktop P:\desktop /sec /E /R:3
robocopy C:\Users\$env:Username\favorites P:\favorites /sec /E /R:3

Related

Get Information from Shares with Information to create the folders in a new Domain

so I am helping with the migration of the data to another company which bought the first one, for which I have to export Foldernames, User-Names and Permissions in an .csv File.
I have a working Skript but it seems to be taking an awful long amount of time. It worked with a few shares which don´t have too much folders, but now I have run into scripts running for multiple hours(100.000+ Folders).
From the smaller shares I know it gives me the correct information but it is taking to long for the amount of shares left.
$FolderPath = dir -Directory -LiteralPath "\\?\UNC\Server\Share" -Recurse -Force
$Report = #()
Foreach ($Folder in $FolderPath) {
$Acl = Get-Acl -Path $Folder.FullName
foreach ($Access in $acl.Access){
$Properties = [ordered]#{
'FolderName'=$Folder.FullName
'AD Group or User'=$Access.IdentityReference
'Permissions'=$Access.FileSystemRights
'Inherited'=$Access.IsInherited
}
$Report += New-Object -TypeName PSObject -Property $Properties
}
}
$Report | Export-Csv -path "C:\Filepath\export.csv" -Delimiter ";" -Encoding UTF8
Am I missing a simple thing why its taking so long or did I just mess up completely?
I just don´t seem to find it.
Any help would be very much appreciated
Thanks in Advance
Michael
As commented, building the $Report array by adding new items to it with += is a very time and memory consuming way.
It is way quicker to let PowerShell do the collecting like below.
Also, Get-ChildItem (alias dir) can be slow, especially when dealing with many subfolders, so using RoboCopy could be a faster alternative for this.
# get the list of directory full path names
# Get-ChildItem can be slow, so maybe try Robocopy as alternative
# $Folders = (Get-ChildItem -Directory -LiteralPath "\\?\UNC\Server\Share" -Recurse -Force).FullName
$Folders = (robocopy "\\Server\Share" NULL /L /E /NP /NFL /XJ /NC /NJH /NJS /R:0 /W:0) -replace '^\s*\d*\s*'
$Report = foreach ($Folder in $Folders) {
$Acl = Get-Acl -Path $Folder
foreach ($Access in $Acl.Access){
[PsCustomObject]#{
'FolderName' = $Folder
'AD Group or User' = $Access.IdentityReference
'Permissions' = $Access.FileSystemRights.ToString()
'Inherited' = $Access.IsInherited
}
}
}
$Report | Export-Csv -Path "C:\Filepath\export.csv" -Delimiter ";" -Encoding UTF8

Search for registry key path

please, could you help me with searching for registry path?
I am trying to find path of REG_BINARY with name 00036601 in HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles\Outlook\20424cec73cea54ab3d011f91bf036b2
I have problem because last folder(20424cec73cea54ab3d011f91bf036b2) in path is different on every laptop. Cannot find any working solution with REG QUERY in cmd or powershell.
I know how to find it in known path or list all subkeys, but failed to filter one value.
So i want to get output like: key name 00036601 found in HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles\Outlook\20424cec73cea54ab3d011f91bf036b2
EDIT: sorry for my english, maybe i am notz describing it correctly, please, could you look on image?
Regedit
I am looking for string name 00036601 - marked in image. Thanks for help
EDIT2: i found way how to do it with cmd "REG QUERY HKCU\SOFTWARE\Microsoft /s /f 00036601"
But not with powershell...
You can search the registry with PowerShell. I do not have the same registry path as you have.
Get-ChildItem -Path HKCU:\Software\Microsoft\Office\16.0 `
-Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.PSChildName -eq '00036601' }
If you must do it from a cmd.exe shell:
powershell -NoLogo -NoProfile ^
"Get-ChildItem -Path HKCU: -Recurse -ErrorAction SilentlyContinue | " ^
"Where-Object { $_.PSChildName -eq '00036601' }"
EDIT: that was never going to get there.
This works on my machine to find the IM enabled setting.
$r = Get-ChildItem -Path 'HKCU:/Software/Microsoft/Office/' -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Property -eq 'EnablePresence' }
(Get-ItemProperty -Path $r.PSPath).EnablePresence
Please try this on your machine.
$r = Get-ChildItem -Path 'HKCU:/Software/Microsoft/Office/' -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Property -eq '00036601' }
(Get-ItemProperty -Path $r.PSPath).'00036601'

Remote PowerShell, Local Variables, and ForEach

I am looking to get a file inventory of a specific file on some reomote servers using PowerShell and Invoke-Command. I want to gather the info and then export as CSV to a specific folder.
I have a couple of local variables for the date (to append to the file name) and a list of servers. I understand that I need to use the -ArgumentList parameter to pass the local variables, but the syntax is confounding me with the ForEach aspect involved (I am not a programatically minded person). Here is what I have:
$FileServerList = "Server01","Server02","Server03"
$DateTime = Get-Date -Format s
ForEach ($FileServer in $FileServerList) {
Invoke-Command -ComputerName $FileServer -ScriptBlock {
Get-ChildItem -Path "D:\PathtoFile\*" -Recurse -Include "index.html" | Select-Object Name,DirectoryName,CreationTime,LastWriteTime`
| Export-Csv -Path C:\Users\Public\Documents\Data_$DateTime.csv -NoTypeInformation -Verbose
}
}
Should I save the script block itself in a variable or go another route? Any guidance is appreciated.
Since Invoke-Command is not called with a separate credential, I assume that the user in current Powershell session has credentials to access servers.
For remote locations, you can use UNC paths:
$FileServerList = "Server01","Server02","Server03"
$DateTime = Get-Date -Format s
ForEach ($FileServer in $FileServerList) {
Get-ChildItem -Path "\\$FileServer\d$\PathtoFile\*" -Recurse -Include "index.html" |
Select-Object Name,DirectoryName,CreationTime,LastWriteTime |
Export-Csv -Path \\$FileServer\c$\Users\Public\Documents\Data_$DateTime.csv -NoTypeInformation -Verbose
}

Getting ACL info using PowerShell and Robocopy due to PathTooLongException

I'm trying to get a listing of all permissions on some network folders using PowerShell. Unfortunately I'm encountering the dreaded PathTooLongException so I'm attempting to use Robocopy as a work around. However I'm a complete novice with PowerShell so was hoping for a little help. The easiest command I've come up with is
Get-Childitem "S:\StartingDir" -recurse | Get-Acl | Select-Object path,accestostring | Export-Csv "C:\export.csv"
That works and does what I want except the exception I'm getting. How would I insert Robocopy into this statement to bypass the exception? Any thoughts?
First, create a batch file, such as getShortFilename.bat, with the following lines:
#ECHO OFF
echo %~s1
This will return the short filename of the long filename passed to it. The following script will use that to get the short filename when Get-Acl fails due to a long path. It will then use the short path with cacls to return the permissions.
$files = robocopy c:\temp NULL /L /S /NJH /NJS /NDL /NS /NC
remove-item "c:\temp\acls.txt" -ErrorAction SilentlyContinue
foreach($file in $files){
$filename = $file.Trim()
# Skip any blank lines
if($filename -eq ""){ continue }
Try{
Get-Acl "$filename" -ErrorAction Stop| Select-Object path, accesstostring | Export-Csv "C:\temp\acls.txt" -Append
}
Catch{
$shortName = &C:\temp\getShortFilename.bat "$filename"
$acls = &cacls $shortName
$acls = $acls -split '[\r\n]'
#create an object to hold the filename and ACLs so that export-csv will work with it
$outObject = new-object PSObject
[string]$aclString
$firstPass = $true
# Loop through the lines of the cacls.exe output
foreach($acl in $acls){
$trimmedAcl = $acl.Trim()
# Skip any blank lines
if($trimmedAcl -eq "" ){continue}
#The first entry has the filename and an ACL, so requires extra processing
if($firstPass -eq $true){
$firstPass = $false
# Add the long filename to the $exportArray
$outObject | add-member -MemberType NoteProperty -name "path" -Value "$filename"
#$acl
# Add the first ACL to $aclString
$firstSpace = $trimmedAcl.IndexOf(" ") + 1
$aclString = $trimmedAcl.Substring($firstSpace, $trimmedAcl.Length - $firstSpace)
} else {
$aclString += " :: $trimmedAcl"
}
}
$outObject | add-member -MemberType NoteProperty -name "accesstostring" -Value "$aclString"
$outObject | Export-Csv "C:\temp\acls.txt" -Append
}
}
Notes:
The string of ACLs that is created by Get-Acl is different from the on created by cacls, so whether that's an issue or not...
If you want the ACL string to be in the same format for all files, you could just use cacls on all files, not just the ones with long filenames. It wouldn't be very difficult to modify this script accordingly.
You may want to add extra error checking. Get-Acl could of course fail for any number of reasons, and you may or may not want to run the catch block if it fails for some reason other than the path too long.

Powershell Control Windows Search through command line

I am trying to write a powershell script that will disable indexing on some drives but keep it activated on some others (ex: C:).
Has anyone done it before ?
Thanks
try this, (not tested):
function Disable-Indexing{
Param($Drive)
$obj = Get-WmiObject -Class Win32_Volume -Filter "DriveLetter='$Drive'"
$indexing = $obj.IndexingEnabled
if("$indexing" -eq $True){
write-host "Disabling indexing of drive $Drive"
$obj | Set-WmiInstance -Arguments #{IndexingEnabled=$False} | Out-Null
}
}
use:
disable-indexing "c:"

Resources