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

Server2003, enable / disable user login via powershell

$
0
0
Hi all,

Newbie, in Africa for short time only and probably haven't done all the homework I should have.

Unix and OO background but just learning powershell.

I need to be able to enable / disable local user accounts on a local server in a school; no clusters, pretty much stand-alone.  I presume if I can get the user object it has a member / method for enabling / disabling, but I don't understand how to get the user object.  In particular, I don't understand the two-character abbreviations used in front of params to queries.

If I bring up active directory users and computers, what I see is:

techna-school

  ...

  Tech/na school

      Students

The users I want to enable/disable are members of the "Students" group above, and for RDP / security purposes are members of the "Learners" group.  The server is not in any "official" (i.e. DNS recognized) domain, just gets net access as a normal user via dialup and DHCP.

I'm guessing I need something kinda like the following to get at the user objects, but I haven't a clue what the "ou", "dc", or anything else needed are supposed to be as I don't have an MS server background.

$learners = [ADSI] "LDAP://ou=Learners,dc=techna-school"

Any help would be much appreciated.

Thanks,

Gary

How to close active PowerShell Window, upon script completion.

$
0
0

Hi All,

I searched through the forums, and didn't find this specific question.  My apologies if the answer is out there.

I've written a script that launches a PS1 via a shortcut on my desktop.  This is a GUI app, so the next thing I did was figure out how to hide the shell during it's execution.  The final part thats missing is how to exit the hidden shell window upon completion.

Currently, I'm unhiding the window so that I can type "EXIT" manually.  This is fine for me, but for other users who may use this script, I'd prefer that they never see the command window, except maybe very briefly during the launch of the script.

The only way I've found to do this involves querying PS for the Window Title, and then executing Stop-Process; however the script in quesion is an Exchange 2010 script which will not let me modify the Window Title from "Machine: SERVERNAME.Domainname.com".

If anyone has any ideas, or needs any more info - I would appreciate any help you can give me.

Thanks!

Jay

Is it possible to add a property using variable in variable name?

$
0
0

I want to query for a list of virtual machines within a folder, then create a menu of the host names using forms.  Since the list of machines is subject to change, I want to build the list each time the script is run, rather than build off a static list. 

For each virtual machine I need to create the list of variables below:

$hostnameX = New-Object System.Windows.Forms.checkbox
$hostnameX.Location = New-Object System.Drawing.Size(10,20)
$hostnameX.Size = New-Object System.Drawing.Size(100,20)
$hostnameX.Checked = $true
$hostnameX.Text = "Type"
$hostnameX.Controls.Add($hostnameX)

The location and size values need to be incremented but I think I can figure that part out.

I can use New-Variable to generate the initial variable. But I receive errors using the same method to try to create a new property for the variable.

$VMS = Get-Cluster MyCLUS | Get-vApp "My vApp" | Get-VM | Select Name,PowerState | Sort Name

For ($i=0; $i -lt ($VMS.count); $i++)
{

$VMS[$i].Name
$VMGUEST = "$($VMS[$i].Name)" -replace("-","")

New-Variable "CB$VMGUEST" "New-Object System.Windows.Forms.checkbox"
New-Variable "CB$VMGUEST.Location" "New-Object System.Drawing.Size(10,20)"

In the above, $CBVMGUEST1 =  New-Object System.Windows.Forms.checkbox which is what I want,  but $CBVMGUEST1.Location is not set.

Is there way to add a property using a variable in the variable name?  Or any other suggestions on how to tackle this issue?


Powershell Commands

$
0
0

Hi I bought the book Active Directory Management by Richard Siddaway.  I have been trying to create a new user with Powershell.  Creating a new AD user with Powershell 

The first two lines work ok

$secpass = Read-Host "Password" -AsSecureString

which prompts for password  *********

second line is New-ADUser -Name "GREEN Dave" -SamAccountName dgreen

which works but, when I enter the next command         -UserPrincipalName "dgreen@contoso.com"  -AccountPassword $secpass 

 it gives me the error message, '-UserPrincipalName' is not recognised as a cmdlet 

on the previous lines I have created the user and the password but this part of the command is failing?

thanks in advance for any help!!

Check (out of a .csv) if OU exists in AD. If 'no' create. If 'yes' move on.

$
0
0

[CmdletBinding()]
param(
[Parameter (Mandatory=$True,
HelpMessage="What must be the name of the main OU?")]
[String]$Prime_OU
)

$Domain = (Get-ADDomain | Select -ExpandProperty DNSRoot).split(".")
$Domain1 = $Domain[0]
$Domain2 = $Domain[1]

If (([ADSI]::Exists("LDAP://OU=$Prime_OU,DC=$Domain1,DC=$Domain2")) -eq $false) `
{New-ADOrganizationalUnit -Name $Prime_OU -Path "DC=$Domain1,DC=$Domain2" -ProtectedFromAccidentalDeletion $false
Write-Host "OU $Prime_OU made" -ForegroundColor Green}
Else {Write-Host "OU $Prime_OU already exists and will be used" -ForegroundColor Red}
$Root = [ADSI]"LDAP://OU=$Prime_OU,DC=$Domain1,DC=$Domain2"

Import-Csv "GebruikerslijstChoco.csv" -Delimiter ';' |
ForEach-Object {
If (([ADSI]::Exists("LDAP://$_.Path")) -eq $false) `
{New-ADOrganizationalUnit -Name $_.Department -Path $Root -ProtectedFromAccidentalDeletion $false 
Write-Host "OU $_ made" -ForegroundColor Green}
Else {Write-Host "Processing" -ForegroundColor Green}
}

I can't get the last part of the code (starting from 'ForEach-Object) to work. Any suggestions?

How do I get authority to add logon script in GPO?

$
0
0

I have created a powershell script to map network drives at logon.  The script resides in a folder on the AD server.  In following an how-to example, I have created the powershell script with executes correctly mapping all of the drives.  I want this to execute for anyone who logs onto the domain from any workstation so the user drives are available.  The How-To steps through creating the GPO and adding the script.  However, when I try to copy the script from the source folder to the sysvol logon folder, I get an error that I need permission so the process fails.  Does the script need to reside in the logon folder in order to execute?  I have tried to change the permissions on the sysvol share but still get the message.  Any ideas?

Making a specified window active

$
0
0

I'm trying to make an internet explorer window active when I run a script that runs every hour but it only works if it runs as a single action. I've tried  it on windows scheduler and in a timed a loop in powershell and nothing works. I read somewhere that its to do with a security measure on windows.

Is there any other way to accomplish this?

$locationurmatch = "xxxxxxxx"

###get opened ie window 
$app = new-object -com shell.application
$ie = $app.windows() | where {$_.Type  -eq "HTML Document" -and $_.LocationURL -match "$locationurmatch"} | select -last 1
Set-ForegroundWindow ((Get-Process -Name iexplore)| where {$_.Type  -eq "HTML Document" -and $_.LocationURL -match "$locationurmatch"}

Please post solution and not just point me to a link as I'm really bad with powershell and reading code specs.


 

Set folder permissions by Powershell

$
0
0

Hello there.

I'm trying to set permissions to a shared folder by Powershell.

I used the following script:

$Acl = Get-Acl "C:\MySharedFolder"
$Ar = New-Object  system.security.accesscontrol.filesystemaccessrule("username","FullControl","Allow")
$Acl.SetAccessRule($Ar)
Set-Acl "C:\MySharedFolder" $Acl

So, what it happens is:

1. The permission doesn't work;

2. This permission appears in the "Security" tab of the folder as "Special permissions".

Do I need to do something else?

Is there a special way to set permissions to shared folders?

Thanks in advance.

Regards


Lucas Gustavo





Invoke-command -scriptblock not working as intended

$
0
0

Hi all, I've got a piece of code, I'm trying to install a program on a remote server yet the start script part isn't working. here is my piece of code..

#Variables
$computername = Get-Content 'F:\Kuliah\Ide TA\TAku\Coba\Comp-List.txt'
$sourcefile = 'F:\INSTALLER\npp.6.3.Installer.exe'
#This section will install the software 
#$mycreds = Get-Credential
foreach ($computer in $computername) 
{
	$destinationFolder = "\\$computer\C$\Temp"
	#This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist it will create it.
	if (!(Test-Path -path $destinationFolder))
	{
		New-Item $destinationFolder -Type Directory
	}
	Copy-Item -Path $sourcefile -Destination $destinationFolder
	Invoke-Command -ComputerName $computer -ScriptBlock {Start-Process 'c:\temp\npp.6.3.Installer.exe'}
}

the copy part works, and properly copies my program. yet the invoke command isn't working on the remote server. though it works completely fine if run at my own pc.


why can't I make a Youtube Account??

$
0
0
I'm trying to make a Youtube account. But every time when i have to verify my Email account it keeps on saying "

Microsoft account is unavailable from this site, so you can't sign in or sign up. The site may be experiencing a problem.

You can sign in or sign up at other Microsoft sites and services, or try again later at this site." what's worng with Microsoft servers???

Run PowerShell script from C# writing to input pipe

$
0
0

Hello,

I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:

1. Get text output from the script (easy, many examples available)

3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit

4. If output does contain that prompt, just let it exit by itself without sending any input

Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.

I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?

I have tried using PS object model like so:

using (Pipeline pipeline = runspace.CreatePipeline()) { Command command = new Command(scriptPS, true, true);   pipeline.Commands.Add(command);   pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);   pipeline.Input.Write("\n");   Collection<PSObject> psresults = pipeline.Invoke();

   //...

But I get an error because the script prompts:

"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows."

I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.

Please help!


Delete a specific folder with Powershell

$
0
0

I need to carry out the following action with Powershell, could someone assist me with this.

Within the H:\ drive I want to find the folder called "old" and first list it to see where it is and then a second script to find it and remove.  The reason I need a powershell script for this is because under H:\ are all the user home folders so essentially all users should have the folder "old" nested in their redirected folders.

Hope that makes sense

SSH HostKey Fingerprint

$
0
0

Hi I am using the code below for SFTP upload to a SFTP server using WinSCP assembly. My code is running on Windows Server 2008 R2 Standard. This code has a line that asks a value for "SshHostKeyFingerprint". Now, I noticed when i connected SFTP server for the first time, a fingerprint showed up, and I had to accept as yes. I believe this fingerprint is stored somewhere in the server.
1. How to find this fingerprint from the system in the format for powershell?
2. Where this fingerprint is located in the server?


------------------
try
{
    # Load WinSCP .NET assembly
    [Reflection.Assembly]::LoadFrom("WinSCP.dll") | Out-Null
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = "example.com"
    $sessionOptions.UserName = "user"
    $sessionOptions.Password = "mypassword"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Upload files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
 
        $transferResult = $session.PutFiles("b:\toupload\*", "./", $FALSE, $transferOptions)
 
        # Throw on any error
        $transferResult.Check()
 
        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

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







How to get a file path excluding the file name?

$
0
0

Hi,

I'm looking to get the directory path for a file but I don't want it to include the file's name. Any ideas?

Thanks

Dearbhla

Running Commands against a list of users in a csv (O365)

$
0
0

Hi All, I posted this in the O365 forum but was advised to post here instead.

I am trying to run some post deployment scripts on a list of users who have been migrated to O365. The list is from a csv.

Here is what I currently have, at the moment I am just trying to run Get Commands and then once I am happy I will when run the deployment Set commands.

So I have a csv file that loks like this:

UserPrincipleName
joe.blogs@domain.com
jane.blogs@domain.com

I have tried running the following, but the results I get show me results for every mailbox on our O365 organisation, not the 2 in my csv file.

Just so you know I can confirm  I am connected to the O365 Powershell session:

Import-CSV "C:\emails.csv" | ForEach-Object {Get-Mailbox | fl} 

I have also tried this and I get the same results:

$list = Import-Csv "C:\emails.csv"

foreach($entry in $list) {

$User = $entry.User

Get-Mailbox -id $User

}

Any help would be greatly appreciated.


SetServiceAccount method in Powershell doesn't work for Clustered sql services when we call the method remotely

$
0
0

Has anyone tried to change Clustered sql services service account remotely with the SetServiceAccount method availble in ManagedComputer object.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null
$wmi = new-object ("Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer") "$Server"
$Services = $wmi.services | where {($_.ServiceAccount -eq '****') -and ($_.Type -ne 'ReportServer')} | ForEach{($_.SetServiceAccount($NewServiceAccount,$Password)}

here $Server is the active node of SQL Server 2008 Cluster.

I am getting below exception:

Exception: Exception calling "SetServiceAccount" with "2" argument(s): "Set service account failed. "

But this script is working fine for Non clustered services on this active node. Also if i run the script in the Active node, then this script is working fine for both Clustered and Non-Clustered services.

Why this script is giving exception when executing remotely.

Combine Columns From Separate Arrays Into One Formatted Table

$
0
0

What I'm trying to do is make two WMI queries with 2 different classes for a list of machines and then patch the columns together into one single array that is formatted as a table with columns and rows. I seem to keep banging my head against the wall and I can't help but feel that the answer is simple. I can certainly create an array that contains all 3 columns (such as in the commented out part) but no matter which angle I go at it, it always seems to end up as all the data in one single row in each column rather than a nicely formatted table. I've even tried constructing separate custom objects and adding the different objects to the array but that's obviously not working. Below is the code of the last thing I tried. I need someone to bash it to death and tell me the (most likely obvious) thing that I'm doing wrong. Thanks!

$failedos = @()
$failedcs = @()
$ccs = get-adcomputer -property operatingsystem -filter {name -like "*-CC*"} | select name | sort name
$cs = foreach ($cc in $ccs){$cc.name | % {if ($c=get-wmiobject -computername $cc.name -class win32_computersystem -ErrorAction SilentlyContinue){$c | select @{Name="Name";Expression={$_.Name}}, @{Name="Model";Expression={$_.Model}}} else {$failedcs += "$_"}}}
$os = foreach ($cc in $ccs){$cc.name | % {if ($o=get-wmiobject -computername $cc.name -class win32_operatingsystem -ErrorAction SilentlyContinue){$o | select @{Name="OperatingSystem";Expression={$_.caption}}} else {$failedos += "$_"}}}

#[array]$osprops = @{'Name'=$cs.Name;'Model'=$cs.Model;'OperatingSystem'=$os.OperatingSystem}

$result = @()
Foreach ($Line in $cs) {
 $MyCustomObject = New-Object -TypeName PSObject
 Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Name" -Value $Line.name -Force
 Add-Member -InputObject $MyCustomObject -MemberType NoteProperty -Name "Model" -Value $Line.Model -Force
 $result += $MyCustomObject
}

foreach ($Line2 in $os) {
 $MyCustomObject2 = New-Object -TypeName PSObject
 Add-Member -InputObject $MyCustomObject2 -MemberType NoteProperty -Name "OperatingSystem" -Value $Line2.OperatingSystem -Force
 $result += $MyCustomObject2
}

how-to use invoke-command with $variable for scriptblock

$
0
0

Hello all

I tested different ways to use the invoke-command but not successfull as I need it.

invoke-command -Session $session -ScriptBlock {& \\servername\Software\RStarter\RStarter.exe -E=NIX -D=20140101 > \\servername\Software\RStarter\out-20140101.txt} -AsJob     works fine, but I need it more flexible.

I try it like this, but without success

$RunPath = "\\servername\Software\RStarter\RStarter.exe"
$RunParameter = "-E=NIX -D=20140101"
$RunOutPath = "\\servername\Software\RStarter\out-20140101.txt"
$ScriptBlock = "{& " + $RunPath + " " + $RunParameter + " > " + $RunOutPath + " }"
write-host $ScriptBlock   show's the correct string as the working one above
invoke-command -Session $session -ScriptBlock $Scriptblock -AsJob       does not work, no errors

I also try it like this way, without success

$RunCommand = "{& " + $RunPath + " " + $RunParameter + " > " + $RunOutPath + " }"
$ScriptBlock = [ScriptBlock]::Create($RunCommand)
invoke-command -Session $session -ScriptBlock $Scriptblock -AsJob       does not work, no errors

So have some one any ideas what goes wrong or how can I make it run ?
thank all

Execute bat file remotely without enabling PowerShell Remoting - Like psexec

$
0
0

Hi All,

I want to execute a bat file on a remote machine. I know this has been like thousand times already, my scenario is quite different. kindly Assist.

Source machine - From where PS script will be run 
Target Machine - Machine on which "bat" file needs to executed on.

Bat file is already saved on "Target Machine"

I don't want to enable PowerShell Remoting (there are 30000+ machines , enabling it will be pain and out of my pay grade)
I tried inovoke-command and figured out that PS remoting needs to be enabled (if there is a way to do with out PS remoting please advice)
Certain machines dont have PowerShell installed (XP machines and Server 2003).

It should pretty much act like PSexec but something that is already integrated in OS. 


Tried []Process.create WMI method. For some reason its not working.. may be i'm doing it all wrong.. 

Thank you all in advance. 


$Bug

Powershell to unzip file having passowrd

$
0
0
hi, i am using the following script to unzip files it works fine with files not having password

$shell=new-object -com shell.application

$CurrentLocation=get-location

$CurrentPath=$CurrentLocation.path

$Location=$shell.namespace($CurrentPath)

$ZipFiles = get-childitem *.zip

$ZipFiles.count | out-default

foreach ($ZipFile in $ZipFiles)

{

$ZipFile.fullname | out-default

$ZipFolder = $shell.namespace($ZipFile.fullname)

$Location.Copyhere($ZipFolder.items())

}


# for password protected file it pops up a windows saying password needed, how can i enter the password in script

#what changes i need to make if i have to extract password protected files.




student
Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>