Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Help please, if you can/dare!

$
0
0

Hi,

The following is a script I'm trying to put together that 

takes in a list of users from a database file and adds them as users into the active directory. Also omits duplicates. I'll comment where I know issues reside, I'm hoping you'll be kind enough to help me get it to work since PS errors don't help me much I'm a noob.

                                  

Import-Module ActiveDirectory
                               #EDIT PATH SO IT POINTS TO DB FILE \/  

#MONDAY'S CSV
$newUserList = Import-Csv C:\Users\Administrator\Desktop\dbs\Monday.csv

ForEach ($item in $newUserList){ 
  $fname = $($item.first_name)
  $lname = $($item.last_name)
  $phone = $($item.phone1)

#I know everything works up to this point.

$username=$fname+$lname.substring(0,1)

# Puts Domain name into a Placeholder.

$domain=’@csilab.local’

# Build the User Principal Name Username with Domain added to it

$UPN=$username+$domain

# Create the Displayname

$Name=$fname+” “+$lname

# Create User in Active Directory  FIRST issue resides here, PS doesn't understand the following cmdlets, it misinterprets them all as objects. I assume none of it works but I'm especially unsure of the TelephoneNumber asI just guessed on that one:

$newusers1 = (NEW-QADUSER –FirstName $fname –Lastname $lname -Telephonenumber $phone –Name $DisplayName $Name –SamAccountName $username –UserPassword ‘1NewPassword’ –UserPrincipalName $UPN –Name $Name –ParentContainer ‘csilab.local’) 

}

#THE FOLLOWING CODE TAKES USERS IN newusers1 VAR AND PUTS THEM IN AD ACTIVE USERS GROUP. I haven't tested this as script isn't even making accounts yet. However I know this code section works.


get-AdUser $newusers1 |  Move-ADObject -TargetPath 'OU=Active Users, dc=csilab, dc=local'
Add-ADGroupMember -Identity "Active Users Security" -Members $newusers1


#REMOVES ANY DUPLICATES IN AD THAT GET PAST THE SORTING CODE IN DB FILE IMPORT SECTION. I want it to both confirm same name AND phone number since it's unlikely you'll have two people with both matching. Whereas two people with the same name is possible.

(get-AdGroupMember "Active Users Security") | Remove-ADUser -Identity 'SamAccountName' 'SamTelephoneNumber' IncludeEqual -confirm:$false 



#Error checking component, ignore if it doesn't work, even with a variable I couldn't get this to work

if($error -eq 0) 
{

write-host "Thank you, the users have been added to the directory successfully." 
$b1 = Read-Host ('dddd')
}

if($error -eq 1)
{

write-host "UNEXPECTED ERROR:" -ForegroundColor Red
$error[0]
$b1 = Read-Host ('dddd')


}

#Thank you for your time... I know this is a mess.


Running a Powershell script remotely using an non-administrator user

$
0
0
I'm attempting to do the following:

- From one machine run a Powershell command impersonating a non-administrator user that will invoke a Powershell script on another machine
- I'm authenticating by CredSSP, which does seem to work.
- All machines are Windows Server 2012 Standard (non R2)
- The non privileged user is in the Remote Management Users group on the target machine


This works:

$user = "CONSO\regularjoe"
$PasswordFile = "c:\users\adminjoe\Password.txt"
$KeyFile = "c:\users\adminjoe\AES.key"
$key = Get-Content $KeyFile

$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

Invoke-Command -ComputerName REMOTESERVER02 -Authentication Credssp -EnableNetworkAccess -Credential $MyCredential -ScriptBlock { $env:username }


Output is simply:

regularjoe

------------------


However, this does not work:

$user = "CONSO\regularjoe"
$PasswordFile = "c:\users\adminjoe\Password.txt"
$KeyFile = "c:\users\adminjoe\AES.key"
$key = Get-Content $KeyFile

$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

Invoke-Command -ComputerName REMOTESERVER02.conso.com -Authentication Credssp -EnableNetworkAccess -Credential $MyCredential -ScriptBlock { c:\script.ps1 }


Output is this:

AuthorizationManager check failed.
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
    + PSComputerName        : REMOTESERVER02.conso.com


------------------

The script itself simply contains "$env:username".  I can read the file using get-filecontents (I gave it Full Control). Execution policy is Unrestricted, although I tried signing the ps1 against the domain anyways.

I expect I'm missing some sort of permission, I'm just having trouble figuring out a way to diagnose what. Would anyone have any suggestions on a method to debug this or possibly faced this challenge in the past?


Thanks!


Set-ADUser -Description not playing ball...

$
0
0

Hi all,

I'm piping an ADUser object to Set-ADUser then trying to update the -Description field like this:

Get-ADUser ** THIS PART WORKS ** | 

Where-Object { ** THIS PART WORKS, TOO ** } | 

Set-ADUser -Description "60 Days Inactive " + $_.lastlogondate + ' ' + $_.Description

This way I hope to add the string, the last logon date of the piped object & original description of the piped object to an updated description.

The problem is that I only get the 60 Days Inactive part. I've tried wrapping various parts of that line in braces, curly braces, etc... but no joy...

Does anybody know how I can get around this?

Powershell and native win32_service create method

$
0
0

Hello All!

I am having strange issue with following code from my powershell module

            [string]$Name = "VeryImportantService"
            [string]$DisplayName = "VeryImportantService"
            [string]$PathName = "PathToExecutable"
            [int]$ServiceType = 16
            [int]$ErrorControl = 2
            [string]$StartMode = "Automatic"
            [bool]$DesktopInteract = $false
            [string]$StartName = "Domain\msaaccount$"
            [string]$StartPassword = ""


            # Connect to remote server and define class
            $ConOptions = New-Object System.Management.ConnectionOptions
            $ConOptions.EnablePrivileges = $true

            $MgmtScope = New-Object System.Management.ManagementScope
            $MgmtScope.Path = "\\$MachineName\root\cimv2"
            $MgmtScope.Options = $ConOptions

            $MgmtPath = New-Object System.Management.ManagementPath
            $MgmtPath.ClassName = "Win32_Service"

            $Service = New-Object System.Management.ManagementClass($MgmtScope, $MgmtPath, $null)

            # Create service
            $Service.create($Name, $DisplayName, $PathName, $ServiceType, $ErrorControl, $StartMode, $DesktopInteract, $StartName, $StartPassword)

PoSH run as administrator in both cases.

The issue is - when i run that set of commands pasting one by one - voila - all works fine.

When i run function from module .. i am getting exception from create method:

22

The account under which this service runs is either invalid or lacks the permissions to run the service.

Anyone knows why this is happening?

Michał

Edit:

Executing:

$Service = get-wmiobject -ComputerName $MachineName win32_service | where {$_.name -eq $Name}      
$Service.Change($null,$null,$null,$null,$null,$null,$StartName,$null,$null,$null)

Works just fine from within the script - so this is only invoking create method issue.

import certificate error use powershell 3.0

$
0
0
$remoteDirPath = '\\192.168.1.10\D$\cert\cert'
$pfxpath = '\\192.168.1.10\D$\cert\cert\apiclient_cert.p12'
$password = '1266682321'
$StoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]'LocalMachine'
$StoreName = 'My'

$user = "domain\admin"
$passwd = "password"
net use $remoteDirPath $passwd /user:$user

Add-Type -AssemblyName System.Security
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificate.Import($pfxpath, $password, 'Exportable')

$Store = New-Object system.security.cryptography.X509Certificates.x509Store($StoreName, $StoreLocation)
$Store.Open('ReadWrite')
$Store.Add($certificate)
$Store.Close()

Code as above,local normal operation, but use winrm ...Tip a mistake

Exception calling "Import" with "3" argument(s): "Access denied.

At line:16 char:1\n+ $certificate.Import($pfxpath, $password, \'Exportable\')

thanks.

Powershell Scheduled task only performing 2 foreach

$
0
0

We have a scheduled task which calls a PS1.  The PS1 using a foreach to add DNS records into InfoBlox.  The scheduled task will start but only add 2 of the DNS records in the CSV.  If the PS1 is run manually it works fine.  Scheduled Task and PS1 below:

<?xml version="1.0" encoding="UTF-16"?><Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Date>2015-07-29T14:36:30.133207</Date><Author>privilagedAccount</Author><Description>Add DNS Hosts records in InfoBlox</Description></RegistrationInfo><Triggers><TimeTrigger><StartBoundary>2015-07-29T14:52:00</StartBoundary><Enabled>true</Enabled></TimeTrigger></Triggers><Principals><Principal id="Author"><UserId>US\us-svcibwebapi</UserId><LogonType>Password</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>false</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><IdleSettings><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><RunOnlyIfIdle>false</RunOnlyIfIdle><WakeToRun>false</WakeToRun><ExecutionTimeLimit>PT2H</ExecutionTimeLimit><Priority>7</Priority></Settings><Actions Context="Author"><Exec><Command>powershell</Command><Arguments>-file G:\DNSWebAPI\DNS_ADD\InfoBlox_Add_Host.ps1</Arguments></Exec></Actions></Task>


##############################################################################
#July 2015

#v1.0 - To bulk add/delete/change infoblox records
##########################################################



# import-module activedirectory

#############################
# basic auth header encoding
#############################
$user = "admin"
$pass = "abc123"
$pair = "$($user):$($pass)"
$encauth = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($encauth)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }
$cred = New-Object System.Management.Automation.PSCredential($user,$pass)


$date = Get-Date -Format MMddyyyy
$csvinput = import-csv "G:\DNSWebAPI\DNS_ADD\input\$date-add.csv"
$url = "https://10.60.24.4/wapi/v1.0/record:host"
$logfile = "G:\DNSWebAPI\Logs\$date-ADDs.log"
$tomorrow = (get-date).AddDays(1).ToString("MMddyyyy")


[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}


foreach ($item in $csvinput)
{
Invoke-WebRequest -Uri $url -Headers $headers -Body (ConvertTo-Json @{ipv4addrs= @( @{ipv4addr=$item.ipaddress} ); name=$item.fqdn; view=$item.view}) -Method Post -ContentType "application/json"
}


New-Item G:\DNSWebAPI\DNS_ADD\input\$tomorrow-add.csv -type file -Value "ipaddress,fqdn,view" -Force





#############################################################
# Powershell to JSON format test for array and hash table
#############################################################
#$body = @{ name="test.local"; ipv4addrs= @( @{ipv4addr="1.1.1.1"} )}
#
#$body = @{ipv4addrs= @( @{ipv4addr="1.1.1.1"} )}
#
#$body = @{ipv4addrs= @( @{ipv4addr="1.1.1.1"} ); name="test.local"}
#
#$body= @{view="default";name="test.local";ipv4addrs= @(@{ipv4addr="1.1.1.21"})}
#
#$JSON = $body | ConvertTo-Json
#
#$JSON

Cannot understand or figure out why the scheduled task will only create 2 of the CSV inputs then hang. Any help greatly appreciated!

-Paul


Attempt to convert foreach > function / script block > runspaces

$
0
0

Hi everyone,

As many on this forum, I too am trying to make an inventory script.

The inventory is meant for approx. 500 machines.

At first I created a simple script to check the class Win32_OperatingSystem.

After a while I started to query AD, a lot of WMI classes, and some file or update related items.

The script was taking a very long time to complete all checks.

So I've build some checks like: ping, WMI and AD to combine to make the script as light as possible.

After that, I've added some try/catch statements for error handling.

Then I used jobs for each WMI query to let them run at the beginning of the script.

Also a friend of me pointed out that its better to use foreach, instead of foreach-object.

In my quest for speed, I've also converted the plain script to a function.

At the moment my script will run about an hour for 385 machines.

After searching the web I found out that its possible to use workflows, or runspaces to make the jobs run parallel.

But since I'm using jobs I don't think that parallel workflows will work.

So my next option is to use runspaces.

I've tried to use several guides but none seem to work.

I've got 3 arrays (script scope) to store the collected data, and 1 with the computer names.

I currently start the function as follows:

foreach ($Computer in $Computers)

{

Invoke-Command -ScriptBlock ${function:Scan-System} -ArgumentList $Computer

}

Now my question is: How can I convert my script to use runspaces?

Thanks in advance.

Method "NewTriggerByOnce" not found

$
0
0

Here is what I'm trying to do (add trigger to scheduled task on remote machine):

Invoke-Command -ComputerName BETA -ScriptBlock {Set-ScheduledTask -TaskPath '\Monitor\' -TaskNam
e 'Off' -Trigger (New-ScheduledTaskTrigger -At 16:40 -Once)}

which results into:

Method "NewTriggerByOnce" not found+ CategoryInfo          : ObjectNotFound: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [New-ScheduledTaskT
   rigger], CimException+ FullyQualifiedErrorId : HRESULT 0x80041002,New-ScheduledTaskTrigger+ PSComputerName        : BETA

Cannot validate argument on parameter 'Trigger'. The argument is null or empty. Provide an argument that is not null or
 empty, and then try the command again.
    + CategoryInfo          : InvalidData: (:) [Set-ScheduledTask], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationError,Set-ScheduledTask+ PSComputerName        : BETA

wondering may be someone have same issue?


Get-Process behavior

$
0
0

Hi,

Using Get-Process with -ComputerName against multiple computers, I noticed if one of the computers list fails the entire cmd will fail, I mean, does not return the results for the computers that are available... 

I now that i can solve this with a foreach loop, but I was wondering if this behavior is the expected one!?

Thanks .


Issues with ContainerImage cmdlets

$
0
0

I am investigating the use of containers, so I had to use the ContainerImage cmdlets to get the pieces.  I ran into a couple issues, and figured this forum might be the right place to post them.

The instructions for obtaining the image (https://msdn.microsoft.com/en-us/virtualization/windowscontainers/management/manage_images?f=255&MSPPError=-2147217396#installing-base-os-images) say to use the command Install-ContainerImage -Name <name>  When I issue that command, it goes off and seems to process it by displaying a status bar showing progress across the top of the window, but then it errors out with:

Install-ContainerOSImage : The term 'Install-ContainerOSImage' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\ContainerProvider\0.5.2\ContainerProvider.psm1:245 char:5
+     Install-ContainerOSImage -WimPath $Destination `
+     ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Install-ContainerOSImage:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

There is not option to specify a destination path for the Install-ContainerImage cmdlet, according to its help, shown below:

SYNTAX
    Install-ContainerImage [-Name] <string> [[-Version] <string>] [[-SearchKey] <string>]  [<CommonParameters>]

I find it interesting that the error message says there is a -WimPath parameter, but the help doesn't.

I then used the Save-ContainerImage cmdlet with a -Destination parameter value of C:\Temp.  It returned this error:

Please provide file name with path.
At C:\Program Files\WindowsPowerShell\Modules\ContainerProvider\0.5.2\ContainerProvider.psm1:586 char:9
+         throw "Please provide file name with path."
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Please provide file name with path.:String) [], RuntimeException
    + FullyQualifiedErrorId : Please provide file name with path.

I entered a name for the file and it was fine.  I guess I was expecting it to work like a Copy command where it would default to the source file name, which is what I wanted, because I did not know the source file name.

So I then tried with a destination of C:\Temp\*.*.  It came back and asked me:

Overwrite File
Do you want to overwrite the existing file: c:\Temp\*.* ?
[Y] Yes  [N] No  [?] Help (default is "Y"):

Not quite what I would have expected.  Maybe my expectations are a little high to expect parameters that are asking for paths to work similar to a Copy command.

As stated at the beginning, I was able to get things to work, but I thought I should report this someplace.


. : | : . : | : . tim

Pulling Custom Attributes - Null Values still picked up

$
0
0

We use the Exchange Custom Attributes in AD to track when to disable an out of office or forwarding when requested.  So I want to report on this and pull all Mailboxes with a value in custom attributes 7,8, and 9.  I want to grab it all first but $null and "" does not work and just bizarre.  It still pulls back empty values.  The short code snip is not difficult and very beginner and should work.  Very frustrating.  Any insight from someone would be helpful if it is beyond this type of code I require it to be laid out like I am five.  Yeah i know this just does not come naturally and I have scripted with this on and off for a couple of years now.

#Load Exchange Module
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

#Get All Mailboxes that are type "User"
$AllMailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox | ? {($_.CustomAttribute7 -ne $null) or ($_.CustomAttribute7 -ne "")}



Copy and paste entire row in Excel

$
0
0

Hey Guys/Gals,

I was wondering if anyone knew how to cut an entire row in excel and paste it in a different row.  Say, cut row 250 and paste it in Row 100.

What I have doesn't quite work.  The Cutting does, but not the pasting.  What I get with the paste is

Method invocation failed because [System.__ComObject] doesn't contain a method named 'paste'.

Here is the code so far:

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Open("C:\ReportProject\Test.xlsx")
$ws = $wb.Sheets.Item(13)

$rows = $ws.UsedRange.Rows.Count

[void]$ws.Cells.Item($count,1).EntireRow.insert()
$OldRange = $ws.Cells.Item(250,1).EntireRow
[void]$OldRange.Select()
[void]$OldRange.Cut()
[void]$ws.Cells.Item(100,1).EntireRow.paste()


$wb.Close()
$xl.Quit()
Thanks in advance!! :)

Replace Two commas with one

$
0
0

I'm trying to convert some text file to csv format. I have some lines with two commas in them that would translate to shifting a column in csv.

my code doesn't seem to replace the two commas with a single one, it is as follows:

Get-Content -path $outPath|
ForEach-Object {$_ -replace ",,","," } |
Out-File -filepath $outPath

Please Help me

Thank You

 

Question on get-aduser and properties

$
0
0

I am fairly new to PowerShell and have gotten quite a bit of help browsing the Forums and asking questions.

I have been working on getting Properties from get-aduser, and its bafflilng to me on the below examples.

To find if a user account is enabled I have used:

get-aduser -identity USERNAME | %{$_.enabled}

   This will return True or False

To check if a user account is Locked I found this will return True or False

(get-aduser -identity USERNAME -Properties LockedOut).LockedOut

Why is this?  When I try

get-aduser -identity USERNAME | %{$_.LockedOut}, it returns blank

Subsequently if I try

(get-aduser -identity USERNAME -Properties Enabled).Enabled, it returns blank.

Problem with SQL from Powershell

$
0
0

I have copied function Invoke-SQL :

function Invoke-SQL ($sqlCommand, $dataSource, $database){
   
    $connectionString = "Data Source=$dataSource; " +
            "Integrated Security=SSPI; " +
            "Initial Catalog=$database"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    $connection.Close()
    write-host $sqlcmd                         # To check what I'm feeding MSSQL with
    #$dataSet.Tables | out-file fejl.txt   # Used to export results from queries 
   
}

sqlcmd = "SET var = var + '-X' WHERE var=003996-2013

I get :

Exception calling "Fill" with "1" argument(s): "Conversion failed when converting the nvarchar value '000001-2013' to d
ata type int."
At C:\test.ps1:26 char:18
+     $adapter.Fill <<<< ($dataSet) | Out-Null
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

What is my problem - I don't try to "touch" this record : var =  '000001-2013'


scripting new-mailboximportrequest

$
0
0

New-mailboximportrequest needs a couple of parameters including a mailbox, and the path to a PST

I created an array like this

$upn = get-aduser -filter {UserPrincipalName -like "*@teststeve.com"} | foreach-object {$_.name}

Then created an array like this

$arr = get-childitem -path "\\2-exchcas1\c$\psts\" | where-object {$_.extension -eq ".pst"} | foreach-object {$_.name} |sort-object {$_.name}

These both work fine.

Id like to export the two to a csv file so I get

user1, user1.pst
user2, user2.pst
user3, User3.pst

then I can spot check the upns and psts match up correctly.

After I manipulate the file so everything is correct, Id like to read it back in and run

New-mailboximportRequest –mailbox $upn –filepath $path

Any suggestions? Ive been trying to work with hash tables and 2d arrays but, Im sure Im making it harder than it has to be.

Thanks.

GUI - No parameters displayed after pressing OK

$
0
0

HI,

The following code is expected to output 3 strings typed in the created GUI - $x,$y,$z.

Actually nothing is displayed after pressing ENTER. Any ideas why ?

thanks

========================================================================

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Data Entry Form"
$objForm.Size = New-Object System.Drawing.Size(300,400) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter"){
    $x=$objTextBox1.Text
$y=$objTextBox2.Text
$z=$objTextBox3.Text
$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(50,300)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$x=$objTextBox1.Text
$y=$objTextBox2.Text
$z=$objTextBox3.Text
$objForm.Close()})
$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(200,300)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,20) 
$objLabel1.Size = New-Object System.Drawing.Size(280,20) 
$objLabel1.Text = "Enter the DIR to search recursively:"
$objForm.Controls.Add($objLabel1) 

$objTextBox1 = New-Object System.Windows.Forms.TextBox 
$objTextBox1.Location = New-Object System.Drawing.Size(10,40) 
$objTextBox1.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($objTextBox1) 

$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(10,60) 
$objLabel2.Size = New-Object System.Drawing.Size(280,20) 
$objLabel2.Text = "Enter file extention:"
$objForm.Controls.Add($objLabel2) 

$objTextBox2 = New-Object System.Windows.Forms.TextBox 
$objTextBox2.Location = New-Object System.Drawing.Size(10,80) 
$objTextBox2.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($objTextBox2) 

$objLabel3 = New-Object System.Windows.Forms.Label
$objLabel3.Location = New-Object System.Drawing.Size(10,100) 
$objLabel3.Size = New-Object System.Drawing.Size(280,20) 
$objLabel3.Text = "Enter string to filter out:"
$objForm.Controls.Add($objLabel3) 

$objTextBox3 = New-Object System.Windows.Forms.TextBox 
$objTextBox3.Location = New-Object System.Drawing.Size(10,120) 
$objTextBox3.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($objTextBox3) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

"RESULT = " + $x + $y + $z

Use a PowerShell script as generic script for failover cluster

$
0
0

Hello,

it is possible to use a VB script as generic script resource in a failover cluster: https://msdn.microsoft.com/en-us/library/aa372846%28v=vs.85%29.aspx

Is it possible to do the same with powershell? And if yes is there a sample somewhere available.

Thanks,

Daniel

Power shell script works on one server but not the other....

$
0
0

Here is the Power shell script.

#******Creating Users from a csv*************************
Import-Module activedirectory
#**********LOads the csv file for reading****************
$csv = Import-Csv "File.csv"

#*******Makes a user for every person listed in the csv**
ForEach ($User in $csv){
#The list of things that will be read from the csv
$FirstName = $user.first
$LastName = $user.last
$OU = $user.ou
$pass = $User.ID
$Newusername = "$FirstName.$LastName"

New-ADUser –Name "$FirstName $LastName" –SamAccountName "$Newusername" -description "User2015" -UserPrincipalName "$Newusername@domain.ns" -GivenName "$FirstName" -Surname "$LastName" –Department "$OU" –Path "ou=$OU,ou=students,dc=domain,dc=ns" –Enabled $true -AccountPassword (ConvertTo-SecureString "$pass" -AsPlainText -force) -PassThru
}
Write-Host "Done"

It works on one server that is 2008 R2 and has service pack one i created another server that's 2008 R2 and i get this error...

 

Import-Csv : Cannot open file "C:\Users\jwelshman\file.csv".
At C:\Users\Desktop\New folder\addusers.ps1:4 char:18
+ $csv = Import-Csv <<<<  "2015Students.csv"
    + CategoryInfo          : OpenError: (:) [Import-Csv], FileNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
At C:\Users\Desktop\New folder\addusers.ps1:15 char:309
+ New-ADUser –Name "$FirstName $LastName" –SamAccountName "$Newusername" -description "user2015" -UserPrincipa
lName "$Newusername@domain.NS" -GivenName "$FirstName" -Surname "$LastName" –Department "$OU"  –Path "ou=$OU,ou=st
udents,dc=domain,dc=ns" –Enabled $true -AccountPassword (ConvertTo-SecureString <<<<  "$pass" -AsPlainText -force)
 -PassThru
    + CategoryInfo          : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands. 
   ConvertToSecureStringCommand

Any ideas would be great.




Functions alway loaded

$
0
0

Hi People,

In our company we created a few functions to do stuff in active directory and exchange. To store does functions we created a .psm1 file and load it all the time we need to use does functions. 

The problem is that it takes a time to always load the funtions. I want does functions always loaded. 

Is is possible to always have does modules loaded in the system, or work with sessions you can connect to, so i dont gave to load them all the time?

Thanks,

Michael


Viewing all 21975 articles
Browse latest View live