Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
When I import the AD module I get problems because the domain controller isn't running AD Web services.

I'm trying to get a home lab set up ASAP so I can start learning how it's all supposed to really work.

Adbot
ADBOT LOVES YOU

vanity slug
Jul 20, 2010

You need to run AD Web Services to use the AD PowerShell module, yeah (and ADAC).

Drighton
Nov 30, 2005

Scikar posted:

I might not be understanding right (I'm not great with coding jargon) but I think Get-Acl is already one step ahead of you. The object you get as output is just a copy of the ACL, if you make any changes to it then you still need to apply them to a target with Set-Acl (or equivalent) afterwards.

E: Just realised that part doesn't actually use Get-Acl, whoops! I'll see if I can't find the right script I was thinking of.

Sorry for responding so late, but I was out last week and forgot about this. It would help if I explained my intentions better. The script is meant to verify the validity of existing permissions of a folder, then correct, remove, or add access control entries as necessary (or as requested by the user).

I noticed the code to do this was all over the place so thought I'd create a function for both add and remove. I don't think I'll mess with this much more though, since I can easily accomplish this by making the ACL a global variable. Just trying to do things the right way, is all.

Update: Figured out the problem. While I can't explain exactly why it works this way, I can at least move on.

code:
Function ModifyACE([ref]$objACL) {
$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule ("domain\user", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")

$objACL.AddAccessRule($objACE) #Error: Method invocation failed because [System.Management.Automation.PSReference] doesn't contain a method named 'AddAccessRule'.

$objACL.Value.AddAccessRule($objACE) #This works
}

Drighton fucked around with this message at 17:36 on Oct 23, 2013

evil_bunnY
Apr 2, 2003

code:
#load CLI args (This should be a filename) into array
$a = (get-content groups.txt)
#get list of users, show account and display name
ForEach-Object ($user in $a) {Get-ADGroupMember -Identity $user | get-aduser -properties * | select SamAccountName, displayname}
code:
PS C:\scripts> .\Get-ADGroupUserList.ps1 groups.txt
At C:\scripts\Get-ADGroupUserList.ps1:4 char:23
+ ForEach-Object ($user in $a) {Get-ADGroupMember -Identity $user | get-aduser -pr ...
+                       ~~
Unexpected token 'in' in expression or statement.
At C:\scripts\Get-ADGroupUserList.ps1:4 char:22
+ ForEach-Object ($user in $a) {Get-ADGroupMember -Identity $user | get-aduser -pr ...
+                      ~
Missing closing ')' in expression.
At C:\scripts\Get-ADGroupUserList.ps1:4 char:28
+ ForEach-Object ($user in $a) {Get-ADGroupMember -Identity $user | get-aduser -pr ...
+                            ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken
Is it not reading the file to an array? File's just group names on each line.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
You have a syntax error. Don't use foreach-object, just use foreach

Or do this:

ForEach-Object $a {Get-ADGroupMember -Identity $_ | get-aduser -properties * | select SamAccountName, displayname}

adaz
Mar 7, 2009

By the way all the problems people have getting the AD cmd-lets to work (making sure you are on right version, right module is install on right computer, right things enabled on X) are pretty much the reason I'm going to say, again, you're better off learning the Directory Services .net namespace and how to use it in powershell as it's always available and it's all the AD-cmdlets are using in the background anyway.

Buller
Nov 6, 2010
Can someone help me set up multiple windows paths in powershell?

As far as i understand now i can only have 1 which i use for python.

Id like to be able to have some more so that i can use ipython and pip without having to change my enviorment path all the time.

Wicaeed
Feb 8, 2005
Quick question regarding this script (a friend wrote it and I tweaked it):

http://pastebin.com/RRxeK3CF

If I wanted to return only servers that match a certain part of the results on the 'logonserver' portion, or the 'NTP Source' result, how could I do that?

adaz
Mar 7, 2009

Wicaeed posted:

Quick question regarding this script (a friend wrote it and I tweaked it):

http://pastebin.com/RRxeK3CF

If I wanted to return only servers that match a certain part of the results on the 'logonserver' portion, or the 'NTP Source' result, how could I do that?


If I understand what you want correctly something like this would be the fastest way but ughhhh

code:
echo $DomainComputers | foreach { $ip = "$_" ; (Services $ip)} | where-object {$_. -match "Hostname:ComputerName"}

The spiffy way is to re-write the thing to return you objects and filter off the objects

code:

Function Get-ComputerInfo
{param([string]$ip,[boolean]$reachable)
       #1.) Create our output object.
       $computerInfo = New-Object –TypeName PSObject
       $computerInfo | Add-Member –MemberType NoteProperty –Name IPReachable –Value $reachable
   
   if($reachable) {

       #2.) Get Hostname/Logged in User
       $computer = gwmi -query "Select name, username from win32_computersystem" -ComputerName $ip -ErrorVariable err -ErrorAction SilentlyContinue
       $loggedOnUsers=  @()
       foreach($objItem in $computer) {
            $loggedOnUser = New-Object -TypeName psObject
            $loggedOnUser | Add-Member -MemberType NoteProperty -Name Hostname -Value $objitem.name
            $loggedOnUser | Add-Member -MemberType NoteProperty -Name Username -Value $objitem.username
            $loggedOnUsers += $loggedOnUser
       }
       $computerInfo | add-member -MemberType NoteProperty -Name LoggedONUsers -Value $loggedOnUsers

       #3.) Retrieving logon server.
       $computerinfo | add-member -membertype NoteProperty -name logonserver -value $(get-item env:logonserver)

       #4.) Getting DHCP Info
        $DHCPInfo = gwmi -query "select dhcpenabled,ipaddress,dhcpserver from win32_networkadapterconfiguration where ipenabled='true'" -Computer $ip -EV Err -EA SilentlyContinue 
        $dhcpValues = @()
        foreach($objItem in $DHCPInfo) {
            $dhcpValue = New-Object -TypeName psObject
            $dhcpValue | Add-Member -MemberType NoteProperty -Name DHCPEnabled -Value $objitem.DhcpEnabled
            $ipAddys = @()
            foreach($ipVal in $objItem.IPADdress) {
                $ipAddys += $ipval
            }
            $dhcpValue | Add-Member -MemberType NoteProperty -Name IPAddress -Value $ipAddys
            $dhcpValue | Add-Member -MemberType NoteProperty -Name dhcpServer -Value $objItem.DHCPServer
            $dhcpValues += $dhcpValue

        }
        $computerinfo | add-member -MemberType NoteProperty -Name dhcpValues -Value $dhcpValues

        #5.) Get NTP providers 
        $computerInfo | add-member -membertype NoteProperty -name ntpsType -value $(w32tm /query /computer:$ip /configuration | ?{$_ -match 'Type:'})


        return $computerInfo   

   }else {
    Return $computerInfo
   }

}

Function Ping-Computer{
param([string]$ip)

    $ping = New-Object System.Net.NetworkInformation.Ping
    $Reply = $ping.send($ip)
    if ($Reply.Status -eq "Success") {
        Return $true
    }else {
        Return $false
    }

}
	

$DomainComputers = (gc Computers.txt)

$allComputerInfos = @()
foreach($computer in $DomainComputers) {
    
    $allComputerInfos += Get-ComputerInfo -ip $computer -reachable $(Ping-Computer -ip $computer)
    
  
}

# example filters:
$allComputerInfos | where-Object {$_.ntpsType -match "Type: NT5DS (Local)"}

$allComputerInfos | where-object {$_.logonserver -match "computernamehere"}

CLAM DOWN
Feb 13, 2007

nesaM killed Masen
Does Powershell 3.0 have any new ways to handle the pagefile? I have some code that uses the old WMI method (ie. get-wmiobject Win32_PageFileusage | select AllocatedBaseSize) but I'd love it if they added a new way to handle this.

ephphatha
Dec 18, 2009




Finally got off my arse and wrote a script to rename folders dumped from my camera into something more suitable for long term storage.

The camera makes a number of folders with the naming pattern "<three digit autoincrementing number><last digit of year>MMDD" and I want to rename them to the pattern "YYYYMMDD_<index padded to 3 digits>".

The following works, but is there anything I should be doing different?

code:
$folders = Get-ChildItem -Name | Where-Object {$_ -match "^\d{8}$"}

if ($folders) {
    echo "The following folders will be renamed:"
    echo $folders

    foreach($folder in $folders) {
        $baseName = "201$($folder.Substring(3))";
        echo "Looking for folders starting with $baseName"
        $existingFolders = Get-ChildItem -Name "$($baseName)_*"
        
        if ($existingFolders -is [array]) {
            echo "Found the following folders matching the above pattern:"
            echo $existingFolders
            $existingFolders = $existingFolders[-1]
        } #Intentional retest
        
        if ($existingFolders -is [string]) {
            echo "Latest index appears to be $($existingFolders)."
            $index = $existingFolders.Substring(9,3) -as [int]
            $index++
            echo "Using $index as the next index."
        } else {
            echo "Found no folders with that name pattern, starting from 001."
            $index = 1
        }
        
        $newName = "$($baseName)_{0:D3}" -f $index
        
        echo "The folder formerly known as $folder will be renamed $($newName)."
        Rename-Item $folder $newName
    }
} else {
    echo "Nothing to do, no folders appear to need renaming."
}

Scikar
Nov 20, 2005

5? Seriously?

adaz posted:


The spiffy way is to re-write the thing to return you objects and filter off the objects

code:
       $computerInfo = New-Object –TypeName PSObject
       $computerInfo | Add-Member –MemberType NoteProperty –Name IPReachable –Value $reachable

If you're using PSv3 you can score more points by doing this with PSCustomObject, which is about 30x faster:

code:
$computerInfo = [PSCustomObject]@{ Name = IPReachable; Value = $reachable }
If you're not using v3 then you can still do this:
code:
$computerInfo = New-Object PSObject -Property @{ Name = IPReachable; Value = $reachable }
which is only 4x as fast but still an improvement. I don't usually go to too much trouble to optimise my scripts because if you have something you run once a week and it takes 2 minutes instead of 1 you aren't gaining much. But creating objects in order to use the pipeline properly is something that a lot of scripts will do thousands of times (and it's a good habit to get into so you can chain all of your stuff together), so it can make a massive difference.

EAT THE EGGS RICOLA
May 29, 2008

I've been messing around with Desired State Configuration and it seems pretty awesome so far, how have you all been finding it/using it?

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin
I'm trying to write a command to restart a service on a remote PC but I get a return value of 5, access denied.

I've tried it by using WMI and with Stop-Service.

I'm posting from a phone so it's hard to post the code.

The Electronaut
May 10, 2009

adaz posted:

Each SQL query is unique? How many are there? Is there any reason why you need to exclude the leftmost column as opposed to just not querying for that data?

To get started what I'd use is a function I wrote long ago and my normal method of avoiding export-CSV's... eccentricities. Yes it would be a glorious world where we could just pipe the DataSet to export-csv and it'd handle it gracefully... unfortunately that world doesn't exist.

code:
############
# SQL Data #
############
function Get-SqlData
{
param(
[parameter(Mandatory=$true,HelpMessage="SQL Server to connect to.")]
[string]$serverName,

[parameter(mandatory=$true,HelpMessage="SQL DB")]
[string]$databaseName,

[parameter(mandatory=$true,HelpMessage="SQL Query to run.")]
[string]$query
)
    $SQLDT = New-Object "System.Data.DataTable"
    $connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
    $da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
    [void]$da.fill($sqlDt)
    return $sqlDt
}
So as an example for how get-SqlData works and how you'd export it to CSV

code:

# Execute our SQL Query and store the data in the $queryResults variable.
$queryResults = Get-SqlData -server sqlserver -database databasename -query "select firstname,lastname from employees where lastname like 'd%'"

# Initialize our array which we will use to store then data and then
# to pipe to Export-CSv
$exportTable = @()

# add the result sets to the array
foreach($result in $queryResults) {
   # shorthand method of creating an object with two properties called 
   # firstname, lastname.
   $OutObj = "" | select firstname,lastname
   # set the properties on each object.
   $outObj.Firstname = $result.firstname
   $outObj.lastName = $result.Lastname
   #add the Object to our array for later exporting
   $exportTable += $outObj
}
# Export out to CSV
$exportTable | export-Csv C:\blah\blah.csv -noTypeInformation

With dates and so forth look at Get-Date and system.datetime class, should have all the functions you need for formatting your date/time string however you want.

Holy quote from the dead.

This has problems (thank you though for posting this, I've had in the back of my mind a common thing I've been wanting to get automated but have been scratching my head how to do it, load the SQL modules in, leverage sqlcmd, etc.) with queries that take longer than 30 seconds to run.

I re-wrote it:

code:
function Get-SqlData
{
	param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
		[string]$query=$(throw 'query is required.'))
 
	Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
 
	$SqlConnection = New-object System.Data.SqlClient.SqlConnection
	$SqlConnection.ConnectionString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI"
	$SqlCommand = New-Object System.Data.SqlClient.SqlCommand
	$SqlCommand.CommandText = "$query"
	$SqlCommand.Connection = $SqlConnection
	$SqlCommand.CommandTimeout = 0
	$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
	$SqlAdapter.SelectCommand = $SqlCommand

	$dt = New-Object "System.Data.DataTable"
	[void]$SqlAdapter.fill($dt)
	return $dt
}

Bloodborne
Sep 24, 2008

I just picked up the morelunches.com Powershell3 in a month of lunches book. It's supposed to be a good starter for somebody with no experience in scripting languages. I guess I'll see if I can put something together at the end, like maybe automatically making a distribution list or something that I'm sure should be easy.

Djimi
Jan 23, 2004

I like digital data
I spent about 30+ minutes on the internet and did a few searches in the cavern here for figuring out my attempt to find/replace with regex matching and using the found pattern in the replacement to create links to other files. The only matches / replacements I need are the beginning of the line in an html table page, so I should be able to anchor with ^.

I don't know powershell that well, and I'm probably worse in regex

A line in the file to find/replace would be:
code:
<tr><td>something</td>...more html...<td></td>s etc...blah blah
<tr><td>something-else</td>....blah blah blah more <td></td>s
<tr><td>SOME-OTHER-THING ....blah blah blah more <td></td>s
So I found a page that said I could basically do something like line 6 below which could be line an inline replacement like sed -i
code:
$html= (gc .\file.html)
$new_html= .\new_file.html
$open="<tr><td><a href=`""
$mid="`"</a>"
$ext="_page.log"
$close="</td>"
$link = [regex]::replace($html, "^<tr><td>(\w+)</td>", '$open $1 $mid $1 $ext $close');
Nothing is matching and if I can get it to match, I'm pretty sure I need to have an OR section for the cases where there is the hyphen(s) on the matching/replacing line.

Thanks in advance :tipshat:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Djimi posted:

I spent about 30+ minutes on the internet and did a few searches in the cavern here for figuring out my attempt to find/replace with regex matching and using the found pattern in the replacement to create links to other files. The only matches / replacements I need are the beginning of the line in an html table page, so I should be able to anchor with ^.

I don't know powershell that well, and I'm probably worse in regex

A line in the file to find/replace would be:
code:
<tr><td>something</td>...more html...<td></td>s etc...blah blah
<tr><td>something-else</td>....blah blah blah more <td></td>s
<tr><td>SOME-OTHER-THING ....blah blah blah more <td></td>s
So I found a page that said I could basically do something like line 6 below which could be line an inline replacement like sed -i
code:
$html= (gc .\file.html)
$new_html= .\new_file.html
$open="<tr><td><a href=`""
$mid="`"</a>"
$ext="_page.log"
$close="</td>"
$link = [regex]::replace($html, "^<tr><td>(\w+)</td>", '$open $1 $mid $1 $ext $close');
Nothing is matching and if I can get it to match, I'm pretty sure I need to have an OR section for the cases where there is the hyphen(s) on the matching/replacing line.

Thanks in advance :tipshat:

For the record, parsing HTML with regexes is not recommended. Something like the HTML Agility Pack would make your life much easier.

Djimi
Jan 23, 2004

I like digital data

Ithaqua posted:

For the record, parsing HTML with regexes is not recommended. Something like the HTML Agility Pack would make your life much easier.


Oh, I didn't know I was asking about something that cannot be done that easily. I figured I just don't know the syntax at all.
I've outlined all the cases and the structure is guaranteed. I'd really rather not have to install anything.

Should I be making a match function and then do the replacing in a for-each loop? Thanks again.

Frag Man
Sep 2, 2011
So I just started this program to become an IT-technician (Rough swedish translation) and completely new for this year is that we get to learn Powershell! I've never done something like this before and am really confused about how to write a script with parameters that might or might not be used in the syntax.

My assignment is to write a script that makes a backup of a directory. The first two parameters are the source and the destination. Destination is optional to write, if it isnt specified the copy will be placed in a default directory, say C:\Backup in this case.
The third parameter that might be used is if the copy will be reclusive or not, and the fourth is to specify what files to copy from the source using wildcards.

Pseudocode looks something like this: Backup.ps1 $Source $Destination $Reclusive? $Specifics?

My problem is how I make Powershell not confuse one parameter for another if one is left out. Like if I wrote $Reclusive and $Specifics but left out $Destination.

Djimi
Jan 23, 2004

I like digital data

Frag Man posted:

Pseudocode looks something like this: Backup.ps1 $Source $Destination $Reclusive? $Specifics?

My problem is how I make Powershell not confuse one parameter for another if one is left out. Like if I wrote $Reclusive and $Specifics but left out $Destination.
I'm not an expert (see my post above :v: ) — but here's a tutorial on passing parameters.
And I think you mean recursive not reclusive - but maybe you do — I know some /dev/null files that never go anywhere.

Frag Man
Sep 2, 2011
Thanks for the tip! If I understand correctly, I can disable positional parameters but then I have to write out each parameter in the syntax If I want another value. I think this will work for my assignment.

To clarify, the $Recurse (Formerly $Reclusive, my bad) parameter is supposed to tell powershell if the backup is done with subfolders and the whole subdirectory with files, or only the files from the folder specified is copied.

The $Specifics is more of a filter that I can specify to only take backups of certain kind of files using wildcards.

Example: PS C:\. backup.ps1 C:\folder\ C:\Backup\ -recurse Yes -specifics *.txt

Would copy all the .txt-files and the subfolders from C:\Folder\ to c:\Backup\. That's at least what it's supposed to do. I'm currently using If-operators to specify what parameter-values that change the outcome of the script, but that's kinda cumbersome and I feel like there should be an easier way.

AreWeDrunkYet
Jul 8, 2006


It may be against the spirit of the assignment, but you can just take those parameters and pass them over to robocopy to avoid reinventing the wheel.

Fenrisulfr
Oct 14, 2012

Frag Man posted:

Example: PS C:\. backup.ps1 C:\folder\ C:\Backup\ -recurse Yes -specifics *.txt

A small thing, but you can make $Recurse a [switch] parameter, which is True if -Recurse is present and false if it isn't.

Frag Man
Sep 2, 2011

AreWeDrunkYet posted:

It may be against the spirit of the assignment, but you can just take those parameters and pass them over to robocopy to avoid reinventing the wheel.

That's exactly what we aren't allowed to do. Our teacher has several times stated that some methods arent allowed, such as robocopy or using arraylists. Usually after some students have spent several hours writing functions using those methods. If someone could clarify why some methods wouldnt be allowed I'd be vary happy, cause our teacher sure as hell won't.

The script is taking form, but we have an unfortunate kink to iron out. Our script is taking backups of the directory, but the backups have different form depending on if they are recursive or not. When the copy is recursive the sourcefolder is fully copied into the folder named BACKUP_$Getdate. But when we arent using a recursive copy-item the folder is not copied, instead the files in the source directory are dropped in the BACKUP_$Getdate directory. I'm not quite sure which form of directory structure is correct for the assignment, but I think it's either way as long as the result of running the script is consistent.

I'll just post the script here if that's okay. It's not complete, we still need to add several things.

Backupscript posted:


Param ($path, $to="C:\backup\", $re = "nej", $wild="nej")

$date=get-date -format "yyyy-MM-dd_HH-mm-ss"
$TestPath=test-path -path $path

If(-not $TestPath)
{
Write-host "No sourcedirectory stated"
Break
}

$NyMapp=New-Item -path $to\"backup_$date" -itemtype directory
$to2=$NyMapp
Write-host "Directory created at $to2"


If($re -eq "ja" -and $wild -ne "nej")
{
copy-item -filter $wild -path $path -Recurse -destination $to2
}

ElseIf($re -eq "ja")
{
copy-item -path "$path" -Recurse -destination $to2
}


Elseif($Wild -ne "nej")
{
#$a=Get-ChildItem -path $path "$wild"
copy-item "$path\$wild" -destination $to2
}


Else
{
#copy-item -path $path -destination $to
#$a=get-childitem -path $path;
copy-item "$path\*" -destination $to2
}

Get-childItem -path "$to2" -Recurse | rename-item -NewName {$_.name +".bak"}
Get-ChildItem -path "$to2" -Recurse | Out-File $to\Backup_$date.log
Get-ChildItem -path "$to2" -Recurse | Out-File $Path\Backup_$date.log


Edit: Mixing up reclusive and recursive AGAIN!

Frag Man fucked around with this message at 13:56 on Nov 22, 2013

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
A few things:
  • When posting code on the forums, use code blocks, not quote blocks
  • $re should be a [switch] parameter, and also be given a descriptive name.
  • When creating paths, use "join-path" instead of string concatenation. This will take care of things like joining "C:\Foo" and "Bar". Without join-path, you'd get "C:\FooBar". With join-path, you'd get "C:\Foo\Bar"

The specific problem you're having is because when you do, for example:
copy-item C:\Foo C:\Bar", you're telling PowerShell to copy the ENTIRE "C:\Foo" folder into "C:\Bar", so the resulting folder structure is "C:\Bar\Foo". If you do copy-item C:\Foo\* C:\Bar", it'll copy the contents of C:\foo.

Dr. Arbitrary
Mar 15, 2006

Bleak Gremlin

Djimi posted:

And I think you mean recursive not reclusive - but maybe you do — I know some /dev/null files that never go anywhere.

I hate seeing mixups like this because they always seem get stuck in my head and I want to use them. A few years ago a co-worker had used 'enchanted' in place of 'enhanced.' For the rest of my life I'll probably have a nagging urge to use the phrase "enchanted mode."

vanity slug
Jul 20, 2010

PowerShell automagically does things.

AreWeDrunkYet
Jul 8, 2006

Frag Man posted:

That's exactly what we aren't allowed to do. Our teacher has several times stated that some methods arent allowed, such as robocopy or using arraylists. Usually after some students have spent several hours writing functions using those methods. If someone could clarify why some methods wouldnt be allowed I'd be vary happy, cause our teacher sure as hell won't.

Robocopy isn't a method, it's a separate Windows program, and it already does everything the assignment is asking you to do (and then some). It was more of a joke suggestion, since you wouldn't really be learning or doing anything - just accepting parameters and passing them on in the order/format robocopy requires.

Not sure why you shouldn't use an arraylist, but I also don't really see how it would help. Maybe to prevent you from going in an unnecessary direction?

Swink
Apr 18, 2006
Left Side <--- Many Whelps
I'm pulling a telephone number from AD and trying to convert it to a string, so I can use substring to get the last three numbers.


code:
$number = get-aduser -Identity [i]username[/i] -properties telephonenumber | select telephonenumber

$number = $number.tostring()
At this point the variable is empty. Why is that? What's the correct way to get that number as a string?


Edit - Solved it already.

$number = get-aduser -Identity username -properties telephonenumber | select -expandproperty telephonenumber

Swink fucked around with this message at 23:35 on Nov 26, 2013

Dravs
Mar 8, 2011

You've done well, kiddo.
Ugh, I need help with a script.

Quite simply, I am trying to output a list of users who are in one group, yet not in another.

I can do Get-ADUser -Filter {(memberof -ne "group name 1")} and it will output AD accounts which are not in that group.

I then tried Get-ADUser -Filter {((memberof -ne "Group name 1") -AND (memberof -eq "group name 2"))} and it does not output anything. In fact the -eq switch does not seem to work, if I run with just that I see nothing.

Is there anyway to do what I am trying to do? I have been banging my head against this for a couple of hours and the above it the closest I have got.

The Electronaut
May 10, 2009

Dravs posted:

Ugh, I need help with a script.

Quite simply, I am trying to output a list of users who are in one group, yet not in another.

I can do Get-ADUser -Filter {(memberof -ne "group name 1")} and it will output AD accounts which are not in that group.

I then tried Get-ADUser -Filter {((memberof -ne "Group name 1") -AND (memberof -eq "group name 2"))} and it does not output anything. In fact the -eq switch does not seem to work, if I run with just that I see nothing.

Is there anyway to do what I am trying to do? I have been banging my head against this for a couple of hours and the above it the closest I have got.

I'd honestly use a LDAP query here.

Dravs
Mar 8, 2011

You've done well, kiddo.
My powershell knowledge is almost non-existent so I am picking this up as I go along. How do you do an LDAP query?

The Electronaut
May 10, 2009

Dravs posted:

My powershell knowledge is almost non-existent so I am picking this up as I go along. How do you do an LDAP query?

http://forums.somethingawful.com/showthread.php?action=showpost&postid=374711474

See adaz's post there, instead of the filter being userworkstations, you'd want a (memberof=CN=Group,OU=Users,DC=Domain,DC=com) plus a !(memberof=CN=Group,OU=Users,DC=Domain,DC=com) to NOT out the membership of that other group. You'll want to get the CNs for your two groups.

I'm doing this from a phone, sorry for being brief.

psylent
Nov 29, 2000

Pillbug
Hi guys, I'm slowly working my through CBT Nuggets intro to Powershell so forgive any ignorance on my part.

I'm trying to build a script that prompts for a username and once it has does three things:
1. Changes the description to "Terminated - $DATE" in the format YYYY.MM.DD
2. Moves the object to a particular OU
3. Strips the object of all group memberships

I've got the commands for the steps 1 and 2, except for adding the date in automatically, I'll need help there - but stripping the object is a bit of a mystery at this point.

Any pointers will be much appreciated.

code:
$username = read-host "Enter user name"
Get-ADUser $username| Move-ADObject -TargetPath 'OU=Users,OU=Disabled,OU=Administration,OU=Infrastucture,DC=MYCOMPANY,DC=local'

Set-ADUser $username -Description

vanity slug
Jul 20, 2010

You're looking for something like
code:
$date = Get-Date -Format yyyy.MM.dd
Set-ADUser -Identity $Username -Description "Terminated - $date"

psylent
Nov 29, 2000

Pillbug
Here's the finished product:

code:
#get UserName
$termuser = read-host "Enter user name"

#Exports Group Memberships to CSV
$target = "\\SERVER\users$\_archived\" + $termuser + ".csv"
Get-ADPrincipalGroupMembership $termuser | select name | Export-Csv -path $target
write-host "* Group Memberships archived to" $target

#Move to "Disabled Users" OU
Get-ADUser $termuser| Move-ADObject -TargetPath 'OU=Users,OU=Disabled,OU=Administration,DC=COMPANY,DC=local'
write-host "* " $termuser "moved to Mailboxes To Be Archived"

#Change Description to "Terminated YYYY.MM.DD - CURRENT USER"
$terminatedby = $env:username
$termDate = get-date -uformat "%Y.%m.%d"
$termUserDesc = "Terminated " + $termDate + " - " + $terminatedby
set-ADUser $termuser -Description $termUserDesc 
write-host "* " $termuser "description set to" $termUserDesc

#removes from all distribution groups
$dlists =(Get-ADUser $termuser -Properties memberof | select -expand memberof)
foreach($dlist in $dlists){Remove-ADGroupMember $termuser -Identity $dlist -Confirm:$False}
write-host "* Removed from all distribution and security groups"

#moves home drive to archive
move-item \\SERVER\users$\$termuser \\SERVER\users$\_archived\$termuser
write-host "* Home Drive archived to \\SERVER\users$\_archived\$termuser"

#disable user
Disable-ADAccount -Identity $termuser

write-host "*** " $termuser "account has been disabled ***"

Son of Thunderbeast
Sep 21, 2002
Hey guys, I'm a fairly new scripter, been teaching myself PoSh for a few weeks or so at this point.

I got voluntold for a project that I now feel may have been a bit above my paygrade and have now spent waaaaaay too long trying to get this to work.

The goal: to take an input CSV file and re-create all the directories with the necessary NTFS rights, as well as a network share with permissions.

My (main) problem: As far as I know, the script works great up until the part where it has to actually set the share permissions; all the technet articles and resources I've looked up haven't helped me figure out what I'm doing wrong, probably because I'm too inexperienced to recognize where the problem is.

Oh yeah and another really stupid loving oversight I didn't think about until today; I've been testing this locally and apparently I have PoSh v3, and the server has PoSh v2. I'm about to test it there and see what errors I get.

I might be new to IT in general but I'm pretty certain that ^^THAT^^ was loving dumb.


And I know I have a LOT of other problems in my code; all input is welcome but mainly I just wanna get my script to work.

Code:
http://pastebin.com/FVPkAmQL

sample csv:
http://pastebin.com/3nCdWSk3

Being that this is the first time I've asked for help like this I'm also pretty sure I'm leaving out a bunch of crucial info; I'll be here all day tho.

Thanks in advance for any help, also for this thread! It's been a great resource.

EDIT: Oh yeah there's a LOT of probably-hilarious bullshit in there from me trying to track what variables were carrying where and when and other debugging things, just warning y'all

Son of Thunderbeast fucked around with this message at 00:33 on Dec 31, 2013

vanity slug
Jul 20, 2010

Well, what are the errors you're getting? :)

Adbot
ADBOT LOVES YOU

Fryedegg
Jan 13, 2004
Everquest killed my libido (and my cat). 8(

Son of Thunderbeast posted:

Oh yeah and another really stupid loving oversight I didn't think about until today; I've been testing this locally and apparently I have PoSh v3, and the server has PoSh v2. I'm about to test it there and see what errors I get.

First thing I would do is upgrade the server to v3, if possible.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply