Powershell New-Item: How to Accept Confirmation Automatically - powershell

I'm trying to create a new directory on a network drive using a powershell script but it keeps prompting me
"Confirm: Are you sure you want to perform this action ...."
Is there a way to override this so it doesn't ask me since I'm running this script from a web interface.
Here is my call:
New-Item $rollbackDirectory -type Directory -Force
It does the same thing, with or without the -Force parameter
I've also tried this format with no luck
New-Item -name $rollbackName -itemtype directory -path $rollbackdrive -Debug -Force

-confirm need only be specified when you want the cmdlet to prompt you for confirmation. Whether the cmdlet by itself would prompt for confirmation or not depends on the developer of the cmdlet who can set a high, medium, low for the cmdlet based on its effect. Based on the value of $ConfirmPreference you will get the confirmation automatically for a cmdlet. The default value for $ConfirmPreference is high and the level set for New-Item is medium. So if the New-Item is prompting for confirmation, the $ConfirmPreference value must have been changed to medium or low.
Change it using $ConfirmPreference="high" or even $ConfirmPreference="none" to make New-Item not prompt, or your solution of -confirm:$false works as well by overriding the $ConfirmPreference.
Explained perfectly here: http://blogs.msdn.com/b/powershell/archive/2006/12/15/confirmpreference.aspx
Hope this clears it up.

I ended up trying this (even though I read on another SO post that it is not correct):
New-Item $rollbackDirectory -type Directory -Force -Confirm:$false
And it worked! Hope this helps others with the same issue

Related

How do I reference the current logged in user when a script is running?

So, I'm using Desktop Central to run some scripts on a bunch of machines. The script is supposed to open a zip file in the c:\users%USERNAME%\ folder, and decompress it to a folder of my choosing. The idea is to use a single script for many machines, that can leverage the c:\users\LOGGEDONUSER\downloads folder (Default TEAMS download dir). The idea is that each user will download the archive from teams, and a script will decompress and install from each users DOWNLOADS folder.
The issue is that I don't seem to know how to write a script uses a variable representing the username of the logged in user for the -path in my argument.
For instance;
Extract file
Expand-archive -path $home\Downloads\SWANDPDM_SP5.1.zip -DestinationPath C:\temp\swpdminstaller\extracted\ -Force
#Define registry values to modify to allow for no UAC
$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
$Name = 'ConsentPromptBehaviorAdmin'
$Value = '0'
#Run reg change
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force
#Run installer
Invoke-Item C:\temp\swpdminstaller\extracted\SOLIDWORKS_AND_PDM_2021_SP5.1\startswinstall.exe
#Define reg values to change back to default
$RegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
$Name = 'ConsentPromptBehaviorAdmin'
$Value = '5'
#Run reg change
New-ItemProperty -Path $RegistryPath -Name $Name -Value $Value -PropertyType DWORD -Force
This works great if I copy the script to the machine manually, and launch the script as a user. It looks at $home and figures out the correct directory based on whomever is logged in.
However, when it runs as Desktop Central, $home doesn't mean the same location. It comes back with this;
Expand-archive : The path 'C:\Windows\system32\config\systemprofile\Downloads\SWANDPDM_SP5.1.zip' either does not
exist or is not a valid file system path.
At C:\Program Files (x86)\DesktopCentral_Agent\Computer\startup\76507\SWandPDMdecomInstall.ps1:2 char:1
+ Expand-archive -path $home\Downloads\SWANDPDM_SP5.1.zip -DestinationP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Windows\syst...NDPDM_SP5.1.zip:String) [Expand-Archive], InvalidOpe
rationException
+ FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Expand-Archive
I tried using various env variables with no luck. It seems like because it's a "Desktop central" account that's running the script remotely, I can't get it to point to the correct folder in c:\users\NAMEOFLOGGEDINUSER\
So, it thinks $home = 'C:\Windows\system32\config\systemprofile\ instead of c:\users\NAMEOFLOGGEDINUSER\
Is there a way that I can get the username of the current logged on user, assign it to a variable, and then use that variable instead of $home? Keep in mind, it needs to find the logged in user while running the script as the Desktop Central service account. I've tried running the script as various domain admins\system accounts with no luck.
I thought about doing a whoami, writing to a text file, then omitting the domain portion of the output and assigning it to a variable, but there's got to be a better way.
Any help is greatly appreciated!
EDIT: Thought I was on to something, but it didn't work. I tried;
Expand-archive -path $env:HOMEPATH\Downloads\SWANDPDM_SP5.1.zip -DestinationPath C:\temp\swpdminstaller\extracted\ -Force
I see from the comments that you found a workaround. But to answer your original question, you can't get the logged in username from the usual Powershell techniques ($env:USERNAME, whoami, etc.) when you're running the script under a different security context.
But you can check who owns the Explorer.exe process:
$User = (Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'" |
Invoke-CimMethod -MethodName GetOwner).User
The "Desktop central" user will probably not have Explorer running. However, if there are multiple users logged in via RDP sessions this will return an array.

powershell Script to save users profile when they log off their session

I am trying to create a script in PowerShell which would save the users data from this path c:\Users\[user]\Documents when the user log off.
I currently have something which could work for a single nominal user however I'd like to have something which work dynamically for every users. Here is my current script:
Copy-Item -Path C:\Users\username\Documents\ -Destination \\SRVIMP02\save\Username -force -Recurse
If you are wanting to use the current user name instead of a static name, you can leverage $env:username . This should give you the current user name.
In your case the following example should work:
Copy-Item -Path C:\users\$($env:USERNAME)\documents\ -Recurse -Destination \SRVIMP02\save\$($env:USERNAME)\ -Force

Can't remove PowerShell alias via ps1 script

Every time I run a script, I need to remove the curl alias from PowerShell in order to use the actual curl which is installed on my machine.
From PowerShell, I can remove the alias perfectly fine by using: Remove-Item alias:curl
But for some reason, when I put this code into a ps1 script and run that script, the alias is not removed.
Does anyone know why this is the case?
You can also update your profile to remove the alias each time PowerShell starts; $profile is an automatic variable that stores the paths to the PowerShell profiles that are available in the current session.
if (!(Test-Path -Path $profile)) {
New-Item -Path $profile -Force
}
Add-Content -Path $profile -Value "Remove-Item alias:curl"
. $profile

Force Remove a Folder in-use using Powershell

I've created a script which at the end deletes all the associated files, self-destructs by deleting itself, and then it's supposed to delete the folder it is contained in as well.
I've tried several ways of closing Windows Explorer, searching through active processes and killing any related processes, but still cannot successfully delete the folder despite being able to self-destruct the script itself.
Set-Location -Path $PSScriptRoot
Remove-Item -Path $PSScriptRoot\Mobile -Force -Recurse
Remove-Item -Path $PSScriptRoot\NoMobile -Force -Recurse
Remove-Item -Path $MyInvocation.MyCommand.Source -Force -Recurse
Set-Location ..
Remove-Item $foldername -Force -Recurse
The last line throws an error that "The process cannot access the file...because it is being used by another process".
Any thoughts?
This may be not the answer you might be expecting right now but posting it so that it might be helpful if someone comes into this thread.
I happen to face issue in deleting the file then after help from co-worker I found that file was open in the editor or on some other user machine. I got to follow the below document to find out who had the file open and then close those files and tried to perform delete operation and this time it worked as expected. Please find the document to figure out who happen to have the file open which you are trying to delete.
https://techgoeasy.com/how-to-tell-who-has-a-file-open-in-windows/

PowerShell New-Item Positional Parameter Oddities

Given the Microsoft documentation for PowerShell, I can see no reason why the following code should fail with the given error. Then again, PowerShell can fail when a script just gets too long. All the paths are double-quote strings.
##### ALGORITHM Take in keystore path, make a backup in an adjacent directory
$ksPath = $java_store_path.Substring(0, $java_store_path.LastIndexOf('\') + 1)
$backupPath = $ksPath + "backups"
New-Item $backupPath PowerShell -type directory -force
New-Item : A positional parameter cannot be found that accepts argument 'PowerShell'.
https://technet.microsoft.com/en-us/library/ee176914.aspx
New-Item c:\scripts\Windows PowerShell -type directory
If that's valid, mine should be too. I'm running on Server 2012 R2.
The example on that page is just plain wrong. It seems they meant to refer to the path C:\Scripts\WindowsPowerShell or they forgot to quote the directory with spaces in it.
So it should have been one of these:
New-Item c:\scripts\WindowsPowerShell -type directory
New-Item 'c:\scripts\Windows PowerShell' -type directory
New-Item "c:\scripts\Windows PowerShell" -type directory
Ask yourself, what would PowerShell alone have been referring to? What parameter would it have corresponded to?
Edit: as the commenters have pointed out, the example was supposed to show the nameSet parameters, where a separate -Path and -Name are specified, and purportedly PowerShell was supposed to be a value to the -Name parameter. That does look correct. The reason the example didn't work (and yours as well), is because the -Name parameter cannot be specified positionally, which you can see in the MSDN article I linked to below, and in the built-in help:
Type: String
Parameter Sets: nameSet
Aliases:
Required: True
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
In that case, their example should have been something like these:
New-Item c:\scripts\Windows -Name PowerShell -type directory
New-Item -Path c:\scripts\Windows -Name PowerShell -type directory
So reiterating, named parameters would have worked here, and would have avoided confusion.
Generally, you shouldn't be using positional parameters in scripts, unless they're extremely clear (and even then, I'd recommend avoiding).
Using named parameters would have made this easier to figure out. And tab-completion helps with filling in the parameter names and in completing paths (usually with proper quoting too).
I think you should change yours to:
New-Item -Path $backupPath -Type Directory -Force
And looking over that technet article, it's really not so good. The MSDN article on New-Item is better, and this is the information you should see when running Get-Help New-Item as well.
Side question:
Then again, PowerShell can fail when a script just gets too long.
What?