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

How to use Powershell script to get OU info for current logged in user

$
0
0

Hello folks,

I am fresh new to Powershell but I know it is feasible to use powershell to get OU info from active directory for the current logged in user, I wonder who can explain to me how to do it?

Ideally I need a script file, by running the script file I can get the OU info.

Thank you very much.


Hex changes after piping to findstr ???

$
0
0

Re:  cat CPO0008.VDI | findstr HDRE > HDRfile

Hex format of input file:  48  44  52  45  31  38  31  34

Hex format of output file:  FF  FE  48  00  44  00  52  00  45  00  31  00  38  00  31  00  34  00

Any help with why/how this is happening is so greatly appreciated.  Thank you!

Get-PrintJob returning an error

$
0
0

Greetings Everyone, 

I am writing a Powershell script that takes a printer name and printer IP address and uses a WQL query to return a list of workstations that the printer is installed on. The script will export those workstation ids to a .csv file and then use that .csv file to provide the workstation ids for the Get-PrintJob commands -ComputerName attribute.  The problem is that when it gets to the -ComputerName attribute it returns a "FullyQualifiedErrorId : HRESULT 0x8007092f". I am not sure why, because if I use an actual workstation name in place of my variable the script works just fine. Any help would be appreciated. 

$printerIP = read-host "Plese enter printer IP"
$printerName = read-host "Please enter printer name"

$WQLquery = @"
select SMS_R_System.Name from
SMS_R_System inner join
SMS_G_System_PRINTER_DEVICE on
SMS_G_System_PRINTER_DEVICE.ResourceID =
SMS_R_System.ResourceId where
SMS_G_System_PRINTER_DEVICE.PortName like '$printerIP'"@

$wsid = ForEach-Object {Get-WmiObject -Query $WQLquery -ComputerName "sccm.site.is.here.hehe" -Namespace "root\sms\site_thisisthesitecode" | Select-Object Name} | Export-CSV wsid.csv -NoTypeInformation

$workstationid = Import-CSV wsid.csv -Header 'Name'

foreach ($_ in $workstationid) {
Get-PrintJob -ComputerName $_ -PrinterName $printerName}

#Remove-Item wsid.csv

How to recover from copying directory tree from (now deleted domain) user to local user

$
0
0

On my windows 10 notebook computer I had two accounts: my personal local account and a domain account.

After I moved the files from my domain account %USERPROFILE% to my personal account %USERPROFILE%, I logged into the local administrator account and disconnected from the domain and became a member of the workspace WORKSPACE instead of the domain.

Now, when I right click on one of these files and click on properties->security->edit

At this point I get a modal dialog box that says

"The permissions on <directory> are incorrectly ordered, which may cause some entries to be ineffective. To order the permissions correctly, click Reorder.To leave the permissions unchanged, (the view will be read-only) click Cancel.

So I click reorder button and I see a list of group or owner names

  • NULL SID (where did this come from?)
  • Everyone (why is this here? I did not put it here)
  • CREATOR OWNER (what is this)?
  • CREATOR GROUP (what is this)?
  • SYSTEM (why is this here?)
  • Account Unknown (S-1-5-21-212.....) (Is this my old domain account?)
  • Account Unknown (S-1-5-21-212.....) (this looks like a duplicate)
  • Siegfried Heintze (my hotmail account) (Ok, finally my entry)
  • Administrators (SW\Administrators)

Wow! What a lot of garbage! So I click the "Remove" button seven times until "Siegfried Heintze" is highlighted. Now I click the check box for "Allow" and "full control" and now I click "OK" twice.

This seems to solve the problem.

Can someone help me write a powershell script to automate this for a very deep directory tree?

Much to my surprise, my little file called CHOWN.BAT sometimes solves the problem and sometimes not and I don't know why:

cd %1
takeown /f . /r /d y
icacls . /grant shein:f /t /q

In the cases where it does not work, the above manual procedure seems to work which is why I would like to automate it with powershell.

Sometimes, when working with a very deep directory structure, the CHOWN.BAT gives this error because the directory path is too long:

C:\Users\shein\Documents\books\2015\javascript\BDD JS\Learning Behavior-driven Development with JavaScript\ch06_UITestingWebDriverJS\node_modules\browserify\node_modules\browser-pack\node_modules\combine-source-map\node_modules\convert-source-map>icacls . /grant shein:f /t /q
.\.travis.yml: The system cannot find the path specified.

Other times CHOWN.BAT does not give any error messages and still does not work. Strange.

Thanks

Siegfried


siegfried heintze

Need help isolating script parameters from other running scripts.

$
0
0

My script uses the param, works great.

Param(
  [Parameter(Mandatory=$True)]
  [string]$servername

)

The script takes 20 mins or so to complete. When I spawn a new powershell instance to call the same script with new parameters while the first one is running, the second instance is taking parameters from the first instance.

I'm missing something basic with scoping, script blocks or something similar. I was under the impression powershell command line provides this isolation while PowerShell ISE does not unless you declare so.

My goal is to run the same script multiple times without interference from other instances while retaining the switch input functionality.

Example:

c:\myscript.ps1 -servername server1 -host host1 -vlan vlan1

c:\myscript.ps1 -servername server2 -host host2 -vlan vlan2

Thanks in advance.

Reuse WPF window in PS

$
0
0
Hi!
I am new to WPF and PS. I have a main window that has a button. When the button is clicked, it will open another wpf window called w2. If I close w2 and try to click the button again, I get an error message basically saying that the window was closed and cannot be reused.

How can I make sure that a new wpf window is created everytime the button is clicked?
Note: I am using visual studio to create the window (GUI).

Thanks


Problem running script with right click open with powershell

$
0
0

I have created a script. It runs fine with no errors IN powershell ise and when I open it IN powershell ( See link 1)

http://tinypic.com/r/wl8y0l/9

But when I right click and run with powershell this error comes up.

http://tinypic.com/r/8z4kk2/9

This is really bugging me. I have set my execution policy to Unrestricted.

For somer eason I cannot get this to work.



Help please!


Need Powershell Script to get shared folder and NTFS permission from list of servers

$
0
0

Hi Friends,

 

I need powershell script to dump all the shared folder and thier permission from serverlist.txt. the below code just giving me the shares but not the permissions.

$strComputer = gc C:\ps-test\serverlist.txt
foreach ($computer in $strComputer) {
$colItems = get-wmiobject -class "Win32_Share" -namespace "root\CIMV2" -computername $computer
foreach ($colItem in $colItems) {
$sharename = $colItem.Name
$share = "\\" + $computer + "\" + $sharename | Out-File C:\ps-test\result.txt -NoClobber -Append
$share
}
}


Windows Context Menu Item { Rename file with Random Hash } PIPELINE EXPRESSION ERROR

$
0
0

Powershell %{Rename-Item "%1" "$(-join ((1..12) | %{(65..90) + (97..122) | Get-Random} | %{[char]$_}) + $_.extension)"}

So, in Powershell, If you would create a directory somewhere, E.G. 'C:\Users\YourAccount\MyTestDirectory\'

Create a new file of any type in that directory, E.G. 'New Text Document.txt'.

Open Windows Powershell, Navigate to that directory, E.G. 'cd MyTestDirectory'

PS C:\USers\James>
PS C:\Users\James\MyTestDirectory>
PS C:\Users\James\MyTestDirectory> Get-ChildItem | %{Rename-Item $_ "$(-join ((1..12) | %{(65..90) + (97..122) | Get-Random} | % {[char]$_}) + $_.extension)"}

Your 'New Text Document.txt', has name changed to something like 'WzWSVYDXyvjz.txt'. Which is exactly the type of functionality I want, only I want to make this as a shell command in the registry.

{HKEY_CLASSES_ROOT/*/shell/HashRename/command}
One would think that you would just use the command: 
{Rename-Item %1 "$(-join ((1..12) | %{(65..90) + (97..122) | Get-Random} | % {[char]$_}) + $_.extension)"}
or
{Rename-Item %1 "$(-join ((1..12) | %{(65..90) + (97..122) | Get-Random} | % {[char]$_}) + %1.extension)"}
Now when you right-click on your file and click on the menu-item you've just created 'Generate Random Hash Filename', it should do the same thing, right? But it doesn't work. Instead you get:

At line: 1 char:72
+ {Rename-Item C:\Users\James\MyTestDirectory\New Text Document $(-join ((1..12) | ((65..90)  ---
+                                                                                                                        ~~~~~~
'Expressions are only allowed as the first element of a pipeline. At line:1 char:111'
+ --- Get-Random} |  {[char]$_}) + C:\Users\James\MyTestDirectory\New Text Document.txt)}
+                             ~~~~~~~ 
'Expressions are only allowed as the first element of a pipeline. At line: 1 char:124'
+ --- {[char]$_}) + 'C:\Users\James\MyTestDirectory\New Text Document.txt')}
+

'You must provide a value expression following the '+' operator. At line: 1 char:125'
+ --- {[char]$_}) + 'C:\Users\James\MyTestDirectory\New Text Document.txt')}
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'Unexpected token 'C:\Users\James\MyTestDirectory\New Text Document.txt' in expression or statment.
+CategoryInfo :ParserError: (:) []. ParentCOntainsErrorRecordException
+FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline


Uninstalling Software using PowerShell

$
0
0

Right, this is what I have.. I understand why its not working but cant think of way round it or easier way to get to the point I want to be at..

I have script where I can check disk space and install on the local or remote machines.. this works fine.. But I've been advised to follow best practice I should incorporate something that checks where a version is already installed and install it if necessary..

Here's a similar representation of the piece of script  -

$FileName = get-itemproperty 'C:\Powershell\Blah Blah Blah 1.1.1.1 Installer.msi' | Select name
Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -like "$FileName"} | foreach-object -process {$_.Uninstall()}

It doesn't find the software installed to be able to install it.. I've checked..

But when I Type the following -

Get-WmiObject -Class Win32_Product | Where-Object {$_.Name -eq "Blah Blah Blah"} | foreach-object -process {$_.Uninstall()}

Basically the same as the top example without the '1.1.1.1 Installer.msi' part.. It has the expected result - It picks up the installed software and installs correctly..

Is there a way to get round this or an easier way to look to see if the software or previous versions are installed and if there is.. to uninstall them?

A friend of mine mentioned 'Uninstall Stings' but after research they confuse me a bit..

Any guidance or assistance is greatly appreciated..

Thanks Guys - Loving the PowerShell Community :)

during daily task via task scheduler

$
0
0
how to replicate folders from central location to multiple servers around 500 servers and folder needs to replicate delta changes also if any incremental folder added or delta changes only those changes needs to needs to replicate from central repository not entire set of folder since already set of folder already replicated (during daily task via task scheduler) 

Count object based by properties

$
0
0
HI All,
I'm trying to count objects based by properties.
Example, I would like to know how many users have attribute Country set with Italy, how many with France etc... not knowing which value is set in attribute Country. How I can do it ?
Thanks!

Function doesn't work like wished

$
0
0

Hello guys
Im working on a Powershell script which should gives me all files from the wished source file which are older than 2 days. Here's my script. 

function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$label2 = New-Object System.Windows.Forms.Label
$label1 = New-Object System.Windows.Forms.Label
$textBox2 = New-Object System.Windows.Forms.TextBox
$textBox1 = New-Object System.Windows.Forms.TextBox
$button5 = New-Object System.Windows.Forms.Button
$button4 = New-Object System.Windows.Forms.Button
$button3 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$openFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog
$saveFileDialog1 = New-Object System.Windows.Forms.SaveFileDialog
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$date = Get-Date -Format d.MMMM.yyyy


$button1_OnClick=


{
$destination= $textbox2.Text
$NeueVar = "$destination" + "\" + "$date"
New-Item -Path $destination -Name $date -ItemType directory

$source = $textbox1.Text
copy-Item  -Recurse $source -Destination $NeueVar
$backup_log = Dir -Recurse $destination | out-File "$destination  \backup_log.txt"
$attachment = "$desination  \backup_log.txt"
}

$button2_OnClick=

{
$source = $textbox1.Text
$changedDays = 2;
$destination= $textbox2.Text
$NeueVar = "$destination" + "\" + "$date"
Copy-Item $Source $NeueVar -Recurse -force | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) }

$backup_log = Dir -Recurse $destination | out-File "$destination  \backup_log.txt"
$attachment = "$desination  \backup_log.txt"
}

$button5_OnClick=
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$FolderBrowserDialog.ShowDialog() | Out-Null
$destination= $FolderBrowserDialog.SelectedPath
$textBox2.Text= $destination
}

$button4_OnClick=
{

[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog
$FolderBrowserDialog.ShowDialog() | Out-Null
$source = $FolderBrowserDialog.SelectedPath
$textBox1.Text= $source
}

$OnLoadForm_StateCorrection=
{
$form1.WindowState = $InitialFormWindowState
}

$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 410
$System_Drawing_Size.Width = 583
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Name = "form1"
$form1.Text = "soemthing"

$label2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 34
$System_Drawing_Point.Y = 81
$label2.Location = $System_Drawing_Point
$label2.Name = "label2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 80
$System_Drawing_Size.Width = 44
$label2.Size = $System_Drawing_Size
$label2.TabIndex = 8
$label2.Text = "Destination"

$form1.Controls.Add($label2)

$label1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 51
$System_Drawing_Point.Y = 30
$label1.Location = $System_Drawing_Point
$label1.Name = "label1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 80
$System_Drawing_Size.Width = 44
$label1.Size = $System_Drawing_Size
$label1.TabIndex = 7
$label1.Text = "Source"

$form1.Controls.Add($label1)

$textBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 101
$System_Drawing_Point.Y = 81
$textBox2.Location = $System_Drawing_Point
$textBox2.Name = "textBox2"
$textBox2.ReadOnly = $false
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 169
$textBox2.Size = $System_Drawing_Size
$textBox2.TabIndex = 6

$form1.Controls.Add($textBox2)

$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 101
$System_Drawing_Point.Y = 30
$textBox1.Location = $System_Drawing_Point
$textBox1.Name = "textBox1"
$textBox1.ReadOnly = $false
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 169
$textBox1.Size = $System_Drawing_Size
$textBox1.TabIndex = 5

$form1.Controls.Add($textBox1)


$button5.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 299
$System_Drawing_Point.Y = 81
$button5.Location = $System_Drawing_Point
$button5.Name = "button5"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 110
$button5.Size = $System_Drawing_Size
$button5.TabIndex = 4
$button5.Text = "Search"
$button5.UseVisualStyleBackColor = $True
$button5.add_Click($button5_OnClick)

$form1.Controls.Add($button5)


$button4.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 299
$System_Drawing_Point.Y = 30
$button4.Location = $System_Drawing_Point
$button4.Name = "button4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 110
$button4.Size = $System_Drawing_Size
$button4.TabIndex = 3
$button4.Text = "Search"
$button4.UseVisualStyleBackColor = $True
$button4.add_Click($button4_OnClick)

$form1.Controls.Add($button4)


$form1.Controls.Add($button3)


$button2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 366
$System_Drawing_Point.Y = 346
$button2.Location = $System_Drawing_Point
$button2.Name = "button2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 150
$button2.Size = $System_Drawing_Size
$button2.TabIndex = 1
$button2.Text = "Incrementell"
$button2.UseVisualStyleBackColor = $True
$button2.add_Click($button2_OnClick)

$form1.Controls.Add($button2)

$openFileDialog1.FileName = "openFileDialog1"
$openFileDialog1.ShowHelp = $True

$saveFileDialog1.CreatePrompt = $True
$saveFileDialog1.ShowHelp = $True

#endregion Generated Form Code

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

}
GenerateForm

I think I did a mistake by the following lines:

$button2_OnClick=

{
$source = $textbox1.Text
$changedDays = 2;
$destination= $textbox2.Text
$NeueVar = "$destination" + "\" + "$date"
Copy-Item $Source $NeueVar -Recurse -force | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-1) }

$backup_log = Dir -Recurse $destination | out-File "$destination  \backup_log.txt"
$attachment = "$desination  \backup_log.txt"
}

The thing is, that I can see files which are older than 2 days, but this isn't what I want.

Can someone tell me what I did wrong?
Regards

^PQL


mohamedhassan_99@hotmail.com

Activating windows via powershell

$
0
0

Hi, I am trying to activate windows via powershell and have found this script:

https://social.technet.microsoft.com/Forums/office/en-US/9fcdb039-f9f0-48a9-8253-1f52c0257a80/activate-windows-using-powershell?forum=winservergen

Problem is, i cannot run it. THis is my exact version of the script:

##### Getting serial key from Bios ####
$key = (wmic path softwarelicensingservice get OA3xOriginalProductKey)[2];break

# Getting activation object#

$service = get-wmiObject -query 'select * from SoftwareLicensingService'

##### Install product key and activate ####
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()


I also tried to create the $key parameter manually like this 

$key = "xxx-xxx-xxx-xxx";break


I also tried both variations without the break

My problem is this line:

$service.InstallProductKey($key)

It gives me the following error:

Exception calling "InstallProductKey" : ""
At line:1 char:1+ $service.InstallProductKey($key)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : WMIMethodException

If i try to echo the $key to a file, or write $key in powershell it seems like it contains the key and a newline. 

I suspect the new line is the problem here, as the scripts works perfectly if i manually insert the key like this:

# Getting activation object#
$service = get-wmiObject -query 'select * from SoftwareLicensingService'

##### Install product key and activate ####
$service.InstallProductKey("xxx-xxx-xxx-xxx")
$service.RefreshLicenseStatus()


Verify the tampstamp option was used on a signed script

$
0
0

We've run into the issue of the code signing certificate expiring and scripts stop functioning.  I see that the way around this is to use the -timestampserver option but I haven’t been able to verify that this option was used.

set-AuthenticodeSignature script.ps1 $Cert -TimeStampServer "http://timestamp.verisign.com/scripts/timstamp.dll"

To try and verify I ran 

Get-AuthenticodeSignature script.ps1 -Verbose | fl

SignerCertificate      : [Subject]
                                  CN=Code sign certificate owner DC=Contoso, DC=com

                                    [Issuer]
                                    CN=Contoso CA, DC=Contoso, DC=com

                                  [Serial Number]
                                    xxxxxxxxxxxxxxxxxxxxx

                                  [Not Before]
                                    5/5/2016 2:23:16 PM

                                  [Not After]
                                    5/4/2018 2:23:16 PM

                                    [Thumbprint]
                                    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

TimeStamperCertificate :
Status                 : Valid
StatusMessage          : Signature verified.
Path                   : script.ps1
SignatureType          : Authenticode
IsOSBinary             : False

I would have assumed that the get-authenticodeSignature would have listed something different but both results for with and without the timestampserver option look the same using. The only difference I can find is in the file size which about doubles the lines used for the hash. 

Is there a way to verify that a script is signed with the timestampserver option other than the hash length?


Removing driver with powershell

$
0
0

Hi,

I am trying to uninstall a I4600 driver. On the first time, Windows 8.1 did not install the driver. So I install the software driver and everything installed fine.

So I uninstall the software driver and the driver remain.

So I wrote that script:

I will convert later the c:\sovgarde\devcon command to run it with start-process

$id = (Get-CimInstance Win32_PnPEntity | where Description -match 'KODAK i4600 Scanner').pnpDeviceID
$id
$ppid = "{0}{1}" -f '@',$id
$ppid
c:\sovgarde\Devcon.exe status $ppid
c:\sovgarde\Devcon.exe disable $ppid
c:\sovgarde\Devcon.exe remove $ppid

What I see is disabling the device is working correctly and remove seems to be correct to. However in the device manager, the device is there and now active.

Manually in device manager I can remove the device and select remove device driver and then it does not reappear as functionnal (driver missing),

How may I remove the device and prevent it to reappear?

Thanks,

françois


Move-ADObject user account from child to parent domain

$
0
0

Hello Everyone,

I have a need to move a user from a child domain to the parent domain.  While running the below cmdlet I am getting back an error stating "Server is unwilling to process the request".

Move-ADObject -Server dc01.domain.local:3268 -Identity "distinguished name of user" -TargetPath "distinguished path of OU" -TargetServer dc01.domain.local:3268

Can anyone provide an example of how to use move-ADObject to move a user account from a child domain to parent?

I realize I can use ADMT but I need a way to do this programmatically.  Unless ADMT has API to call?

Thanks for any info

Ian...

Migrated documents Internal Links are broken

$
0
0

We are migrating documents from files server to overdrive physical folder for each user. We have notices so many documents containing internal link references become as broke link.

First of all I want to understand what are the possible options are available to re mediate the broken links and how this can be re mediate using PowerShell scripts.

Please advise

Avian

open files in the cloud

$
0
0

I know this is a PowerShell forum but I figured the technical expertise would be found here.

I need to do the following. Machine abc does not have Office installed locally. A user who is logged into machine abc goes to a network share and double clicks on an Office doc (.xlsx, docx etc....) I need that document to launch in Office.Live.com

Now, I can modify the File Association and point any .xlsx or docx file to run a custom PowerShell Script. This PowerShell script looks like this:

(if an Excel file was clicked on.......this is just an example.)

if (Test-Path "C:\Program Files\Microsoft Office 15\root\office15\Excel.exe"){start-sleep -m 1}
ELSE {cmd.exe /c "C:\Program Files\Internet Explorer\iexplore.exe" "https://office.live.com/start/Excel.aspx?"}

My issue is this does not open the document that was actually clicked on, it only opens the portal. How would that be done? So the file could be something like this: \\Server\Share\SubFolder\SubFolder2\Expense Report for January 2017.xlsx

How would you launch that in Office.Live with Powershell?


mqh7

PowerShell doesn't output error - yet nothing is happening.

$
0
0

I have a script that I crafted up to get a list of account that need disabled, then piped the users and move them to a different OU. It doesn't appear to actually be working. It gets all the way down to the "Start-Sleep" - then doesn't continue the script - or do anything to the user specified. Write Verbose tells me 

Cmdlet Write-Verbose at command pipeline position 1

Supply values for the following parameters

message: 

---Script----

# This script will disable all users that are contained within a CSV in Active Directory - Pipe the disabled user and place it into the appropriate OU.
# Create by DR
# January 25th, 2017

##################
#BEGIN VARIABLES
##################
$VerbosePreference = "silentlycontinue"

#Defines the CSV file path to import it
$UsersToDisable = Get-Content "THIS IS WHERE I PUT MY FILE PATH\UsersToDisable.csv"

#Defines the domain and the target domain controller
$LocalDomain = 'THIS IS MY LOCAL DOMAIN'
$TargetDomainController = 'THIS IS MY TARGET DC'

#Defines where to Move Inactive Users
$MoveUsersToOU = 'OUR OU FOR INACTIVE USERS GOES HERE'

#Defines file path to save log locally
$LogPath = "YET ANOTHER LOG PATH\ActiveDirectoryLogs"

##################
#END VARIABLES
##################

#Import Module: Import the Powershell Active Directory module
Import-Module ActiveDirectory

#Timestamp: Create a timestamp for use as part of a directory or file name
$TimeStampBefore = Get-Date -Format s | foreach {$_ -replace ":", "-"} 

#Log Folder - Create a Log Foler if one doesn't already exist
If ( -Not (Test-Path -Path $LogPath)) {New-Item -Path $LogPath -ItemType Directory}

#Load Users: Load list of users into a variable
$UsersToDisable

#Document Before: Document user settings before making changes
$CsvBeforePath = $LogPath+ '\DisableUsers-' +$MoveUsersToOU+ '-' +$TimeStampBefore+ '-before.csv'
foreach ($i in $userstodisable) {Get-ADUser -identity $i | Export-Csv -Path $CsvBeforePath}




ForEach ($i in $UsersToDisable) 
{

#Disable Users: Disable these Active Directory User Accounts and Move to Target Path
foreach ($i in $usertodisable) {Get-ADUser -identity $i | Disable-ADAccount -identity $i | Move-ADObject -TargetPath (Get-ADOrganizationalUnit -Filter 'Name -eq $MoveUsersToOU')} 
Write-Host "Attempting to get AD User, disable, and move to Inactive Users OU" -ForegroundColor Red -BackgroundColor White
Write-Verbose

#Pause: Allow for Active Directory to make replication changes
Write-Host "Waiting 60 seconds for Active Directory to make Replication Changes" -ForegroundColor Cyan -BackgroundColor Blue
Start-Sleep -Seconds 60

# Create a TimeStamp for use as part of a directory file name
$TimeStampAfter = Get-Date -Format s | foreach {$_ -replace ":", "-"}

#Document Users After Making Changes
$CsvAfterPath = $LogPath+'\DisableUsers-'+$MoveUsersToOU+'_'+$TimeStampAfter+'-After.csv'
foreach ($i in $usertodisable) {Get-ADUser -identity $i | Export-Csv -Path $CsvAfterPath}
}
#clear

Viewing all 21975 articles
Browse latest View live


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