Huge enthusiasm for Powershell but facing several problems with variables in ForEach loop and functions


hello, first post here please forgive me week english , beginner questions. have huge enthusiasm for learning powershell , use daily basic task if mange write 400+ lines active directory script, have huge headache when comes to functions, foreach loop , pipeline. don't have "linux bash" background when comes scripting let me describe my problem.

i've created 2 functions:

function cutstringtolength{
param(
    [string]$string,
    [int32]$length
    )
    if($string.length -gt $length){
        $results=$string.remove($length)
        }else{
        $results=$string.padleft($length)
        }
    return $results -replace '\s+', ''
}


and

function cleanup {
(((((($args -replace "ä", "au") -replace "ü", "ue") -replace "ö", "oe") -replace "Ä", "au") -replace "Ü", "ue") -replace "Ö", "oe") -replace "ß", "ss"
}

the "cleanup" function working without problems when use in ps comandline this:

cleanup "äüöß"

now, want use them in foreach loop:

$userobjects = import-csv c:\users\administrator\desktop\0.csv # example: http://pastebin.com/raw.php?i=bz6fs07e
foreach ( $userobject in $userobjects ) {
#assign content variables
$filenachname = (get-culture).textinfo.totitlecase(($userobject.nachname).tolower())
$filevorname = (get-culture).textinfo.totitlecase(($userobject.vorname).tolower())

$usr_ln = $filenachname
$usr_fn = $filevorname

$usr_ln2 = cleanup "$usr_ln"
$usr_fn2 = cleanup "$usr_fn"

$usr_ln2 = cutstringtolength $usr_ln2 6
$usr_ln2 = $usr_ln2.toupper()
$usr_fn2 = cutstringtolength $usr_fn2 2
$usr_fn2 = $usr_fn2.toupper()
$usr_login = $usr_ln2 + $usr_fn2

# output content screen
write-host $usr_ln $usr_fn2 has login: $usr_login
}

the "cutstringtolength" function work expect "cleanup" function simple don't work. have no idea why. can me understand going on ?

easy way cut string:

function get-substring{ 	param( 		[system.string]$inputobject, 		[system.int32]$length 	) 	($inputobject.tochararray() | select-object -first $length) -join '' }

if object string don't have put between brackets, string :)

and problem encoding csv file

i used code , worked

(get-content file.txt -encoding string) -split ',' | % {cleanup $_}



Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Group Policy Event ID 1058 Error Code 1326 (The user name or password is incorrect)

Suspicious event log Event ID: 4905

DCOM received error "2147746132" from...