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

Running PowerShell from batch/cmd, error in command when using cmd, but works fine in PowerShell..

$
0
0

I'm using the following PowerShell command to automatically close a application:

Get-Process | Where-Object {$_.Path -like "G:\TCAFiles\Users\ywxychtb\930\plugins\minorating\MinoRatingPlugin.exe"} | Stop-Process -Force

I need this to run in a .bat script and found that I can use the following command in the command prompt to do this:

PowerShell -command "& {Get-Process | Where-Object {$_.Path -like "G:\TCAFiles\Users\ywxychtb\930\plugins\minorating\MinoRatingPlugin.exe"} | Stop-Process -Force }"

Unfortunately it gives me the following error:

At line:1 char:45
+ & {Get-Process | Where-Object {$_.Path -like G:\TCAFiles\Users\ywxychtb\930\plug ...
+                                             ~
You must provide a value expression following the '-like' operator.
At line:1 char:46
+ & {Get-Process | Where-Object {$_.Path -like G:\TCAFiles\Users\ywxychtb\930\plug ...
+                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'G:\TCAFiles\Users\ywxychtb\930\plugins\minorating\MinoRatingPlugin.exe' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : ExpectedValueExpression

Any idea what is wrong?
I've already tried putting ' and "'s around the $_.Path -like "G:\TCAFiles\Users\ywxychtb\930\plugins\minorating\MinoRatingPlugin.exe part, but this didn't help.


Output Redirection with Start-Process for DB export

$
0
0
I'm trying to call a DB export command using Start-Process from Powershell and capture all of the output.
I'm using Powershell 2.0 on Win2008 R2.
Below are the various attempts I've made at this and some notes on the results.

I'm finding that if I use -RedirectStandardOutput and -RedirectStandardError, I get nothing from StdOut and StdErr is capturing most but not all of the output (1479 lines - missing about 40, so maybe hitting some line or memory limit?).
If I try to use Unix-like redirects (2>&1>>logfile), I get an initial line output with handles, etc and then invalid characters where the export lines should be, so it's some kind of encoding problem.  Out-File and tee produce similar results.

I'm hoping someone might have some insight into why StdOut and StdErr seem to be reversed and if there are some limits to StdErr.  Or if there is a method to address the encoding issue with using Unix redirects.

example of Unix-like redirect output:
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                 
-------  ------    -----      ----- -----   ------     -- -----------                                                 
     20       1      304        144     3     0.03  11640 expdp                                                       

〲㔱〭ⴹ㜱ㅔ㨴㌲㔺′㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽㴽਍〲㔱〭ⴹ㜱ㅔ㨴㈴㔺‹ഠ㈊㄰ⴵ㤰ㄭ吷㐱㐺㨲㤵䐠瑡⽥楔敭椠⁳敓瑰浥敢⵲㜱ㄭ‵㨲㈴㔺‹䵐਍〲㔱〭ⴹ㜱ㅔ㨴㈴㔺‹捓楲瑰攠數畣楴杮椠⁳㩃潜獰扜湩睜灩扜湩扜捡畫彰灣捰瀮ㅳ਍〲㔱〭ⴹ㜱ㅔ㨴㈴㔺‹潌⁧楆敬慮敭椠⁳㩃潜獰扜湩睜灩汜杯扜捡畫彰灣捰氮杯਍〲㔱〭ⴹ㜱ㅔ㨴㈴㔺‹㴽㴽㴽㴽


Variables used in snippets below to avoid any questions about what's running.
$strExportExe = "C:\oracle\product\11.2.0\dbhome_1\BIN\expdp.exe"
$strDate3 = Get-Date -format yyyyMMdd_HH_mm_ss
$strExportFile = "${strInstance}_${strDate3}.exp"
$strArguments = "System/$strPwrd FULL=Y DIRECTORY=BACKUP_DIR DUMPFILE=$strExportFile"
$strBackupLog = "$strOpsLog\backup_cppc.log"
$strTmpBackupFile = "$strOpsTmp\tmp_backup_cppc.log"
FuncLogWrite is just a function to append lines to the main log file($strBackupLog) while adding a date/time to the front of the line

Various Attempts
1. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru -RedirectStandardOutput $strBackupLog -RedirectStandardError $strTmpBackupFile
  - dumps into  StdError file & nothing in StdOut file

2. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru 2>&1 >>$strBackupLog
  - doesn't properly log output from screen, invalid characters as in example above

3. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru 2>&1 -RedirectStandardOutput $strBackupLog
  - no data in backup log, redirecting stderr to stdout & then sending stdout to log file

4. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru 2>>$strBackupLog >>$strBackupLog
  - throws error "The process cannot access the file 'C:\ops\log\backup_cppc.log' because it is being used by another process"
    because trying to redirect both stderr (2>>) and stdout (>>) to same file

5. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru 1>&2 -RedirectStandardError $strBackupLog
  - errors "The '1>&2' operator is reserved for future use."

6. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru >>$strBackupLog
  - same bad redirect as 2nd one with 2>&1 >>$strBackupLog

7. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru | Out-File $strBackupLog
  - outputs handles etc and invalid characters as in example above

8. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru | Tee-Object -File $strBackupLog
  - same as above invalid characters

9. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru -OutVariable $out
   FuncLogWrite $out
  - this combination sent nothing to screen and nothing in $out being written to log by function FuncLogWrite

10. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru | tee $strBackupLog
  - same invalid characters as in example above

11. $strStdOut = "$strOpsLog\StdOut.log"
    $strStdErr = "$strOpsLog\StdErr.log"
    $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru -RedirectStandardOutput $strStdOut -RedirectStandardError $strStdErr
    FuncLogWrite "StdOut from DB backup"
    FuncLogWrite "======="
    FuncCopyRuntoFullLog $strStdOut
    FuncLogWrite "StdErr from DB backup"
    FuncLogWrite "======="
    FuncCopyRuntoFullLog $strStdErr

  - code above stdout file empty, stderr file only has 1479 lines of output not all of export info, missing about 40 lines at end of what would normally display on screen

12. $strProcess = Start-Process $strExportExe -ArgumentList $strArguments -wait -NoNewWindow -PassThru 2>&1>>$strBackupLog
  - same as 2. above but removed space before log file at end

After these attempted cmds, I've been using:
$strProcess.HasExited
$strProcess.ExitCode
to confirm it's finished and capture exitcode.  If anything other than 0 then would alert that issue with DB export.

Can you help me please, Screen Create User Powershell

$
0
0

I need to create logins, passwords and permissions in SQL, GUI via Powershell.

my code is lost in the line 139.

If ($objTextBox.Text -eq '' -and $objTextBox2.Text -eq '' -and $objTextBox3.Text -eq '' -and $objTextBox4.Text -eq '' -and $procName.Checked -eq '' -and $procName2.Checked -eq '' -and $procName3.Checked -eq '' ) 

And does not create the login on SQL Server, you can be?

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

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null 
$x = @() 
$Form = New-Object System.Windows.Forms.Form 
$Form.Text = "Administração de usuarios SQLServer" 
$Form.Size = New-Object System.Drawing.Size(800,600) 
$Form.StartPosition = "CenterScreen" 
#$Form.controls.add() 
#$Form.Add_Shown({$Form.Activate()}) 
#$Form.ShowDialog() 


$Form.KeyPreview = $True 
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$objTextBox.Text;$Form.Close()}}) 
$Form.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$Form.Close()}}) 

#nova ver ponteiro no primeiro campo 
#$Form.Cursor=[System.Windows.Forms.Cursors]::WaitCursor 
[System.Windows.Forms.Application]::UseWaitCursor=$false 


$OKButton = New-Object System.Windows.Forms.Button 
$OKButton.Location = New-Object System.Drawing.Size(65,460) 
$OKButton.Size = New-Object System.Drawing.Size(75,23) 
$OKButton.Text = "OK" 
$OKButton.Add_Click({$x=$objTextBox.Text,$objTextBox2.Text,$objTextBox3.Text,$objTextBox4.Text,$procName.Checked,$procName2.Checked,$procName3.Checked;$Form.Close()})
$Form.Controls.Add($OKButton) 


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


$objLabel = New-Object System.Windows.Forms.Label 
#$objLabel.DataBindings.DefaultDataSourceUpdateMode = 0 
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Server:" 
$Form.Controls.Add($objLabel) 


$objTextBox = New-Object System.Windows.Forms.TextBox 
$objTextBox.DataBindings.DefaultDataSourceUpdateMode = 0 
$objTextBox.Location = New-Object System.Drawing.Size(10,40) 
$objTextBox.Size = New-Object System.Drawing.Size(260,20) 
$objTextBox.Name="ServerName" 
$objTextBox.TabIndex = 0 
$Form.Controls.Add($objTextBox) 


$objLabel2 = New-Object System.Windows.Forms.Label 
$objLabel2.Location = New-Object System.Drawing.Size(10,70) 
$objLabel2.Size = New-Object System.Drawing.Size(260,20) 
$objLabel2.Text = "Database:" 
$Form.Controls.Add($objLabel2) 


$objTextBox2 = New-Object System.Windows.Forms.TextBox 
$objTextBox2.Location = New-Object System.Drawing.Size(10,90) 
$objTextBox2.Size = New-Object System.Drawing.Size(260,20) 
$objTextBox2.Name="Base Name" 
$objTextBox2.TabIndex = 0 
$Form.Controls.Add($objTextBox2) 


$objLabel3 = New-Object System.Windows.Forms.Label 
$objLabel3.Location = New-Object System.Drawing.Size(10,120) 
$objLabel3.Size = New-Object System.Drawing.Size(260,20) 
$objLabel3.Text = "User:" 
$Form.Controls.Add($objLabel3) 


$objTextBox3 = New-Object System.Windows.Forms.TextBox 
$objTextBox3.Location = New-Object System.Drawing.Size(10,140) 
$objTextBox3.Size = New-Object System.Drawing.Size(260,20) 
$objTextBox3.name="User" 
$objTextBox3.TabIndex = 0 
$Form.Controls.Add($objTextBox3) 


$objLabel4 = New-Object System.Windows.Forms.Label 
$objLabel4.Location = New-Object System.Drawing.Size(350,120) 
$objLabel4.Size = New-Object System.Drawing.Size(260,20) 
$objLabel4.Text = "Password:" 
$Form.Controls.Add($objLabel4) 


$objTextBox4 = New-Object System.Windows.Forms.TextBox 
$objTextBox4.Location = New-Object System.Drawing.Size(350,140) 
$objTextBox4.Size = New-Object System.Drawing.Size(260,20) 
$objTextBox4.name="Pass" 
$objTextBox4.TabIndex = 0 
$Form.Controls.Add($objTextBox4) 


$groupBox = New-Object System.Windows.Forms.GroupBox 
$groupBox.Location = New-Object System.Drawing.Size(10,190) 
$groupBox.size = New-Object System.Drawing.Size(755,200) 
$groupBox.Text = "Permissões e acessos Database:" 
$Form.Controls.Add($groupBox) 


$procName = New-Object System.Windows.Forms.checkbox 
$procName.Location = New-Object System.Drawing.Size(10,40) 
$procName.Size = New-Object System.Drawing.Size(100,20) 
$procName.Checked = $false 
$procName.Text = "Read" 
$procName.TabIndex = 0 
$groupBox.Controls.Add($procName) 


$procName2 = New-Object System.Windows.Forms.checkbox 
$procName2.Location = New-Object System.Drawing.Size(270,40) 
$procName2.Size = New-Object System.Drawing.Size(100,20) 
$procName2.Checked = $false 
$procName2.Text = "Write" 
$procName2.TabIndex = 0 
$groupBox.Controls.Add($procName2) 


$procName3 = New-Object System.Windows.Forms.checkbox 
$procName3.Location = New-Object System.Drawing.Size(550,40) 
$procName3.Size = New-Object System.Drawing.Size(100,20) 
$procName3.Checked = $false 
$procName3.Text = "Alter" 
$procName3.TabIndex = 0 
$groupBox.Controls.Add($procName3) 


If ($objTextBox.Text -eq '' -and $objTextBox2.Text -eq '' -and $objTextBox3.Text -eq '' -and $objTextBox4.Text -eq '' -and $procName.Checked -eq '' -and $procName2.Checked -eq '' -and $procName3.Checked -eq '' ) 




Else 

$objForm.Cursor=[System.Windows.Forms.Cursors]::WaitCursor 

$Instance = $objTextBox.Text 
$DBName = $objTextBox2.Text 
$LoginName = $objTextBox3.Text 
$Password = $objTextBox4.Text 

$bb=$Instance 
$bb 
$bb 

$Server = New-Object ("Microsoft.SqlServer.Management.SMO.Server") $instance 

#Recebi login pra ver se exist. 
$Login = $Server.Logins.Item($LoginName) 

IF (!($Login))  #check se é existente. 

    #Caso não existir é criado um novo login 
    $Login = New-Object ("Microsoft.SqlServer.Management.SMO.Login") ($Server, $LoginName)   
    $Login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin 
    $Login.Create($Password) 


$DB = $Server.Databases[$DBName] 
$User = $DB.Users[$LoginName] 




if (!($User)) # check se usuário é existente. 

    #Se não Add. 
    $User = New-Object ("Microsoft.SqlServer.Management.SMO.User") ($DB, $LoginName) 
    $User.Login = $LoginName 
    $User.Create() 

    IF ($procName.Checked -eq $true) 

    $Role_Leitura="db_datareader" 

    $dbrole = $DB.Roles[$Role_Leitura]   
    $dbrole.AddMember($user.Name) 
    $dbrole.Alter() 
    Write-Host("User $user adicionado com sucesso para $Role_Leitura.") 

Else{ 

}

IF ($procName2.Checked -eq $true) 

    $Role_Gravacao ="db_datawriter" 

    $dbrole2 = $DB.Roles[$Role_Gravacao] 
    $dbrole2.AddMember($user.Name) 
    $dbrole2.Alter() 
    Write-Host("User $user adicionado com sucesso para $Role_Gravacao.") 

Else { 





IF ($procName3.Checked -eq $true) 

    $Role_Modificacao ="db_owner" 

        $dbrole3 = $DB.Roles[$Role_Modificacao] 
    $dbrole3.AddMember($user.Name) 
    $dbrole3.Alter() 
    Write-Host("User $user adicionado com sucesso para $Role_Modificacao.") 

Else { 

  } 

}
$Form.Topmost = $True 

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


$x 

                             

looking script

$
0
0
I am looking for script for identify user name starts with zz in active dricetory secanrio is need user name and Fristname, lastname, profile path,homedrive path etc I am looking script please help me

Not able to restart FTP after adding data channel port using powershell

$
0
0

Hi

Not sure if this is a bug or incomplete syntax. in Windows 2012R2 with IIS8.5 I have setup FTP.  When i ran the below PS script I did not get any error (not any confirmation)

Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.ftpServer/firewallSupport" -name "lowDataChannelPort" -value 7014 

Set-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST'  -filter "system.ftpServer/firewallSupport" -name "highDataChannelPort" -value 7000

This script was generated by IIS Configuration Editor

But after that i ran the below commands and  ftp would fail to start

net stop ftpsvc
net start ftpsvc

Error:

net : The Microsoft FTP Service service could not be started.
At line:1 char:1
+ net start ftpsvc
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The Microsoft F...not be started.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
A system error has occurred.
System error 13 has occurred.
The data is invalid.

However if I ran this 

cmd /c \Windows\System32\inetsrv\appcmd set config -section:system.ftpServer/firewallSupport /lowDataChannelPort:"7001" /highDataChannelPort:"7015"  /commit:apphost

and tried to start FTP, it would start without error.

Thanks

kumar


Merge excel spreadsheets into same worksheet

$
0
0

Hi all,

         looking to merge approx. 150 xlsx files into a single worksheet using powershell. (its aprt of a larger script which also performs other functions)

There seem to many examples or merging multiple files into multiple worksheets - but I haven't been able to successfully get any of them to merge into the same worksheet.

This is an ongoing requirement, so while exporting to csv's, merging and re-opening will work - its not really the long term solution im looking for.


powershell basis

$
0
0
I am looking power shell basis topic like snap drive, wmi, pramam, looping, function, etc basic script and how to run on 1 machines,set of machines, all servers,or workstation, our,security gurop etc video also appreciated

Move a user from AD groups to other AD groups

$
0
0

Hi

I am trying to figure out how to move specific users from several ad groups to new ad groups. This will move the user from the old Citrix farm to the new one. So we want to take this by user or department

The naming of the old AD groups looks like this:

sec_ctx.app.XX.Outlook where XX are the region which gives access to a specific farm in Citrix. We use 3 regions EU, AP and US

The script should look for the groups and if they are member of that group they should be removed from the group and added to the new one like this:

sec_ctx.app.Outlook

So I have removed the regions from the group.

There are a group per application and one group giving access to a Full desktop in Citrix

sec_ctxEU.app.FullDesktop will become sec_ctx.app.FullDesktop

Any ideas ?

Thanks !

Torsten 


How to add External IP Address of Firewall using powershell

$
0
0

Hi 

I am trying to setup FTP using powershell in an Azure VM

In FTP Firewall Support how do I add value for External Ip Address of Firewall using powershell. 

Thanks

Kumar

Hangman Powershell, Spacing help

$
0
0

I am creating the hangman game. For this excercise I am doing, when the player gets to their last guess which is guess 12, they are allowed to try and type the whole word in and not just the letter.Right now my script works perfectly fine with that, but when I have to enter in the word I am trying to guess on the very last guess, I have to put a space inbetween each letter for it to recognize what I am doing. Right now I have this.... and I am unsure why I need to enter in spaces between each letter.

#Reset variables at the beginning of each new round of play
  $tempString = ""
  $words[0] = @("","","","","","","","","","","","","","","")
  $attempts = 0
  $guesses = ""
  $reply = ""

__________________________________________________________________________________________________

#Create a Associative array and load it with words
$words = @{}
$words[0] = @("","","","","","","","","","","","","","","")
$words[1] = @("C","O","M","M","A","N","D","E","R")
$words[2] = @("F","L","A","G")
$words[3] = @("T","O","A","S","T","E","R")
$words[4] = @("M","A","R","K","E","R")
$words[5] = @("P","I","C","T","U","R","E")

Merge two CSV's with a common column

$
0
0

Found many things on the web, but I cannot seem to grasp what is happening.  I have two csv files.

CSV1 has the following column headers:

Name, UserAssigned,Class,Function,Created, LastLogon,Department,Location,PCType,DN,OperatingSystem,ServicePack

CSV2 has the following column headers:

Name, Manufacturer, Model

There are items in CSV2 that are not listed in CSV1. not a problem as long as the ones that are in there get merged correctly.  

I would like the end results to have the following columns:

Name, UserAssigned,Class,Function,Created, LastLogon,Department,Location,PCType,Manufacturer, Model,DN,OperatingSystem,ServicePack

I assume I need to import the csv's and create a hashtable and psobject and then merge, but not having much luck.  Is there a quick and dirty way to do this?  Essentially I am looking to do a VLOOKUP using PowerShell.  

Thanks,

Matt



Matt Dillon

What am I doing wrong?

$
0
0

Hi.  If I run this command by itself, it works fine and returns the Citrix clientname.

 Get-XASession -Account DOMAIN\UserID | select clientname | Format-Table -HideTableHeaders

But if I run it in a script, it is returning: UserID Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Micros......

$groupofUsers = (Get-ADGroupMember -Identity SEC_GROUP1 | where { $_.name.length -eq 7 }).name
ForEach ($groupUser in $groupofUsers)
{
    $clientComputerName = Get-XASession -Account DOMAIN\$groupUser | select clientname | Format-Table -HideTableHeaders
    Write-Host $igroupUserr $clientComputerName
What am I doing wrong? Still in learning phase, so excuse the question if it is a dumb one.


"Fate rarely calls upon us at a moment of our choosing…"

Check string for a blank space

$
0
0

Assuming I am reading a string that is supposed to represents a computer name, how can I check to see if there is a blank space in that string and if there is, treat it as an array and only read in the first element or just read in the string up to the space?


"Fate rarely calls upon us at a moment of our choosing…"

Editing A Dynamic Distribution Group Filter

$
0
0

Hello,

I need some assistance editing a dynamic distrubution group via powershell (customer is on Office 365). I ran the below commands to retrieve the current DDG filter:

$var = Get-DynamicDistributionGroup -Identity "$Identity"
$var.RecipientFilter

The output I got was (Company name was changed for privacy purposes):

((((Company -eq 'Company Name') -and (((RecipientType -eq 'UserMailbox') -or (RecipientType -eq 'MailContact') -or (RecipientType -eq 'MailUser'))))) -and (-not(Name -like 'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')) -and (-not(RecipientTypeDetails
Value -eq 'MailboxPlan')) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'ArbitrationMailbox')) -and (-not(RecipientTypeDetailsValue -eq
 'AuditLogMailbox')))

The issue that they are seeing is that a couple of users are no longer with the company and their accounts have been disabled. However, the disabled users are still listed in the current list of members if I run:

Get-Recipient -RecipientPreviewFilter $var.RecipientFilter

To fix this I took the output from the current filter and tried to edit it to not include disabled accounts:

Get-DynamicDistirbutionGroup dl-all | Set-DynamicDistributionGroup ((((Company -eq 'Company Name') -and (((RecipientType -eq 'UserMailbox') -or (RecipientType -eq 'MailContact') -or (RecipientType -eq 'MailUser'))))) -and (-not(Name -like 'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')) -and (-not(RecipientTypeDetails Value -eq 'MailboxPlan')) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'ArbitrationMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuditLogMailbox')) -and (-not(UserAccountControl -like 'AccountDisabled')))

However this is not working and is instead kicking back errors that says

"Company : The term 'Company' 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."

Any suggestions on getting this script edited?

Thanks in advance

How to get XML nodes/values with System.Xml.Linq.XDocument?

$
0
0

I'm trying to output a hash table of nodes/values from an XML definition of a Schedule Task.

I'd like to accomplish this with System.Xml.Linq.XDocument.

Here's what it looks like using System.Xml.XmlDocument:

[System.Xml.XmlDocument]$xmldoc = new-object System.Xml.XmlDocument
$xmldoc.Load($pathtoxmlfile)
$values = @{};
$xmldoc.SelectNodes("//text()") |

% { $values[$_.ParentNode.ToString()] = $_.Value }; $values | ft

#OUTPUT Name Value ---- ----- AllowHardTerminate true DisallowStartIfOnBatteries false Author MYDOMAIN\myuser.name Description my description UserId MYDOMAIN\myuser.name AllowStartOnDemand true Enabled false Command C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe StopOnIdleEnd true Priority 7 RunLevel HighestAvailable ...

Below is psuedocode -- the Add method will NOT work like this -- for illustration only.

System.Xml.Linq.XDocument

[Reflection.Assembly]::LoadWithPartialName('System.Xml.Linq') | Out-Null $xdoc = [System.Xml.Linq.XDocument]::Load($pathtoxmlfile) $xdoc.Add("//text()") |

% { $values[$_.ParentNode.ToString()] = $_.Value }; $values | ft

How do I use System.Xml.Linq.XDocument to get a listing of nodes/values similar to the output from System.Xml.XmlDocument?



How do I get properties of an object when given its SID? (translate and [adsi] failing)

$
0
0

Hello, I'm attempting to use PowerShell to pull various attribute values (e.g., objectClass, objectCategory, etc.) of members of groups on Active Directory domains. Some members are foreign security principals (FSPs), so the unique identifier that I have for each of them is the SID.  For some FSPs, I can readily get those values viaSystem.Security.Principal.SecurityIdentifier.Translate() and [adsi]("LDAP://<SID=S-1-5-21-XXXXX-XXXXX-XXXXX-XXX>").  But PS returns IdentityNotMappedException or a null value when I try Translate() and the ADSI accelerator (respectively) on other SIDs.  Typically this happens when the SID points to an object that no longer exists on the foreign domain.  But for other unresolvable SIDs, I have verified their existence in the foreign domain by looking up the group (containing the FSP) in Active Directory Users and Computers (ADUC) and by doing an LDAP query on the foreign domain for the given SID.  So my question is, if ADUC shows the resolved accounts when I look up the groups and view their memberships, how can I get PS to provide properties of the objects to which the FSPs point?

Some things to note:  In case it isn't obvious, the domain containing the groups trusts the foreign domains in which the group members reside.  Also, I'm running PS from a third domain, which is the primary domain of my organization.  This primary domain contains some of the members of the groups but not all.  PS is able to resolve/get the properties of objects on this (primary) domain when it finds them in groups (provided the objects still exist in the primary domain), unlike when PS tries to get the properties of FSPs in the other foreign domain.  I also tried usingSystem.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity() as follows:

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ct, $domainName, $domainContext
$idType = [System.DirectoryServices.AccountManagement.IdentityType]::Sid
$fsp = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ctx,$idType,$objectSIDstring)

I've tried using the domain where the groups reside as well as the domain where the PS script resides (our organization's primary domain) for $domainName (something like "example.com") and $domainContext (something like "DC=example,DC=com"), but $fsp ends up being null.  Finally, I'm using PowerShell version 3.

I hope that I have provided enough details, but if not, let me know.

David

what is the .StartTime? I dont see it under properties or methods.

$
0
0

If you run the help below

helpSelect-Object-Examples

Under this I find the following:

 -------------------------- EXAMPLE 4 --------------------------
   
    PS C:\>Get-process | Select-Object -Property ProcessName,@{Name="Start Day"; Expression = {$_.StartTime.DayOfWeek}}
   
    ProcessName  StartDay
    ----         --------
    alg          Wednesday
    ati2evxx     Wednesday
    ati2evxx     Thursday
    ...

What is the StartTime?

I figured that since this was time it had to do with Date so I figured out that this was from Get-Date and I used the Get-Member to confirm that a part of this <dayofweek> was a property of the get-date

However, I cannot find StartTime listed on MSDN or as a property or method anywhere. I tried looking on google and not finding anything there with my searches.

I just learned about the get-member command today and its pretty eye opening and is very exciting with the possibilities but I was just trying to indenfity what that StartTime is part of.

I did find this site below but not sure I fully understand it

https://msdn.microsoft.com/en-us/library/system.diagnostics.process.starttime(v=vs.110).aspx

by understand I mean the process.starttime

when I looked at another like System.DateTime    if I take that to be similar it would mean that startime was a cmdlet and its part of the process?


difference between LDAP and Operation master role

$
0
0

Can someone explain what is difference between LDAP and operation masters. As I know both perform the same job

systemreset

$
0
0

hi

i have 200 windows 8/8.1/10 and on all i need to execute systemreset -factoryreset with options refresh or reset



Nikola Batinica System Administrator at BANINI AD www.banini.co.rs

is there a way to find the cmdlet for properties and methods?

$
0
0

Today I just learned how to use get-member to find the properties and methods of cmdlets.

I am curious if there is some command that does the reverse takes a property or method and tells you what its part of.

I have tried using help and get-command, and things of that nature but those have not worked for me unless I am just missing something because I am tired.

Viewing all 21975 articles
Browse latest View live


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